blob: ee1feb5c82375ef89005a2b3bbe2b70ae9d263a5 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
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
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.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"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
36
37namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000039
Nick Lewycky134af912013-02-07 05:08:22 +000040/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000041static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000044 SourceLocation Loc = SourceLocation(),
45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000046 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000047 return ExprError();
48 // If FoundDecl is different from Fn (such as if one is a template
49 // and the other a specialization), make sure DiagnoseUseOfDecl is
50 // called on both.
51 // FIXME: This would be more comprehensively addressed by modifying
52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53 // being used.
54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000055 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000056 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000057 VK_LValue, Loc, LocInfo);
58 if (HadMultipleCandidates)
59 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000060
61 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000062
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000064 E = S.DefaultFunctionArrayConversion(E.take());
65 if (E.isInvalid())
66 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000067 return E;
John McCall7decc9e2010-11-18 06:31:45 +000068}
69
John McCall5c32be02010-08-24 20:38:10 +000070static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
71 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000072 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000073 bool CStyle,
74 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000075
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000076static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
77 QualType &ToType,
78 bool InOverloadResolution,
79 StandardConversionSequence &SCS,
80 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000081static OverloadingResult
82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
83 UserDefinedConversionSequence& User,
84 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000085 bool AllowExplicit,
86 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000087
88
89static ImplicitConversionSequence::CompareKind
90CompareStandardConversionSequences(Sema &S,
91 const StandardConversionSequence& SCS1,
92 const StandardConversionSequence& SCS2);
93
94static ImplicitConversionSequence::CompareKind
95CompareQualificationConversions(Sema &S,
96 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareDerivedToBaseConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionCategory - Retrieve the implicit conversion
107/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +0000108ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109GetConversionCategory(ImplicitConversionKind Kind) {
110 static const ImplicitConversionCategory
111 Category[(int)ICK_Num_Conversion_Kinds] = {
112 ICC_Identity,
113 ICC_Lvalue_Transformation,
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICC_Qualification_Adjustment,
118 ICC_Promotion,
119 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000120 ICC_Promotion,
121 ICC_Conversion,
122 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
127 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000128 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000129 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000130 ICC_Conversion,
131 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 ICC_Conversion
134 };
135 return Category[(int)Kind];
136}
137
138/// GetConversionRank - Retrieve the implicit conversion rank
139/// corresponding to the given implicit conversion kind.
140ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
141 static const ImplicitConversionRank
142 Rank[(int)ICK_Num_Conversion_Kinds] = {
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
147 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000148 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 ICR_Promotion,
150 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000151 ICR_Promotion,
152 ICR_Conversion,
153 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000159 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000160 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000161 ICR_Conversion,
162 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000163 ICR_Complex_Real_Conversion,
164 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000165 ICR_Conversion,
166 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 };
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
173const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000179 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000183 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 "Integral conversion",
185 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000186 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000190 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000191 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000192 "Derived-to-base conversion",
193 "Vector conversion",
194 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000195 "Complex-real conversion",
196 "Block Pointer conversion",
197 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000198 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000199 };
200 return Name[Kind];
201}
202
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000203/// StandardConversionSequence - Set the standard conversion
204/// sequence to the identity conversion.
205void StandardConversionSequence::setAsIdentityConversion() {
206 First = ICK_Identity;
207 Second = ICK_Identity;
208 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000209 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000210 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000211 ReferenceBinding = false;
212 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000213 IsLvalueReference = true;
214 BindsToFunctionLvalue = false;
215 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000216 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000217 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000218 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000219}
220
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// getRank - Retrieve the rank of this standard conversion sequence
222/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
223/// implicit conversions.
224ImplicitConversionRank StandardConversionSequence::getRank() const {
225 ImplicitConversionRank Rank = ICR_Exact_Match;
226 if (GetConversionRank(First) > Rank)
227 Rank = GetConversionRank(First);
228 if (GetConversionRank(Second) > Rank)
229 Rank = GetConversionRank(Second);
230 if (GetConversionRank(Third) > Rank)
231 Rank = GetConversionRank(Third);
232 return Rank;
233}
234
235/// isPointerConversionToBool - Determines whether this conversion is
236/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000237/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 // Note that FromType has not necessarily been transformed by the
241 // array-to-pointer or function-to-pointer implicit conversions, so
242 // check for their presence as well as checking whether FromType is
243 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000244 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000245 (getFromType()->isPointerType() ||
246 getFromType()->isObjCObjectPointerType() ||
247 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000248 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
250 return true;
251
252 return false;
253}
254
Douglas Gregor5c407d92008-10-23 00:40:37 +0000255/// isPointerConversionToVoidPointer - Determines whether this
256/// conversion is a conversion of a pointer to a void pointer. This is
257/// used as part of the ranking of standard conversion sequences (C++
258/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000259bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000260StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000261isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000262 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000263 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000264
265 // Note that FromType has not necessarily been transformed by the
266 // array-to-pointer implicit conversion, so check for its presence
267 // and redo the conversion to get a pointer.
268 if (First == ICK_Array_To_Pointer)
269 FromType = Context.getArrayDecayedType(FromType);
270
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000273 return ToPtrType->getPointeeType()->isVoidType();
274
275 return false;
276}
277
Richard Smith66e05fe2012-01-18 05:21:49 +0000278/// Skip any implicit casts which could be either part of a narrowing conversion
279/// or after one in an implicit conversion.
280static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
282 switch (ICE->getCastKind()) {
283 case CK_NoOp:
284 case CK_IntegralCast:
285 case CK_IntegralToBoolean:
286 case CK_IntegralToFloating:
287 case CK_FloatingToIntegral:
288 case CK_FloatingToBoolean:
289 case CK_FloatingCast:
290 Converted = ICE->getSubExpr();
291 continue;
292
293 default:
294 return Converted;
295 }
296 }
297
298 return Converted;
299}
300
301/// Check if this standard conversion sequence represents a narrowing
302/// conversion, according to C++11 [dcl.init.list]p7.
303///
304/// \param Ctx The AST context.
305/// \param Converted The result of applying this standard conversion sequence.
306/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
307/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000308/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
309/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000310NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000311StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
312 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000313 APValue &ConstantValue,
314 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000316
317 // C++11 [dcl.init.list]p7:
318 // A narrowing conversion is an implicit conversion ...
319 QualType FromType = getToType(0);
320 QualType ToType = getToType(1);
321 switch (Second) {
322 // -- from a floating-point type to an integer type, or
323 //
324 // -- from an integer type or unscoped enumeration type to a floating-point
325 // type, except where the source is a constant expression and the actual
326 // value after conversion will fit into the target type and will produce
327 // the original value when converted back to the original type, or
328 case ICK_Floating_Integral:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
332 llvm::APSInt IntConstantValue;
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer &&
335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
336 // Convert the integer to the floating type.
337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
339 llvm::APFloat::rmNearestTiesToEven);
340 // And back.
341 llvm::APSInt ConvertedValue = IntConstantValue;
342 bool ignored;
343 Result.convertToInteger(ConvertedValue,
344 llvm::APFloat::rmTowardZero, &ignored);
345 // If the resulting value is different, this was a narrowing conversion.
346 if (IntConstantValue != ConvertedValue) {
347 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000348 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000349 return NK_Constant_Narrowing;
350 }
351 } else {
352 // Variables are always narrowings.
353 return NK_Variable_Narrowing;
354 }
355 }
356 return NK_Not_Narrowing;
357
358 // -- from long double to double or float, or from double to float, except
359 // where the source is a constant expression and the actual value after
360 // conversion is within the range of values that can be represented (even
361 // if it cannot be represented exactly), or
362 case ICK_Floating_Conversion:
363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
365 // FromType is larger than ToType.
366 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
368 // Constant!
369 assert(ConstantValue.isFloat());
370 llvm::APFloat FloatVal = ConstantValue.getFloat();
371 // Convert the source value into the target type.
372 bool ignored;
373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
374 Ctx.getFloatTypeSemantics(ToType),
375 llvm::APFloat::rmNearestTiesToEven, &ignored);
376 // If there was no overflow, the source value is within the range of
377 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000378 if (ConvertStatus & llvm::APFloat::opOverflow) {
379 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000381 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000382 } else {
383 return NK_Variable_Narrowing;
384 }
385 }
386 return NK_Not_Narrowing;
387
388 // -- from an integer type or unscoped enumeration type to an integer type
389 // that cannot represent all the values of the original type, except where
390 // the source is a constant expression and the actual value after
391 // conversion will fit into the target type and will produce the original
392 // value when converted back to the original type.
393 case ICK_Boolean_Conversion: // Bools are integers too.
394 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
395 // Boolean conversions can be from pointers and pointers to members
396 // [conv.bool], and those aren't considered narrowing conversions.
397 return NK_Not_Narrowing;
398 } // Otherwise, fall through to the integral case.
399 case ICK_Integral_Conversion: {
400 assert(FromType->isIntegralOrUnscopedEnumerationType());
401 assert(ToType->isIntegralOrUnscopedEnumerationType());
402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
403 const unsigned FromWidth = Ctx.getIntWidth(FromType);
404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
405 const unsigned ToWidth = Ctx.getIntWidth(ToType);
406
407 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000408 (FromWidth == ToWidth && FromSigned != ToSigned) ||
409 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000410 // Not all values of FromType can be represented in ToType.
411 llvm::APSInt InitializerValue;
412 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
414 // Such conversions on variables are always narrowing.
415 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000416 }
417 bool Narrowing = false;
418 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000419 // Negative -> unsigned is narrowing. Otherwise, more bits is never
420 // narrowing.
421 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000422 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000423 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000424 // Add a bit to the InitializerValue so we don't have to worry about
425 // signed vs. unsigned comparisons.
426 InitializerValue = InitializerValue.extend(
427 InitializerValue.getBitWidth() + 1);
428 // Convert the initializer to and from the target width and signed-ness.
429 llvm::APSInt ConvertedValue = InitializerValue;
430 ConvertedValue = ConvertedValue.trunc(ToWidth);
431 ConvertedValue.setIsSigned(ToSigned);
432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
433 ConvertedValue.setIsSigned(InitializerValue.isSigned());
434 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000435 if (ConvertedValue != InitializerValue)
436 Narrowing = true;
437 }
438 if (Narrowing) {
439 ConstantType = Initializer->getType();
440 ConstantValue = APValue(InitializerValue);
441 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000442 }
443 }
444 return NK_Not_Narrowing;
445 }
446
447 default:
448 // Other kinds of conversions are not narrowings.
449 return NK_Not_Narrowing;
450 }
451}
452
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000453/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000454/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000455void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 bool PrintedSomething = false;
458 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000459 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Second != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000468
469 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000470 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000471 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000473 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000475 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 PrintedSomething = true;
477 }
478
479 if (Third != ICK_Identity) {
480 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000488 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 }
490}
491
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000494void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000497 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000500 if (ConversionFunction)
501 OS << '\'' << *ConversionFunction << '\'';
502 else
503 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 }
508}
509
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000512void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000513 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000514 if (isStdInitializerListElement())
515 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 switch (ConversionKind) {
517 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 break;
521 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000522 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000523 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 break;
525 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000526 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000527 break;
John McCall0d1da222010-01-12 00:44:57 +0000528 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000529 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000530 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000531 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000532 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 }
535
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000536 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537}
538
John McCall0d1da222010-01-12 00:44:57 +0000539void AmbiguousConversionSequence::construct() {
540 new (&conversions()) ConversionSet();
541}
542
543void AmbiguousConversionSequence::destruct() {
544 conversions().~ConversionSet();
545}
546
547void
548AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
549 FromTypePtr = O.FromTypePtr;
550 ToTypePtr = O.ToTypePtr;
551 new (&conversions()) ConversionSet(O.conversions());
552}
553
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000555 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000556 // template argument information.
557 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000558 TemplateArgument FirstArg;
559 TemplateArgument SecondArg;
560 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000561 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000562 // template parameter and template argument information.
563 struct DFIParamWithArguments : DFIArguments {
564 TemplateParameter Param;
565 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568/// \brief Convert from Sema's representation of template deduction information
569/// to the form used in overload-candidate information.
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
571 Sema::TemplateDeductionResult TDK,
572 TemplateDeductionInfo &Info) {
573 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000575 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 Result.Data = 0;
577 switch (TDK) {
578 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000579 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000581 case Sema::TDK_TooManyArguments:
582 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000586 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000587 Result.Data = Info.Param.getOpaqueValue();
588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
623
Richard Smith44ecdbd2013-01-31 05:19:49 +0000624 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 return Result;
629}
John McCall0d1da222010-01-12 00:44:57 +0000630
Larisse Voufo98b20f12013-07-19 23:00:19 +0000631void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
633 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000634 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 case Sema::TDK_InstantiationDepth:
636 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000637 case Sema::TDK_TooManyArguments:
638 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000639 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000640 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000644 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000645 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000646 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000647 Data = 0;
648 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000649
650 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000651 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
654 Diag->~PartialDiagnosticAt();
655 HasDiagnostic = false;
656 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor461761d2010-05-08 18:20:53 +0000659 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 break;
662 }
663}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Larisse Voufo98b20f12013-07-19 23:00:19 +0000665PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000666 if (HasDiagnostic)
667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
668 return 0;
669}
670
Larisse Voufo98b20f12013-07-19 23:00:19 +0000671TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
673 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000674 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000675 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000676 case Sema::TDK_TooManyArguments:
677 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000678 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000679 case Sema::TDK_NonDeducedMismatch:
680 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000681 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000683 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000686
687 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000688 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000689 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000691 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000692 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693 break;
694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 return TemplateParameter();
697}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregord09efd42010-05-08 20:07:26 +0000713
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Richard Smith44ecdbd2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
753 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000754 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 case Sema::TDK_InstantiationDepth:
756 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000757 case Sema::TDK_TooManyArguments:
758 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000759 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000760 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000761 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000762 return 0;
763
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000764 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000765 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000766 case Sema::TDK_NonDeducedMismatch:
767 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768
Douglas Gregor461761d2010-05-08 18:20:53 +0000769 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000770 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000771 break;
772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774 return 0;
775}
776
Larisse Voufo98b20f12013-07-19 23:00:19 +0000777Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000778 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
779 Sema::TDK_FailedOverloadResolution)
780 return static_cast<Expr*>(Data);
781
782 return 0;
783}
784
Benjamin Kramer97e59492012-10-09 15:52:25 +0000785void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000786 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
788 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
790 i->DeductionFailure.Destroy();
791 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000792}
793
794void OverloadCandidateSet::clear() {
795 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000796 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000797 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000798 Functions.clear();
799}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
John McCall4124c492011-10-17 18:40:02 +0000801namespace {
802 class UnbridgedCastsSet {
803 struct Entry {
804 Expr **Addr;
805 Expr *Saved;
806 };
807 SmallVector<Entry, 2> Entries;
808
809 public:
810 void save(Sema &S, Expr *&E) {
811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
812 Entry entry = { &E, E };
813 Entries.push_back(entry);
814 E = S.stripARCUnbridgedCast(E);
815 }
816
817 void restore() {
818 for (SmallVectorImpl<Entry>::iterator
819 i = Entries.begin(), e = Entries.end(); i != e; ++i)
820 *i->Addr = i->Saved;
821 }
822 };
823}
824
825/// checkPlaceholderForOverload - Do any interesting placeholder-like
826/// preprocessing on the given expression.
827///
828/// \param unbridgedCasts a collection to which to add unbridged casts;
829/// without this, they will be immediately diagnosed as errors
830///
831/// Return true on unrecoverable error.
832static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
833 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
835 // We can't handle overloaded expressions here because overload
836 // resolution might reasonably tweak them.
837 if (placeholder->getKind() == BuiltinType::Overload) return false;
838
839 // If the context potentially accepts unbridged ARC casts, strip
840 // the unbridged cast and add it to the collection for later restoration.
841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
842 unbridgedCasts) {
843 unbridgedCasts->save(S, E);
844 return false;
845 }
846
847 // Go ahead and check everything else.
848 ExprResult result = S.CheckPlaceholderExpr(E);
849 if (result.isInvalid())
850 return true;
851
852 E = result.take();
853 return false;
854 }
855
856 // Nothing to do.
857 return false;
858}
859
860/// checkArgPlaceholdersForOverload - Check a set of call operands for
861/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000862static bool checkArgPlaceholdersForOverload(Sema &S,
863 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000864 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000865 for (unsigned i = 0, e = Args.size(); i != e; ++i)
866 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000867 return true;
868
869 return false;
870}
871
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000873// overload of the declarations in Old. This routine returns false if
874// New and Old cannot be overloaded, e.g., if New has the same
875// signature as some function in Old (C++ 1.3.10) or if the Old
876// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000877// it does return false, MatchedDecl will point to the decl that New
878// cannot be overloaded with. This decl may be a UsingShadowDecl on
879// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880//
881// Example: Given the following input:
882//
883// void f(int, float); // #1
884// void f(int, int); // #2
885// int f(int, int); // #3
886//
887// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000888// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889//
John McCall3d988d92009-12-02 08:47:38 +0000890// When we process #2, Old contains only the FunctionDecl for #1. By
891// comparing the parameter types, we see that #1 and #2 are overloaded
892// (since they have different signatures), so this routine returns
893// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000894//
John McCall3d988d92009-12-02 08:47:38 +0000895// When we process #3, Old is an overload set containing #1 and #2. We
896// compare the signatures of #3 to #1 (they're overloaded, so we do
897// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
898// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899// signature), IsOverload returns false and MatchedDecl will be set to
900// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000901//
902// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
903// into a class by a using declaration. The rules for whether to hide
904// shadow declarations ignore some properties which otherwise figure
905// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000906Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000907Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
908 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000909 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000910 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000911 NamedDecl *OldD = *I;
912
913 bool OldIsUsingDecl = false;
914 if (isa<UsingShadowDecl>(OldD)) {
915 OldIsUsingDecl = true;
916
917 // We can always introduce two using declarations into the same
918 // context, even if they have identical signatures.
919 if (NewIsUsingDecl) continue;
920
921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
922 }
923
924 // If either declaration was introduced by a using declaration,
925 // we'll need to use slightly different rules for matching.
926 // Essentially, these rules are the normal rules, except that
927 // function templates hide function templates with different
928 // return types or template parameter lists.
929 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
931 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000932
Alp Tokera2794f92014-01-22 07:29:52 +0000933 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000934 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
935 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
937 continue;
938 }
939
Alp Tokera2794f92014-01-22 07:29:52 +0000940 if (!isa<FunctionTemplateDecl>(OldD) &&
941 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000942 continue;
943
John McCalldaa3d6b2009-12-09 03:35:25 +0000944 Match = *I;
945 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000946 }
John McCalla8987a2942010-11-10 03:01:53 +0000947 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000948 // We can overload with these, which can show up when doing
949 // redeclaration checks for UsingDecls.
950 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000951 } else if (isa<TagDecl>(OldD)) {
952 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000953 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
954 // Optimistically assume that an unresolved using decl will
955 // overload; if it doesn't, we'll have to diagnose during
956 // template instantiation.
957 } else {
John McCall1f82f242009-11-18 22:49:29 +0000958 // (C++ 13p1):
959 // Only function declarations can be overloaded; object and type
960 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000961 Match = *I;
962 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000963 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000964 }
John McCall1f82f242009-11-18 22:49:29 +0000965
John McCalldaa3d6b2009-12-09 03:35:25 +0000966 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000967}
968
Richard Smithac974a32013-06-30 09:48:50 +0000969bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
970 bool UseUsingDeclRules) {
971 // C++ [basic.start.main]p2: This function shall not be overloaded.
972 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000973 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000974
David Majnemerc729b0b2013-09-16 22:44:20 +0000975 // MSVCRT user defined entry points cannot be overloaded.
976 if (New->isMSVCRTEntryPoint())
977 return false;
978
John McCall1f82f242009-11-18 22:49:29 +0000979 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
980 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
981
982 // C++ [temp.fct]p2:
983 // A function template can be overloaded with other function templates
984 // and with normal (non-template) functions.
985 if ((OldTemplate == 0) != (NewTemplate == 0))
986 return true;
987
988 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000989 QualType OldQType = Context.getCanonicalType(Old->getType());
990 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000991
992 // Compare the signatures (C++ 1.3.10) of the two functions to
993 // determine whether they are overloads. If we find any mismatch
994 // in the signature, they are overloads.
995
996 // If either of these functions is a K&R-style function (no
997 // prototype), then we consider them to have matching signatures.
998 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
999 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1000 return false;
1001
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001002 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1003 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001004
1005 // The signature of a function includes the types of its
1006 // parameters (C++ 1.3.10), which includes the presence or absence
1007 // of the ellipsis; see C++ DR 357).
1008 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001009 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001010 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001011 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001012 return true;
1013
1014 // C++ [temp.over.link]p4:
1015 // The signature of a function template consists of its function
1016 // signature, its return type and its template parameter list. The names
1017 // of the template parameters are significant only for establishing the
1018 // relationship between the template parameters and the rest of the
1019 // signature.
1020 //
1021 // We check the return type and template parameter lists for function
1022 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001023 //
1024 // However, we don't consider either of these when deciding whether
1025 // a member introduced by a shadow declaration is hidden.
1026 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001027 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1028 OldTemplate->getTemplateParameters(),
1029 false, TPL_TemplateMatch) ||
Alp Toker314cc812014-01-25 16:55:45 +00001030 OldType->getReturnType() != NewType->getReturnType()))
John McCall1f82f242009-11-18 22:49:29 +00001031 return true;
1032
1033 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001034 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001035 //
1036 // As part of this, also check whether one of the member functions
1037 // is static, in which case they are not overloads (C++
1038 // 13.1p2). While not part of the definition of the signature,
1039 // this check is important to determine whether these functions
1040 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001041 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1042 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001043 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001044 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1045 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1046 if (!UseUsingDeclRules &&
1047 (OldMethod->getRefQualifier() == RQ_None ||
1048 NewMethod->getRefQualifier() == RQ_None)) {
1049 // C++0x [over.load]p2:
1050 // - Member function declarations with the same name and the same
1051 // parameter-type-list as well as member function template
1052 // declarations with the same name, the same parameter-type-list, and
1053 // the same template parameter lists cannot be overloaded if any of
1054 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001055 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001056 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001057 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001058 }
1059 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061
Richard Smith574f4f62013-01-14 05:37:29 +00001062 // We may not have applied the implicit const for a constexpr member
1063 // function yet (because we haven't yet resolved whether this is a static
1064 // or non-static member function). Add it now, on the assumption that this
1065 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001066 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001067 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithac974a32013-06-30 09:48:50 +00001068 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001069 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001070 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001071
1072 // We do not allow overloading based off of '__restrict'.
1073 OldQuals &= ~Qualifiers::Restrict;
1074 NewQuals &= ~Qualifiers::Restrict;
1075 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001076 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001079 // enable_if attributes are an order-sensitive part of the signature.
1080 for (specific_attr_iterator<EnableIfAttr>
1081 NewI = New->specific_attr_begin<EnableIfAttr>(),
1082 NewE = New->specific_attr_end<EnableIfAttr>(),
1083 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1084 OldE = Old->specific_attr_end<EnableIfAttr>();
1085 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1086 if (NewI == NewE || OldI == OldE)
1087 return true;
1088 llvm::FoldingSetNodeID NewID, OldID;
1089 NewI->getCond()->Profile(NewID, Context, true);
1090 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001091 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001092 return true;
1093 }
1094
John McCall1f82f242009-11-18 22:49:29 +00001095 // The signatures match; this is not an overload.
1096 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001097}
1098
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001099/// \brief Checks availability of the function depending on the current
1100/// function context. Inside an unavailable function, unavailability is ignored.
1101///
1102/// \returns true if \arg FD is unavailable and current context is inside
1103/// an available function, false otherwise.
1104bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1105 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1106}
1107
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001108/// \brief Tries a user-defined conversion from From to ToType.
1109///
1110/// Produces an implicit conversion sequence for when a standard conversion
1111/// is not an option. See TryImplicitConversion for more information.
1112static ImplicitConversionSequence
1113TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1114 bool SuppressUserConversions,
1115 bool AllowExplicit,
1116 bool InOverloadResolution,
1117 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001118 bool AllowObjCWritebackConversion,
1119 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001120 ImplicitConversionSequence ICS;
1121
1122 if (SuppressUserConversions) {
1123 // We're not in the case above, so there is no conversion that
1124 // we can perform.
1125 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1126 return ICS;
1127 }
1128
1129 // Attempt user-defined conversion.
1130 OverloadCandidateSet Conversions(From->getExprLoc());
1131 OverloadingResult UserDefResult
1132 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001133 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134
1135 if (UserDefResult == OR_Success) {
1136 ICS.setUserDefined();
Ismail Pazarbasidf1a2802014-01-24 13:16:17 +00001137 ICS.UserDefined.Before.setAsIdentityConversion();
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001138 // C++ [over.ics.user]p4:
1139 // A conversion of an expression of class type to the same class
1140 // type is given Exact Match rank, and a conversion of an
1141 // expression of class type to a base class of that type is
1142 // given Conversion rank, in spite of the fact that a copy
1143 // constructor (i.e., a user-defined conversion function) is
1144 // called for those cases.
1145 if (CXXConstructorDecl *Constructor
1146 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1147 QualType FromCanon
1148 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1149 QualType ToCanon
1150 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1151 if (Constructor->isCopyConstructor() &&
1152 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1153 // Turn this into a "standard" conversion sequence, so that it
1154 // gets ranked with standard conversion sequences.
1155 ICS.setStandard();
1156 ICS.Standard.setAsIdentityConversion();
1157 ICS.Standard.setFromType(From->getType());
1158 ICS.Standard.setAllToTypes(ToType);
1159 ICS.Standard.CopyConstructor = Constructor;
1160 if (ToCanon != FromCanon)
1161 ICS.Standard.Second = ICK_Derived_To_Base;
1162 }
1163 }
1164
1165 // C++ [over.best.ics]p4:
1166 // However, when considering the argument of a user-defined
1167 // conversion function that is a candidate by 13.3.1.3 when
1168 // invoked for the copying of the temporary in the second step
1169 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1170 // 13.3.1.6 in all cases, only standard conversion sequences and
1171 // ellipsis conversion sequences are allowed.
1172 if (SuppressUserConversions && ICS.isUserDefined()) {
1173 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1174 }
1175 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1176 ICS.setAmbiguous();
1177 ICS.Ambiguous.setFromType(From->getType());
1178 ICS.Ambiguous.setToType(ToType);
1179 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1180 Cand != Conversions.end(); ++Cand)
1181 if (Cand->Viable)
1182 ICS.Ambiguous.addConversion(Cand->Function);
1183 } else {
1184 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1185 }
1186
1187 return ICS;
1188}
1189
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001190/// TryImplicitConversion - Attempt to perform an implicit conversion
1191/// from the given expression (Expr) to the given type (ToType). This
1192/// function returns an implicit conversion sequence that can be used
1193/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001194///
1195/// void f(float f);
1196/// void g(int i) { f(i); }
1197///
1198/// this routine would produce an implicit conversion sequence to
1199/// describe the initialization of f from i, which will be a standard
1200/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1201/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1202//
1203/// Note that this routine only determines how the conversion can be
1204/// performed; it does not actually perform the conversion. As such,
1205/// it will not produce any diagnostics if no conversion is available,
1206/// but will instead return an implicit conversion sequence of kind
1207/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001208///
1209/// If @p SuppressUserConversions, then user-defined conversions are
1210/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001211/// If @p AllowExplicit, then explicit user-defined conversions are
1212/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001213///
1214/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1215/// writeback conversion, which allows __autoreleasing id* parameters to
1216/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001217static ImplicitConversionSequence
1218TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1219 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001220 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001221 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001222 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001223 bool AllowObjCWritebackConversion,
1224 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001225 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001226 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001227 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001228 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001229 return ICS;
1230 }
1231
David Blaikiebbafb8a2012-03-11 07:00:24 +00001232 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001233 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001234 return ICS;
1235 }
1236
Douglas Gregor836a7e82010-08-11 02:15:33 +00001237 // C++ [over.ics.user]p4:
1238 // A conversion of an expression of class type to the same class
1239 // type is given Exact Match rank, and a conversion of an
1240 // expression of class type to a base class of that type is
1241 // given Conversion rank, in spite of the fact that a copy/move
1242 // constructor (i.e., a user-defined conversion function) is
1243 // called for those cases.
1244 QualType FromType = From->getType();
1245 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001246 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1247 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001248 ICS.setStandard();
1249 ICS.Standard.setAsIdentityConversion();
1250 ICS.Standard.setFromType(FromType);
1251 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001252
Douglas Gregor5ab11652010-04-17 22:01:05 +00001253 // We don't actually check at this point whether there is a valid
1254 // copy/move constructor, since overloading just assumes that it
1255 // exists. When we actually perform initialization, we'll find the
1256 // appropriate constructor to copy the returned object, if needed.
1257 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001258
Douglas Gregor5ab11652010-04-17 22:01:05 +00001259 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001260 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001261 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001262
Douglas Gregor836a7e82010-08-11 02:15:33 +00001263 return ICS;
1264 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001265
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001266 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1267 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001268 AllowObjCWritebackConversion,
1269 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001270}
1271
John McCall31168b02011-06-15 23:02:42 +00001272ImplicitConversionSequence
1273Sema::TryImplicitConversion(Expr *From, QualType ToType,
1274 bool SuppressUserConversions,
1275 bool AllowExplicit,
1276 bool InOverloadResolution,
1277 bool CStyle,
1278 bool AllowObjCWritebackConversion) {
1279 return clang::TryImplicitConversion(*this, From, ToType,
1280 SuppressUserConversions, AllowExplicit,
1281 InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001282 AllowObjCWritebackConversion,
1283 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001284}
1285
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001286/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001287/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001288/// converted expression. Flavor is the kind of conversion we're
1289/// performing, used in the error message. If @p AllowExplicit,
1290/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001291ExprResult
1292Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001293 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001294 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001295 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001296}
1297
John Wiegley01296292011-04-08 18:41:53 +00001298ExprResult
1299Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001300 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001301 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001302 if (checkPlaceholderForOverload(*this, From))
1303 return ExprError();
1304
John McCall31168b02011-06-15 23:02:42 +00001305 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1306 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001307 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001308 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001309 if (getLangOpts().ObjC1)
1310 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1311 ToType, From->getType(), From);
John McCall5c32be02010-08-24 20:38:10 +00001312 ICS = clang::TryImplicitConversion(*this, From, ToType,
1313 /*SuppressUserConversions=*/false,
1314 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001315 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001316 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001317 AllowObjCWritebackConversion,
1318 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001319 return PerformImplicitConversion(From, ToType, ICS, Action);
1320}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001321
1322/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001323/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001324bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1325 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001326 if (Context.hasSameUnqualifiedType(FromType, ToType))
1327 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001328
John McCall991eb4b2010-12-21 00:44:39 +00001329 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1330 // where F adds one of the following at most once:
1331 // - a pointer
1332 // - a member pointer
1333 // - a block pointer
1334 CanQualType CanTo = Context.getCanonicalType(ToType);
1335 CanQualType CanFrom = Context.getCanonicalType(FromType);
1336 Type::TypeClass TyClass = CanTo->getTypeClass();
1337 if (TyClass != CanFrom->getTypeClass()) return false;
1338 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1339 if (TyClass == Type::Pointer) {
1340 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1341 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1342 } else if (TyClass == Type::BlockPointer) {
1343 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1344 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1345 } else if (TyClass == Type::MemberPointer) {
1346 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1347 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1348 } else {
1349 return false;
1350 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001351
John McCall991eb4b2010-12-21 00:44:39 +00001352 TyClass = CanTo->getTypeClass();
1353 if (TyClass != CanFrom->getTypeClass()) return false;
1354 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1355 return false;
1356 }
1357
1358 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1359 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1360 if (!EInfo.getNoReturn()) return false;
1361
1362 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1363 assert(QualType(FromFn, 0).isCanonical());
1364 if (QualType(FromFn, 0) != CanTo) return false;
1365
1366 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001367 return true;
1368}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001369
Douglas Gregor46188682010-05-18 22:42:18 +00001370/// \brief Determine whether the conversion from FromType to ToType is a valid
1371/// vector conversion.
1372///
1373/// \param ICK Will be set to the vector conversion kind, if this is a vector
1374/// conversion.
John McCall9b595db2014-02-04 23:58:19 +00001375static bool IsVectorConversion(Sema &S, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001376 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001377 // We need at least one of these types to be a vector type to have a vector
1378 // conversion.
1379 if (!ToType->isVectorType() && !FromType->isVectorType())
1380 return false;
1381
1382 // Identical types require no conversions.
John McCall9b595db2014-02-04 23:58:19 +00001383 if (S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor46188682010-05-18 22:42:18 +00001384 return false;
1385
1386 // There are no conversions between extended vector types, only identity.
1387 if (ToType->isExtVectorType()) {
1388 // There are no conversions between extended vector types other than the
1389 // identity conversion.
1390 if (FromType->isExtVectorType())
1391 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001392
Douglas Gregor46188682010-05-18 22:42:18 +00001393 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001394 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001395 ICK = ICK_Vector_Splat;
1396 return true;
1397 }
1398 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001399
1400 // We can perform the conversion between vector types in the following cases:
1401 // 1)vector types are equivalent AltiVec and GCC vector types
1402 // 2)lax vector conversions are permitted and the vector types are of the
1403 // same size
1404 if (ToType->isVectorType() && FromType->isVectorType()) {
John McCall9b595db2014-02-04 23:58:19 +00001405 if (S.Context.areCompatibleVectorTypes(FromType, ToType) ||
1406 S.isLaxVectorConversion(FromType, ToType)) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001407 ICK = ICK_Vector_Conversion;
1408 return true;
1409 }
Douglas Gregor46188682010-05-18 22:42:18 +00001410 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001411
Douglas Gregor46188682010-05-18 22:42:18 +00001412 return false;
1413}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001415static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1416 bool InOverloadResolution,
1417 StandardConversionSequence &SCS,
1418 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001419
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001420/// IsStandardConversion - Determines whether there is a standard
1421/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1422/// expression From to the type ToType. Standard conversion sequences
1423/// only consider non-class types; for conversions that involve class
1424/// types, use TryImplicitConversion. If a conversion exists, SCS will
1425/// contain the standard conversion sequence required to perform this
1426/// conversion and this routine will return true. Otherwise, this
1427/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001428static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1429 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001430 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001431 bool CStyle,
1432 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001433 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001435 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001436 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001437 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001438 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001439 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001440
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001441 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001442 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001443 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001444 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001445 return false;
1446
Mike Stump11289f42009-09-09 15:08:12 +00001447 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001448 }
1449
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001450 // The first conversion can be an lvalue-to-rvalue conversion,
1451 // array-to-pointer conversion, or function-to-pointer conversion
1452 // (C++ 4p1).
1453
John McCall5c32be02010-08-24 20:38:10 +00001454 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001455 DeclAccessPair AccessPair;
1456 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001457 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001458 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001459 // We were able to resolve the address of the overloaded function,
1460 // so we can convert to the type of that function.
1461 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001462
1463 // we can sometimes resolve &foo<int> regardless of ToType, so check
1464 // if the type matches (identity) or we are converting to bool
1465 if (!S.Context.hasSameUnqualifiedType(
1466 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1467 QualType resultTy;
1468 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001469 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001470 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1471 // otherwise, only a boolean conversion is standard
1472 if (!ToType->isBooleanType())
1473 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
Chandler Carruthffce2452011-03-29 08:08:18 +00001476 // Check if the "from" expression is taking the address of an overloaded
1477 // function and recompute the FromType accordingly. Take advantage of the
1478 // fact that non-static member functions *must* have such an address-of
1479 // expression.
1480 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1481 if (Method && !Method->isStatic()) {
1482 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1483 "Non-unary operator on non-static member address");
1484 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1485 == UO_AddrOf &&
1486 "Non-address-of operator on non-static member address");
1487 const Type *ClassType
1488 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1489 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001490 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1491 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1492 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001493 "Non-address-of operator for overloaded function expression");
1494 FromType = S.Context.getPointerType(FromType);
1495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496
Douglas Gregor980fb162010-04-29 18:24:40 +00001497 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001498 assert(S.Context.hasSameType(
1499 FromType,
1500 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001501 } else {
1502 return false;
1503 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001504 }
John McCall154a2fd2011-08-30 00:57:29 +00001505 // Lvalue-to-rvalue conversion (C++11 4.1):
1506 // A glvalue (3.10) of a non-function, non-array type T can
1507 // be converted to a prvalue.
1508 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001509 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001510 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001511 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001512 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001513
Douglas Gregorc79862f2012-04-12 17:51:55 +00001514 // C11 6.3.2.1p2:
1515 // ... if the lvalue has atomic type, the value has the non-atomic version
1516 // of the type of the lvalue ...
1517 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1518 FromType = Atomic->getValueType();
1519
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001520 // If T is a non-class type, the type of the rvalue is the
1521 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001522 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1523 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001524 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001525 } else if (FromType->isArrayType()) {
1526 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001528
1529 // An lvalue or rvalue of type "array of N T" or "array of unknown
1530 // bound of T" can be converted to an rvalue of type "pointer to
1531 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001532 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533
John McCall5c32be02010-08-24 20:38:10 +00001534 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001535 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001536 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537
1538 // For the purpose of ranking in overload resolution
1539 // (13.3.3.1.1), this conversion is considered an
1540 // array-to-pointer conversion followed by a qualification
1541 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 SCS.Second = ICK_Identity;
1543 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001544 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001545 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547 }
John McCall086a4642010-11-24 05:12:34 +00001548 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001549 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001550 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551
1552 // An lvalue of function type T can be converted to an rvalue of
1553 // type "pointer to T." The result is a pointer to the
1554 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001555 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001556 } else {
1557 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001560 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561
1562 // The second conversion can be an integral promotion, floating
1563 // point promotion, integral conversion, floating point conversion,
1564 // floating-integral conversion, pointer conversion,
1565 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001566 // For overloading in C, this can also be a "compatible-type"
1567 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001568 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001569 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001570 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571 // The unqualified versions of the types are the same: there's no
1572 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001573 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001574 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001575 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001576 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001577 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001578 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001579 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001580 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001582 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001583 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001584 SCS.Second = ICK_Complex_Promotion;
1585 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001586 } else if (ToType->isBooleanType() &&
1587 (FromType->isArithmeticType() ||
1588 FromType->isAnyPointerType() ||
1589 FromType->isBlockPointerType() ||
1590 FromType->isMemberPointerType() ||
1591 FromType->isNullPtrType())) {
1592 // Boolean conversions (C++ 4.12).
1593 SCS.Second = ICK_Boolean_Conversion;
1594 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001595 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001596 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001597 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001598 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001599 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001600 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001601 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001602 SCS.Second = ICK_Complex_Conversion;
1603 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001604 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1605 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001606 // Complex-real conversions (C99 6.3.1.7)
1607 SCS.Second = ICK_Complex_Real;
1608 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001609 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001610 // Floating point conversions (C++ 4.8).
1611 SCS.Second = ICK_Floating_Conversion;
1612 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001613 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001614 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001615 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001616 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001617 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001618 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001620 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001621 SCS.Second = ICK_Block_Pointer_Conversion;
1622 } else if (AllowObjCWritebackConversion &&
1623 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1624 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001625 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1626 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001627 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001628 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001629 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001630 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001632 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001633 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001634 SCS.Second = ICK_Pointer_Member;
John McCall9b595db2014-02-04 23:58:19 +00001635 } else if (IsVectorConversion(S, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001636 SCS.Second = SecondICK;
1637 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001638 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001639 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001640 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001641 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001642 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001643 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001644 // Treat a conversion that strips "noreturn" as an identity conversion.
1645 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001646 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1647 InOverloadResolution,
1648 SCS, CStyle)) {
1649 SCS.Second = ICK_TransparentUnionConversion;
1650 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001651 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1652 CStyle)) {
1653 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001654 // appropriately.
1655 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001656 } else if (ToType->isEventT() &&
1657 From->isIntegerConstantExpr(S.getASTContext()) &&
1658 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1659 SCS.Second = ICK_Zero_Event_Conversion;
1660 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001661 } else {
1662 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001663 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001665 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001666
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001667 QualType CanonFrom;
1668 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001670 bool ObjCLifetimeConversion;
1671 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1672 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001674 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001676 CanonFrom = S.Context.getCanonicalType(FromType);
1677 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 } else {
1679 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001680 SCS.Third = ICK_Identity;
1681
Mike Stump11289f42009-09-09 15:08:12 +00001682 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683 // [...] Any difference in top-level cv-qualification is
1684 // subsumed by the initialization itself and does not constitute
1685 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001686 CanonFrom = S.Context.getCanonicalType(FromType);
1687 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001689 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001690 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001691 FromType = ToType;
1692 CanonFrom = CanonTo;
1693 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001695 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001696
1697 // If we have not converted the argument type to the parameter type,
1698 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001699 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001700 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001702 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001703}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001704
1705static bool
1706IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1707 QualType &ToType,
1708 bool InOverloadResolution,
1709 StandardConversionSequence &SCS,
1710 bool CStyle) {
1711
1712 const RecordType *UT = ToType->getAsUnionType();
1713 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1714 return false;
1715 // The field to initialize within the transparent union.
1716 RecordDecl *UD = UT->getDecl();
1717 // It's compatible if the expression matches any of the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001718 for (const auto *it : UD->fields()) {
John McCall31168b02011-06-15 23:02:42 +00001719 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1720 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001721 ToType = it->getType();
1722 return true;
1723 }
1724 }
1725 return false;
1726}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001727
1728/// IsIntegralPromotion - Determines whether the conversion from the
1729/// expression From (whose potentially-adjusted type is FromType) to
1730/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1731/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001732bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001733 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001734 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001735 if (!To) {
1736 return false;
1737 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001738
1739 // An rvalue of type char, signed char, unsigned char, short int, or
1740 // unsigned short int can be converted to an rvalue of type int if
1741 // int can represent all the values of the source type; otherwise,
1742 // the source rvalue can be converted to an rvalue of type unsigned
1743 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001744 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1745 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001746 if (// We can promote any signed, promotable integer type to an int
1747 (FromType->isSignedIntegerType() ||
1748 // We can promote any unsigned integer type whose size is
1749 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001750 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001751 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001752 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001753 }
1754
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001755 return To->getKind() == BuiltinType::UInt;
1756 }
1757
Richard Smithb9c5a602012-09-13 21:18:54 +00001758 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001759 // A prvalue of an unscoped enumeration type whose underlying type is not
1760 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1761 // following types that can represent all the values of the enumeration
1762 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1763 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001764 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001765 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001766 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001767 // with lowest integer conversion rank (4.13) greater than the rank of long
1768 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001769 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001770 // C++11 [conv.prom]p4:
1771 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1772 // can be converted to a prvalue of its underlying type. Moreover, if
1773 // integral promotion can be applied to its underlying type, a prvalue of an
1774 // unscoped enumeration type whose underlying type is fixed can also be
1775 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001776 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1777 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1778 // provided for a scoped enumeration.
1779 if (FromEnumType->getDecl()->isScoped())
1780 return false;
1781
Richard Smithb9c5a602012-09-13 21:18:54 +00001782 // We can perform an integral promotion to the underlying type of the enum,
1783 // even if that's not the promoted type.
1784 if (FromEnumType->getDecl()->isFixed()) {
1785 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1786 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1787 IsIntegralPromotion(From, Underlying, ToType);
1788 }
1789
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001790 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001792 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001793 return Context.hasSameUnqualifiedType(ToType,
1794 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001795 }
John McCall56774992009-12-09 09:09:27 +00001796
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001797 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001798 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1799 // to an rvalue a prvalue of the first of the following types that can
1800 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001801 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001802 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001803 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001804 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001805 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001806 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001807 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 // Determine whether the type we're converting from is signed or
1809 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001810 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001811 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001812
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001813 // The types we'll try to promote to, in the appropriate
1814 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001815 QualType PromoteTypes[6] = {
1816 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001817 Context.LongTy, Context.UnsignedLongTy ,
1818 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001819 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001820 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001821 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1822 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001823 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1825 // We found the type that we can promote to. If this is the
1826 // type we wanted, we have a promotion. Otherwise, no
1827 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001828 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001829 }
1830 }
1831 }
1832
1833 // An rvalue for an integral bit-field (9.6) can be converted to an
1834 // rvalue of type int if int can represent all the values of the
1835 // bit-field; otherwise, it can be converted to unsigned int if
1836 // unsigned int can represent all the values of the bit-field. If
1837 // the bit-field is larger yet, no integral promotion applies to
1838 // it. If the bit-field has an enumerated type, it is treated as any
1839 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001840 // FIXME: We should delay checking of bit-fields until we actually perform the
1841 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001842 using llvm::APSInt;
1843 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001844 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001845 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001846 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001847 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1848 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1849 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001850
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001851 // Are we promoting to an int from a bitfield that fits in an int?
1852 if (BitWidth < ToSize ||
1853 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1854 return To->getKind() == BuiltinType::Int;
1855 }
Mike Stump11289f42009-09-09 15:08:12 +00001856
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001857 // Are we promoting to an unsigned int from an unsigned bitfield
1858 // that fits into an unsigned int?
1859 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1860 return To->getKind() == BuiltinType::UInt;
1861 }
Mike Stump11289f42009-09-09 15:08:12 +00001862
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001863 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001864 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001865 }
Mike Stump11289f42009-09-09 15:08:12 +00001866
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001867 // An rvalue of type bool can be converted to an rvalue of type int,
1868 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001869 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001870 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001871 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001872
1873 return false;
1874}
1875
1876/// IsFloatingPointPromotion - Determines whether the conversion from
1877/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1878/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001879bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001880 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1881 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001882 /// An rvalue of type float can be converted to an rvalue of type
1883 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001884 if (FromBuiltin->getKind() == BuiltinType::Float &&
1885 ToBuiltin->getKind() == BuiltinType::Double)
1886 return true;
1887
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001888 // C99 6.3.1.5p1:
1889 // When a float is promoted to double or long double, or a
1890 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001891 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001892 (FromBuiltin->getKind() == BuiltinType::Float ||
1893 FromBuiltin->getKind() == BuiltinType::Double) &&
1894 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1895 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001896
1897 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001898 if (!getLangOpts().NativeHalfType &&
1899 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001900 ToBuiltin->getKind() == BuiltinType::Float)
1901 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001902 }
1903
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001904 return false;
1905}
1906
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001907/// \brief Determine if a conversion is a complex promotion.
1908///
1909/// A complex promotion is defined as a complex -> complex conversion
1910/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001911/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001912bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001913 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001914 if (!FromComplex)
1915 return false;
1916
John McCall9dd450b2009-09-21 23:43:11 +00001917 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001918 if (!ToComplex)
1919 return false;
1920
1921 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001922 ToComplex->getElementType()) ||
1923 IsIntegralPromotion(0, FromComplex->getElementType(),
1924 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001925}
1926
Douglas Gregor237f96c2008-11-26 23:31:11 +00001927/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1928/// the pointer type FromPtr to a pointer to type ToPointee, with the
1929/// same type qualifiers as FromPtr has on its pointee type. ToType,
1930/// if non-empty, will be a pointer to ToType that may or may not have
1931/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001932///
Mike Stump11289f42009-09-09 15:08:12 +00001933static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001934BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001935 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001936 ASTContext &Context,
1937 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001938 assert((FromPtr->getTypeClass() == Type::Pointer ||
1939 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1940 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001941
John McCall31168b02011-06-15 23:02:42 +00001942 /// Conversions to 'id' subsume cv-qualifier conversions.
1943 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001944 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945
1946 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001947 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001948 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001949 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001950
John McCall31168b02011-06-15 23:02:42 +00001951 if (StripObjCLifetime)
1952 Quals.removeObjCLifetime();
1953
Mike Stump11289f42009-09-09 15:08:12 +00001954 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001955 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001956 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001957 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001958 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001959
1960 // Build a pointer to ToPointee. It has the right qualifiers
1961 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001962 if (isa<ObjCObjectPointerType>(ToType))
1963 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001964 return Context.getPointerType(ToPointee);
1965 }
1966
1967 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001968 QualType QualifiedCanonToPointee
1969 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001970
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001971 if (isa<ObjCObjectPointerType>(ToType))
1972 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1973 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001974}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001975
Mike Stump11289f42009-09-09 15:08:12 +00001976static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001977 bool InOverloadResolution,
1978 ASTContext &Context) {
1979 // Handle value-dependent integral null pointer constants correctly.
1980 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1981 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001982 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001983 return !InOverloadResolution;
1984
Douglas Gregor56751b52009-09-25 04:25:58 +00001985 return Expr->isNullPointerConstant(Context,
1986 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1987 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001988}
Mike Stump11289f42009-09-09 15:08:12 +00001989
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001990/// IsPointerConversion - Determines whether the conversion of the
1991/// expression From, which has the (possibly adjusted) type FromType,
1992/// can be converted to the type ToType via a pointer conversion (C++
1993/// 4.10). If so, returns true and places the converted type (that
1994/// might differ from ToType in its cv-qualifiers at some level) into
1995/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001996///
Douglas Gregora29dc052008-11-27 01:19:21 +00001997/// This routine also supports conversions to and from block pointers
1998/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1999/// pointers to interfaces. FIXME: Once we've determined the
2000/// appropriate overloading rules for Objective-C, we may want to
2001/// split the Objective-C checks into a different routine; however,
2002/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002003/// conversions, so for now they live here. IncompatibleObjC will be
2004/// set if the conversion is an allowed Objective-C conversion that
2005/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002006bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002007 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002008 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002009 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002010 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002011 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2012 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002013 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002014
Mike Stump11289f42009-09-09 15:08:12 +00002015 // Conversion from a null pointer constant to any Objective-C pointer type.
2016 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002017 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002018 ConvertedType = ToType;
2019 return true;
2020 }
2021
Douglas Gregor231d1c62008-11-27 00:15:41 +00002022 // Blocks: Block pointers can be converted to void*.
2023 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002024 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002025 ConvertedType = ToType;
2026 return true;
2027 }
2028 // Blocks: A null pointer constant can be converted to a block
2029 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002030 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002031 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002032 ConvertedType = ToType;
2033 return true;
2034 }
2035
Sebastian Redl576fd422009-05-10 18:38:11 +00002036 // If the left-hand-side is nullptr_t, the right side can be a null
2037 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002038 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002039 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002040 ConvertedType = ToType;
2041 return true;
2042 }
2043
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002044 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002045 if (!ToTypePtr)
2046 return false;
2047
2048 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002049 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002050 ConvertedType = ToType;
2051 return true;
2052 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002053
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002054 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002055 // , including objective-c pointers.
2056 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002057 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002058 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002059 ConvertedType = BuildSimilarlyQualifiedPointerType(
2060 FromType->getAs<ObjCObjectPointerType>(),
2061 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002062 ToType, Context);
2063 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002064 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002065 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002066 if (!FromTypePtr)
2067 return false;
2068
2069 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002070
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002071 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002072 // pointer conversion, so don't do all of the work below.
2073 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2074 return false;
2075
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002076 // An rvalue of type "pointer to cv T," where T is an object type,
2077 // can be converted to an rvalue of type "pointer to cv void" (C++
2078 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002079 if (FromPointeeType->isIncompleteOrObjectType() &&
2080 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002081 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002082 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002083 ToType, Context,
2084 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002085 return true;
2086 }
2087
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002088 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002089 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002090 ToPointeeType->isVoidType()) {
2091 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2092 ToPointeeType,
2093 ToType, Context);
2094 return true;
2095 }
2096
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002097 // When we're overloading in C, we allow a special kind of pointer
2098 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002099 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002100 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002101 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002102 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002103 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002104 return true;
2105 }
2106
Douglas Gregor5c407d92008-10-23 00:40:37 +00002107 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002108 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002109 // An rvalue of type "pointer to cv D," where D is a class type,
2110 // can be converted to an rvalue of type "pointer to cv B," where
2111 // B is a base class (clause 10) of D. If B is an inaccessible
2112 // (clause 11) or ambiguous (10.2) base class of D, a program that
2113 // necessitates this conversion is ill-formed. The result of the
2114 // conversion is a pointer to the base class sub-object of the
2115 // derived class object. The null pointer value is converted to
2116 // the null pointer value of the destination type.
2117 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002118 // Note that we do not check for ambiguity or inaccessibility
2119 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002120 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002121 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002122 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002123 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002124 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002125 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002126 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002127 ToType, Context);
2128 return true;
2129 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002130
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002131 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2132 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2133 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2134 ToPointeeType,
2135 ToType, Context);
2136 return true;
2137 }
2138
Douglas Gregora119f102008-12-19 19:13:09 +00002139 return false;
2140}
Douglas Gregoraec25842011-04-26 23:16:46 +00002141
2142/// \brief Adopt the given qualifiers for the given type.
2143static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2144 Qualifiers TQs = T.getQualifiers();
2145
2146 // Check whether qualifiers already match.
2147 if (TQs == Qs)
2148 return T;
2149
2150 if (Qs.compatiblyIncludes(TQs))
2151 return Context.getQualifiedType(T, Qs);
2152
2153 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2154}
Douglas Gregora119f102008-12-19 19:13:09 +00002155
2156/// isObjCPointerConversion - Determines whether this is an
2157/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2158/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002159bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002160 QualType& ConvertedType,
2161 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002162 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002163 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002164
Douglas Gregoraec25842011-04-26 23:16:46 +00002165 // The set of qualifiers on the type we're converting from.
2166 Qualifiers FromQualifiers = FromType.getQualifiers();
2167
Steve Naroff7cae42b2009-07-10 23:34:53 +00002168 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002169 const ObjCObjectPointerType* ToObjCPtr =
2170 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002171 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002172 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002173
Steve Naroff7cae42b2009-07-10 23:34:53 +00002174 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002175 // If the pointee types are the same (ignoring qualifications),
2176 // then this is not a pointer conversion.
2177 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2178 FromObjCPtr->getPointeeType()))
2179 return false;
2180
Douglas Gregoraec25842011-04-26 23:16:46 +00002181 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002182 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002183 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002184 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002185 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002186 return true;
2187 }
2188 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002189 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002190 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002191 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002192 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002193 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002194 return true;
2195 }
2196 // Objective C++: We're able to convert from a pointer to an
2197 // interface to a pointer to a different interface.
2198 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002199 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2200 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002201 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002202 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2203 FromObjCPtr->getPointeeType()))
2204 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002205 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002206 ToObjCPtr->getPointeeType(),
2207 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002208 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002209 return true;
2210 }
2211
2212 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2213 // Okay: this is some kind of implicit downcast of Objective-C
2214 // interfaces, which is permitted. However, we're going to
2215 // complain about it.
2216 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002217 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002218 ToObjCPtr->getPointeeType(),
2219 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002220 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002221 return true;
2222 }
Mike Stump11289f42009-09-09 15:08:12 +00002223 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002224 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002225 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002226 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002227 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002228 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002229 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002230 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002231 // to a block pointer type.
2232 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002233 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002234 return true;
2235 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002236 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002237 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002238 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002239 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002241 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002242 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002243 return true;
2244 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002245 else
Douglas Gregora119f102008-12-19 19:13:09 +00002246 return false;
2247
Douglas Gregor033f56d2008-12-23 00:53:59 +00002248 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002249 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002250 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002251 else if (const BlockPointerType *FromBlockPtr =
2252 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002253 FromPointeeType = FromBlockPtr->getPointeeType();
2254 else
Douglas Gregora119f102008-12-19 19:13:09 +00002255 return false;
2256
Douglas Gregora119f102008-12-19 19:13:09 +00002257 // If we have pointers to pointers, recursively check whether this
2258 // is an Objective-C conversion.
2259 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2260 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2261 IncompatibleObjC)) {
2262 // We always complain about this conversion.
2263 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002264 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002265 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002266 return true;
2267 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002268 // Allow conversion of pointee being objective-c pointer to another one;
2269 // as in I* to id.
2270 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2271 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2272 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2273 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002274
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002275 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002276 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002277 return true;
2278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002279
Douglas Gregor033f56d2008-12-23 00:53:59 +00002280 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002281 // differences in the argument and result types are in Objective-C
2282 // pointer conversions. If so, we permit the conversion (but
2283 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002284 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002285 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002286 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002287 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002288 if (FromFunctionType && ToFunctionType) {
2289 // If the function types are exactly the same, this isn't an
2290 // Objective-C pointer conversion.
2291 if (Context.getCanonicalType(FromPointeeType)
2292 == Context.getCanonicalType(ToPointeeType))
2293 return false;
2294
2295 // Perform the quick checks that will tell us whether these
2296 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002297 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002298 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2299 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2300 return false;
2301
2302 bool HasObjCConversion = false;
Alp Toker314cc812014-01-25 16:55:45 +00002303 if (Context.getCanonicalType(FromFunctionType->getReturnType()) ==
2304 Context.getCanonicalType(ToFunctionType->getReturnType())) {
Douglas Gregora119f102008-12-19 19:13:09 +00002305 // Okay, the types match exactly. Nothing to do.
Alp Toker314cc812014-01-25 16:55:45 +00002306 } else if (isObjCPointerConversion(FromFunctionType->getReturnType(),
2307 ToFunctionType->getReturnType(),
Douglas Gregora119f102008-12-19 19:13:09 +00002308 ConvertedType, IncompatibleObjC)) {
2309 // Okay, we have an Objective-C pointer conversion.
2310 HasObjCConversion = true;
2311 } else {
2312 // Function types are too different. Abort.
2313 return false;
2314 }
Mike Stump11289f42009-09-09 15:08:12 +00002315
Douglas Gregora119f102008-12-19 19:13:09 +00002316 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002317 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002318 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002319 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2320 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002321 if (Context.getCanonicalType(FromArgType)
2322 == Context.getCanonicalType(ToArgType)) {
2323 // Okay, the types match exactly. Nothing to do.
2324 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2325 ConvertedType, IncompatibleObjC)) {
2326 // Okay, we have an Objective-C pointer conversion.
2327 HasObjCConversion = true;
2328 } else {
2329 // Argument types are too different. Abort.
2330 return false;
2331 }
2332 }
2333
2334 if (HasObjCConversion) {
2335 // We had an Objective-C conversion. Allow this pointer
2336 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002337 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002338 IncompatibleObjC = true;
2339 return true;
2340 }
2341 }
2342
Sebastian Redl72b597d2009-01-25 19:43:20 +00002343 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002344}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002345
John McCall31168b02011-06-15 23:02:42 +00002346/// \brief Determine whether this is an Objective-C writeback conversion,
2347/// used for parameter passing when performing automatic reference counting.
2348///
2349/// \param FromType The type we're converting form.
2350///
2351/// \param ToType The type we're converting to.
2352///
2353/// \param ConvertedType The type that will be produced after applying
2354/// this conversion.
2355bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2356 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002357 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002358 Context.hasSameUnqualifiedType(FromType, ToType))
2359 return false;
2360
2361 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2362 QualType ToPointee;
2363 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2364 ToPointee = ToPointer->getPointeeType();
2365 else
2366 return false;
2367
2368 Qualifiers ToQuals = ToPointee.getQualifiers();
2369 if (!ToPointee->isObjCLifetimeType() ||
2370 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002371 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002372 return false;
2373
2374 // Argument must be a pointer to __strong to __weak.
2375 QualType FromPointee;
2376 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2377 FromPointee = FromPointer->getPointeeType();
2378 else
2379 return false;
2380
2381 Qualifiers FromQuals = FromPointee.getQualifiers();
2382 if (!FromPointee->isObjCLifetimeType() ||
2383 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2384 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2385 return false;
2386
2387 // Make sure that we have compatible qualifiers.
2388 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2389 if (!ToQuals.compatiblyIncludes(FromQuals))
2390 return false;
2391
2392 // Remove qualifiers from the pointee type we're converting from; they
2393 // aren't used in the compatibility check belong, and we'll be adding back
2394 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2395 FromPointee = FromPointee.getUnqualifiedType();
2396
2397 // The unqualified form of the pointee types must be compatible.
2398 ToPointee = ToPointee.getUnqualifiedType();
2399 bool IncompatibleObjC;
2400 if (Context.typesAreCompatible(FromPointee, ToPointee))
2401 FromPointee = ToPointee;
2402 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2403 IncompatibleObjC))
2404 return false;
2405
2406 /// \brief Construct the type we're converting to, which is a pointer to
2407 /// __autoreleasing pointee.
2408 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2409 ConvertedType = Context.getPointerType(FromPointee);
2410 return true;
2411}
2412
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002413bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2414 QualType& ConvertedType) {
2415 QualType ToPointeeType;
2416 if (const BlockPointerType *ToBlockPtr =
2417 ToType->getAs<BlockPointerType>())
2418 ToPointeeType = ToBlockPtr->getPointeeType();
2419 else
2420 return false;
2421
2422 QualType FromPointeeType;
2423 if (const BlockPointerType *FromBlockPtr =
2424 FromType->getAs<BlockPointerType>())
2425 FromPointeeType = FromBlockPtr->getPointeeType();
2426 else
2427 return false;
2428 // We have pointer to blocks, check whether the only
2429 // differences in the argument and result types are in Objective-C
2430 // pointer conversions. If so, we permit the conversion.
2431
2432 const FunctionProtoType *FromFunctionType
2433 = FromPointeeType->getAs<FunctionProtoType>();
2434 const FunctionProtoType *ToFunctionType
2435 = ToPointeeType->getAs<FunctionProtoType>();
2436
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002437 if (!FromFunctionType || !ToFunctionType)
2438 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002439
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002440 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002441 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002442
2443 // Perform the quick checks that will tell us whether these
2444 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002445 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002446 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2447 return false;
2448
2449 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2450 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2451 if (FromEInfo != ToEInfo)
2452 return false;
2453
2454 bool IncompatibleObjC = false;
Alp Toker314cc812014-01-25 16:55:45 +00002455 if (Context.hasSameType(FromFunctionType->getReturnType(),
2456 ToFunctionType->getReturnType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002457 // Okay, the types match exactly. Nothing to do.
2458 } else {
Alp Toker314cc812014-01-25 16:55:45 +00002459 QualType RHS = FromFunctionType->getReturnType();
2460 QualType LHS = ToFunctionType->getReturnType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002461 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002462 !RHS.hasQualifiers() && LHS.hasQualifiers())
2463 LHS = LHS.getUnqualifiedType();
2464
2465 if (Context.hasSameType(RHS,LHS)) {
2466 // OK exact match.
2467 } else if (isObjCPointerConversion(RHS, LHS,
2468 ConvertedType, IncompatibleObjC)) {
2469 if (IncompatibleObjC)
2470 return false;
2471 // Okay, we have an Objective-C pointer conversion.
2472 }
2473 else
2474 return false;
2475 }
2476
2477 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002478 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002479 ArgIdx != NumArgs; ++ArgIdx) {
2480 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002481 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2482 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002483 if (Context.hasSameType(FromArgType, ToArgType)) {
2484 // Okay, the types match exactly. Nothing to do.
2485 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2486 ConvertedType, IncompatibleObjC)) {
2487 if (IncompatibleObjC)
2488 return false;
2489 // Okay, we have an Objective-C pointer conversion.
2490 } else
2491 // Argument types are too different. Abort.
2492 return false;
2493 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002494 if (LangOpts.ObjCAutoRefCount &&
2495 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2496 ToFunctionType))
2497 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002498
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002499 ConvertedType = ToType;
2500 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002501}
2502
Richard Trieucaff2472011-11-23 22:32:32 +00002503enum {
2504 ft_default,
2505 ft_different_class,
2506 ft_parameter_arity,
2507 ft_parameter_mismatch,
2508 ft_return_type,
2509 ft_qualifer_mismatch
2510};
2511
2512/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2513/// function types. Catches different number of parameter, mismatch in
2514/// parameter types, and different return types.
2515void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2516 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002517 // If either type is not valid, include no extra info.
2518 if (FromType.isNull() || ToType.isNull()) {
2519 PDiag << ft_default;
2520 return;
2521 }
2522
Richard Trieucaff2472011-11-23 22:32:32 +00002523 // Get the function type from the pointers.
2524 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2525 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2526 *ToMember = ToType->getAs<MemberPointerType>();
2527 if (FromMember->getClass() != ToMember->getClass()) {
2528 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2529 << QualType(FromMember->getClass(), 0);
2530 return;
2531 }
2532 FromType = FromMember->getPointeeType();
2533 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002534 }
2535
Richard Trieu96ed5b62011-12-13 23:19:45 +00002536 if (FromType->isPointerType())
2537 FromType = FromType->getPointeeType();
2538 if (ToType->isPointerType())
2539 ToType = ToType->getPointeeType();
2540
2541 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002542 FromType = FromType.getNonReferenceType();
2543 ToType = ToType.getNonReferenceType();
2544
Richard Trieucaff2472011-11-23 22:32:32 +00002545 // Don't print extra info for non-specialized template functions.
2546 if (FromType->isInstantiationDependentType() &&
2547 !FromType->getAs<TemplateSpecializationType>()) {
2548 PDiag << ft_default;
2549 return;
2550 }
2551
Richard Trieu96ed5b62011-12-13 23:19:45 +00002552 // No extra info for same types.
2553 if (Context.hasSameType(FromType, ToType)) {
2554 PDiag << ft_default;
2555 return;
2556 }
2557
Richard Trieucaff2472011-11-23 22:32:32 +00002558 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2559 *ToFunction = ToType->getAs<FunctionProtoType>();
2560
2561 // Both types need to be function types.
2562 if (!FromFunction || !ToFunction) {
2563 PDiag << ft_default;
2564 return;
2565 }
2566
Alp Toker9cacbab2014-01-20 20:26:09 +00002567 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2568 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2569 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002570 return;
2571 }
2572
2573 // Handle different parameter types.
2574 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002575 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002576 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002577 << ToFunction->getParamType(ArgPos)
2578 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002579 return;
2580 }
2581
2582 // Handle different return type.
Alp Toker314cc812014-01-25 16:55:45 +00002583 if (!Context.hasSameType(FromFunction->getReturnType(),
2584 ToFunction->getReturnType())) {
2585 PDiag << ft_return_type << ToFunction->getReturnType()
2586 << FromFunction->getReturnType();
Richard Trieucaff2472011-11-23 22:32:32 +00002587 return;
2588 }
2589
2590 unsigned FromQuals = FromFunction->getTypeQuals(),
2591 ToQuals = ToFunction->getTypeQuals();
2592 if (FromQuals != ToQuals) {
2593 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2594 return;
2595 }
2596
2597 // Unable to find a difference, so add no extra info.
2598 PDiag << ft_default;
2599}
2600
Alp Toker9cacbab2014-01-20 20:26:09 +00002601/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002602/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002603/// they have same number of arguments. If the parameters are different,
2604/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002605bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2606 const FunctionProtoType *NewType,
2607 unsigned *ArgPos) {
2608 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2609 N = NewType->param_type_begin(),
2610 E = OldType->param_type_end();
2611 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002612 if (!Context.hasSameType(O->getUnqualifiedType(),
2613 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002614 if (ArgPos)
2615 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002616 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002617 }
2618 }
2619 return true;
2620}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002621
Douglas Gregor39c16d42008-10-24 04:54:22 +00002622/// CheckPointerConversion - Check the pointer conversion from the
2623/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002624/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002625/// conversions for which IsPointerConversion has already returned
2626/// true. It returns true and produces a diagnostic if there was an
2627/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002628bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002629 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002630 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002631 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002632 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002633 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002634
John McCall8cb679e2010-11-15 09:13:47 +00002635 Kind = CK_BitCast;
2636
David Blaikie1c7c8f72012-08-08 17:33:31 +00002637 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
Argyrios Kyrtzidis3e3305d2014-02-02 05:26:43 +00002638 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
David Blaikie1c7c8f72012-08-08 17:33:31 +00002639 Expr::NPCK_ZeroExpression) {
2640 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2641 DiagRuntimeBehavior(From->getExprLoc(), From,
2642 PDiag(diag::warn_impcast_bool_to_null_pointer)
2643 << ToType << From->getSourceRange());
2644 else if (!isUnevaluatedContext())
2645 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2646 << ToType << From->getSourceRange();
2647 }
John McCall9320b872011-09-09 05:25:32 +00002648 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2649 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002650 QualType FromPointeeType = FromPtrType->getPointeeType(),
2651 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002652
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002653 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2654 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002655 // We must have a derived-to-base conversion. Check an
2656 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002657 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2658 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002659 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002660 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002661 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002662
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002663 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002664 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002665 }
2666 }
John McCall9320b872011-09-09 05:25:32 +00002667 } else if (const ObjCObjectPointerType *ToPtrType =
2668 ToType->getAs<ObjCObjectPointerType>()) {
2669 if (const ObjCObjectPointerType *FromPtrType =
2670 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002671 // Objective-C++ conversions are always okay.
2672 // FIXME: We should have a different class of conversions for the
2673 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002674 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002675 return false;
John McCall9320b872011-09-09 05:25:32 +00002676 } else if (FromType->isBlockPointerType()) {
2677 Kind = CK_BlockPointerToObjCPointerCast;
2678 } else {
2679 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002680 }
John McCall9320b872011-09-09 05:25:32 +00002681 } else if (ToType->isBlockPointerType()) {
2682 if (!FromType->isBlockPointerType())
2683 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002684 }
John McCall8cb679e2010-11-15 09:13:47 +00002685
2686 // We shouldn't fall into this case unless it's valid for other
2687 // reasons.
2688 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2689 Kind = CK_NullToPointer;
2690
Douglas Gregor39c16d42008-10-24 04:54:22 +00002691 return false;
2692}
2693
Sebastian Redl72b597d2009-01-25 19:43:20 +00002694/// IsMemberPointerConversion - Determines whether the conversion of the
2695/// expression From, which has the (possibly adjusted) type FromType, can be
2696/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2697/// If so, returns true and places the converted type (that might differ from
2698/// ToType in its cv-qualifiers at some level) into ConvertedType.
2699bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002700 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002701 bool InOverloadResolution,
2702 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002703 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704 if (!ToTypePtr)
2705 return false;
2706
2707 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002708 if (From->isNullPointerConstant(Context,
2709 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2710 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002711 ConvertedType = ToType;
2712 return true;
2713 }
2714
2715 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002716 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002717 if (!FromTypePtr)
2718 return false;
2719
2720 // A pointer to member of B can be converted to a pointer to member of D,
2721 // where D is derived from B (C++ 4.11p2).
2722 QualType FromClass(FromTypePtr->getClass(), 0);
2723 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002724
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002725 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002726 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002727 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002728 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2729 ToClass.getTypePtr());
2730 return true;
2731 }
2732
2733 return false;
2734}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002735
Sebastian Redl72b597d2009-01-25 19:43:20 +00002736/// CheckMemberPointerConversion - Check the member pointer conversion from the
2737/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002738/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739/// for which IsMemberPointerConversion has already returned true. It returns
2740/// true and produces a diagnostic if there was an error, or returns false
2741/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002742bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002743 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002744 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002745 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002746 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002747 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002748 if (!FromPtrType) {
2749 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002750 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002751 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002752 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002753 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002754 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002755 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002756
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002757 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002758 assert(ToPtrType && "No member pointer cast has a target type "
2759 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002760
Sebastian Redled8f2002009-01-28 18:33:18 +00002761 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2762 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002763
Sebastian Redled8f2002009-01-28 18:33:18 +00002764 // FIXME: What about dependent types?
2765 assert(FromClass->isRecordType() && "Pointer into non-class.");
2766 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002767
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002768 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002769 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002770 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2771 assert(DerivationOkay &&
2772 "Should not have been called if derivation isn't OK.");
2773 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002774
Sebastian Redled8f2002009-01-28 18:33:18 +00002775 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2776 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002777 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2778 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2779 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2780 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002781 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002782
Douglas Gregor89ee6822009-02-28 01:32:25 +00002783 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002784 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2785 << FromClass << ToClass << QualType(VBase, 0)
2786 << From->getSourceRange();
2787 return true;
2788 }
2789
John McCall5b0829a2010-02-10 09:31:12 +00002790 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002791 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2792 Paths.front(),
2793 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002794
Anders Carlssond7923c62009-08-22 23:33:40 +00002795 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002796 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002797 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002798 return false;
2799}
2800
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002801/// Determine whether the lifetime conversion between the two given
2802/// qualifiers sets is nontrivial.
2803static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2804 Qualifiers ToQuals) {
2805 // Converting anything to const __unsafe_unretained is trivial.
2806 if (ToQuals.hasConst() &&
2807 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2808 return false;
2809
2810 return true;
2811}
2812
Douglas Gregor9a657932008-10-21 23:43:52 +00002813/// IsQualificationConversion - Determines whether the conversion from
2814/// an rvalue of type FromType to ToType is a qualification conversion
2815/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002816///
2817/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2818/// when the qualification conversion involves a change in the Objective-C
2819/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002820bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002821Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002822 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002823 FromType = Context.getCanonicalType(FromType);
2824 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002825 ObjCLifetimeConversion = false;
2826
Douglas Gregor9a657932008-10-21 23:43:52 +00002827 // If FromType and ToType are the same type, this is not a
2828 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002829 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002830 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002831
Douglas Gregor9a657932008-10-21 23:43:52 +00002832 // (C++ 4.4p4):
2833 // A conversion can add cv-qualifiers at levels other than the first
2834 // in multi-level pointers, subject to the following rules: [...]
2835 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002836 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002837 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002838 // Within each iteration of the loop, we check the qualifiers to
2839 // determine if this still looks like a qualification
2840 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002841 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002842 // until there are no more pointers or pointers-to-members left to
2843 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002844 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002845
Douglas Gregor90609aa2011-04-25 18:40:17 +00002846 Qualifiers FromQuals = FromType.getQualifiers();
2847 Qualifiers ToQuals = ToType.getQualifiers();
2848
John McCall31168b02011-06-15 23:02:42 +00002849 // Objective-C ARC:
2850 // Check Objective-C lifetime conversions.
2851 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2852 UnwrappedAnyPointer) {
2853 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002854 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2855 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002856 FromQuals.removeObjCLifetime();
2857 ToQuals.removeObjCLifetime();
2858 } else {
2859 // Qualification conversions cannot cast between different
2860 // Objective-C lifetime qualifiers.
2861 return false;
2862 }
2863 }
2864
Douglas Gregorf30053d2011-05-08 06:09:53 +00002865 // Allow addition/removal of GC attributes but not changing GC attributes.
2866 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2867 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2868 FromQuals.removeObjCGCAttr();
2869 ToQuals.removeObjCGCAttr();
2870 }
2871
Douglas Gregor9a657932008-10-21 23:43:52 +00002872 // -- for every j > 0, if const is in cv 1,j then const is in cv
2873 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002874 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002875 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002876
Douglas Gregor9a657932008-10-21 23:43:52 +00002877 // -- if the cv 1,j and cv 2,j are different, then const is in
2878 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002879 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002880 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002881 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002882
Douglas Gregor9a657932008-10-21 23:43:52 +00002883 // Keep track of whether all prior cv-qualifiers in the "to" type
2884 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002885 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002886 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002887 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002888
2889 // We are left with FromType and ToType being the pointee types
2890 // after unwrapping the original FromType and ToType the same number
2891 // of types. If we unwrapped any pointers, and if FromType and
2892 // ToType have the same unqualified type (since we checked
2893 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002894 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002895}
2896
Douglas Gregorc79862f2012-04-12 17:51:55 +00002897/// \brief - Determine whether this is a conversion from a scalar type to an
2898/// atomic type.
2899///
2900/// If successful, updates \c SCS's second and third steps in the conversion
2901/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002902static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2903 bool InOverloadResolution,
2904 StandardConversionSequence &SCS,
2905 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002906 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2907 if (!ToAtomic)
2908 return false;
2909
2910 StandardConversionSequence InnerSCS;
2911 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2912 InOverloadResolution, InnerSCS,
2913 CStyle, /*AllowObjCWritebackConversion=*/false))
2914 return false;
2915
2916 SCS.Second = InnerSCS.Second;
2917 SCS.setToType(1, InnerSCS.getToType(1));
2918 SCS.Third = InnerSCS.Third;
2919 SCS.QualificationIncludesObjCLifetime
2920 = InnerSCS.QualificationIncludesObjCLifetime;
2921 SCS.setToType(2, InnerSCS.getToType(2));
2922 return true;
2923}
2924
Sebastian Redle5417162012-03-27 18:33:03 +00002925static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2926 CXXConstructorDecl *Constructor,
2927 QualType Type) {
2928 const FunctionProtoType *CtorType =
2929 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002930 if (CtorType->getNumParams() > 0) {
2931 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002932 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2933 return true;
2934 }
2935 return false;
2936}
2937
Sebastian Redl82ace982012-02-11 23:51:08 +00002938static OverloadingResult
2939IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2940 CXXRecordDecl *To,
2941 UserDefinedConversionSequence &User,
2942 OverloadCandidateSet &CandidateSet,
2943 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002944 DeclContext::lookup_result R = S.LookupConstructors(To);
2945 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002946 Con != ConEnd; ++Con) {
2947 NamedDecl *D = *Con;
2948 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2949
2950 // Find the constructor (which may be a template).
2951 CXXConstructorDecl *Constructor = 0;
2952 FunctionTemplateDecl *ConstructorTmpl
2953 = dyn_cast<FunctionTemplateDecl>(D);
2954 if (ConstructorTmpl)
2955 Constructor
2956 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2957 else
2958 Constructor = cast<CXXConstructorDecl>(D);
2959
2960 bool Usable = !Constructor->isInvalidDecl() &&
2961 S.isInitListConstructor(Constructor) &&
2962 (AllowExplicit || !Constructor->isExplicit());
2963 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002964 // If the first argument is (a reference to) the target type,
2965 // suppress conversions.
2966 bool SuppressUserConversions =
2967 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002968 if (ConstructorTmpl)
2969 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2970 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002971 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002972 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002973 else
2974 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002975 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002976 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002977 }
2978 }
2979
2980 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2981
2982 OverloadCandidateSet::iterator Best;
2983 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2984 case OR_Success: {
2985 // Record the standard conversion we used and the conversion function.
2986 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002987 QualType ThisType = Constructor->getThisType(S.Context);
2988 // Initializer lists don't have conversions as such.
2989 User.Before.setAsIdentityConversion();
2990 User.HadMultipleCandidates = HadMultipleCandidates;
2991 User.ConversionFunction = Constructor;
2992 User.FoundConversionFunction = Best->FoundDecl;
2993 User.After.setAsIdentityConversion();
2994 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2995 User.After.setAllToTypes(ToType);
2996 return OR_Success;
2997 }
2998
2999 case OR_No_Viable_Function:
3000 return OR_No_Viable_Function;
3001 case OR_Deleted:
3002 return OR_Deleted;
3003 case OR_Ambiguous:
3004 return OR_Ambiguous;
3005 }
3006
3007 llvm_unreachable("Invalid OverloadResult!");
3008}
3009
Douglas Gregor576e98c2009-01-30 23:27:23 +00003010/// Determines whether there is a user-defined conversion sequence
3011/// (C++ [over.ics.user]) that converts expression From to the type
3012/// ToType. If such a conversion exists, User will contain the
3013/// user-defined conversion sequence that performs such a conversion
3014/// and this routine will return true. Otherwise, this routine returns
3015/// false and User is unspecified.
3016///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003017/// \param AllowExplicit true if the conversion should consider C++0x
3018/// "explicit" conversion functions as well as non-explicit conversion
3019/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003020///
3021/// \param AllowObjCConversionOnExplicit true if the conversion should
3022/// allow an extra Objective-C pointer conversion on uses of explicit
3023/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003024static OverloadingResult
3025IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003026 UserDefinedConversionSequence &User,
3027 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003028 bool AllowExplicit,
3029 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003030 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003031
Douglas Gregor5ab11652010-04-17 22:01:05 +00003032 // Whether we will only visit constructors.
3033 bool ConstructorsOnly = false;
3034
3035 // If the type we are conversion to is a class type, enumerate its
3036 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003037 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003038 // C++ [over.match.ctor]p1:
3039 // When objects of class type are direct-initialized (8.5), or
3040 // copy-initialized from an expression of the same or a
3041 // derived class type (8.5), overload resolution selects the
3042 // constructor. [...] For copy-initialization, the candidate
3043 // functions are all the converting constructors (12.3.1) of
3044 // that class. The argument list is the expression-list within
3045 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003046 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003047 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003048 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003049 ConstructorsOnly = true;
3050
Benjamin Kramer90633e32012-11-23 17:04:52 +00003051 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003052 // RequireCompleteType may have returned true due to some invalid decl
3053 // during template instantiation, but ToType may be complete enough now
3054 // to try to recover.
3055 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003056 // We're not going to find any constructors.
3057 } else if (CXXRecordDecl *ToRecordDecl
3058 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003059
3060 Expr **Args = &From;
3061 unsigned NumArgs = 1;
3062 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003063 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003064 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003065 OverloadingResult Result = IsInitializerListConstructorConversion(
3066 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3067 if (Result != OR_No_Viable_Function)
3068 return Result;
3069 // Never mind.
3070 CandidateSet.clear();
3071
3072 // If we're list-initializing, we pass the individual elements as
3073 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003074 Args = InitList->getInits();
3075 NumArgs = InitList->getNumInits();
3076 ListInitializing = true;
3077 }
3078
David Blaikieff7d47a2012-12-19 00:45:41 +00003079 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3080 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003081 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003082 NamedDecl *D = *Con;
3083 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3084
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003085 // Find the constructor (which may be a template).
3086 CXXConstructorDecl *Constructor = 0;
3087 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003088 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003089 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003090 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003091 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3092 else
John McCalla0296f72010-03-19 07:35:19 +00003093 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003094
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003095 bool Usable = !Constructor->isInvalidDecl();
3096 if (ListInitializing)
3097 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3098 else
3099 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3100 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003101 bool SuppressUserConversions = !ConstructorsOnly;
3102 if (SuppressUserConversions && ListInitializing) {
3103 SuppressUserConversions = false;
3104 if (NumArgs == 1) {
3105 // If the first argument is (a reference to) the target type,
3106 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003107 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3108 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003109 }
3110 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003111 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003112 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3113 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003114 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003115 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003116 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003117 // Allow one user-defined conversion when user specifies a
3118 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003119 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003120 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003121 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003122 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003123 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003124 }
3125 }
3126
Douglas Gregor5ab11652010-04-17 22:01:05 +00003127 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003128 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003129 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003130 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003131 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003132 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003133 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003134 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3135 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003136 std::pair<CXXRecordDecl::conversion_iterator,
3137 CXXRecordDecl::conversion_iterator>
3138 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3139 for (CXXRecordDecl::conversion_iterator
3140 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003141 DeclAccessPair FoundDecl = I.getPair();
3142 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003143 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3144 if (isa<UsingShadowDecl>(D))
3145 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3146
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003147 CXXConversionDecl *Conv;
3148 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003149 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3150 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003151 else
John McCallda4458e2010-03-31 01:36:47 +00003152 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003153
3154 if (AllowExplicit || !Conv->isExplicit()) {
3155 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003156 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3157 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003158 CandidateSet,
3159 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003160 else
John McCall5c32be02010-08-24 20:38:10 +00003161 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003162 From, ToType, CandidateSet,
3163 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003164 }
3165 }
3166 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003167 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003168
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003169 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3170
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003171 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003172 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003173 case OR_Success:
3174 // Record the standard conversion we used and the conversion function.
3175 if (CXXConstructorDecl *Constructor
3176 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3177 // C++ [over.ics.user]p1:
3178 // If the user-defined conversion is specified by a
3179 // constructor (12.3.1), the initial standard conversion
3180 // sequence converts the source type to the type required by
3181 // the argument of the constructor.
3182 //
3183 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003184 if (isa<InitListExpr>(From)) {
3185 // Initializer lists don't have conversions as such.
3186 User.Before.setAsIdentityConversion();
3187 } else {
3188 if (Best->Conversions[0].isEllipsis())
3189 User.EllipsisConversion = true;
3190 else {
3191 User.Before = Best->Conversions[0].Standard;
3192 User.EllipsisConversion = false;
3193 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003194 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003195 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003196 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003197 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003198 User.After.setAsIdentityConversion();
3199 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3200 User.After.setAllToTypes(ToType);
3201 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003202 }
3203 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003204 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3205 // C++ [over.ics.user]p1:
3206 //
3207 // [...] If the user-defined conversion is specified by a
3208 // conversion function (12.3.2), the initial standard
3209 // conversion sequence converts the source type to the
3210 // implicit object parameter of the conversion function.
3211 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003212 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003213 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003214 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003215 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003216
John McCall5c32be02010-08-24 20:38:10 +00003217 // C++ [over.ics.user]p2:
3218 // The second standard conversion sequence converts the
3219 // result of the user-defined conversion to the target type
3220 // for the sequence. Since an implicit conversion sequence
3221 // is an initialization, the special rules for
3222 // initialization by user-defined conversion apply when
3223 // selecting the best user-defined conversion for a
3224 // user-defined conversion sequence (see 13.3.3 and
3225 // 13.3.3.1).
3226 User.After = Best->FinalConversion;
3227 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003228 }
David Blaikie8a40f702012-01-17 06:56:22 +00003229 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003230
John McCall5c32be02010-08-24 20:38:10 +00003231 case OR_No_Viable_Function:
3232 return OR_No_Viable_Function;
3233 case OR_Deleted:
3234 // No conversion here! We're done.
3235 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003236
John McCall5c32be02010-08-24 20:38:10 +00003237 case OR_Ambiguous:
3238 return OR_Ambiguous;
3239 }
3240
David Blaikie8a40f702012-01-17 06:56:22 +00003241 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003242}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003244bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003245Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003246 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003247 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003249 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003250 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003251 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003252 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3253 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003254 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003255 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003256 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003257 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003258 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3259 << From->getType() << From->getSourceRange() << ToType;
3260 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003261 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003262 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003263 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003264}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003265
Douglas Gregor2837aa22012-02-22 17:32:19 +00003266/// \brief Compare the user-defined conversion functions or constructors
3267/// of two user-defined conversion sequences to determine whether any ordering
3268/// is possible.
3269static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003270compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003271 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003272 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003273 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003274
Douglas Gregor2837aa22012-02-22 17:32:19 +00003275 // Objective-C++:
3276 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003277 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003278 // respectively, always prefer the conversion to a function pointer,
3279 // because the function pointer is more lightweight and is more likely
3280 // to keep code working.
Ted Kremenek8d265c22014-04-01 07:23:18 +00003281 CXXConversionDecl *Conv1 = dyn_cast_or_null<CXXConversionDecl>(Function1);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003282 if (!Conv1)
3283 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003284
Douglas Gregor2837aa22012-02-22 17:32:19 +00003285 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3286 if (!Conv2)
3287 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003288
Douglas Gregor2837aa22012-02-22 17:32:19 +00003289 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3290 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3291 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3292 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003293 return Block1 ? ImplicitConversionSequence::Worse
3294 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003295 }
3296
3297 return ImplicitConversionSequence::Indistinguishable;
3298}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003299
3300static bool hasDeprecatedStringLiteralToCharPtrConversion(
3301 const ImplicitConversionSequence &ICS) {
3302 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3303 (ICS.isUserDefined() &&
3304 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3305}
3306
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003307/// CompareImplicitConversionSequences - Compare two implicit
3308/// conversion sequences to determine whether one is better than the
3309/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003310static ImplicitConversionSequence::CompareKind
3311CompareImplicitConversionSequences(Sema &S,
3312 const ImplicitConversionSequence& ICS1,
3313 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003314{
3315 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3316 // conversion sequences (as defined in 13.3.3.1)
3317 // -- a standard conversion sequence (13.3.3.1.1) is a better
3318 // conversion sequence than a user-defined conversion sequence or
3319 // an ellipsis conversion sequence, and
3320 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3321 // conversion sequence than an ellipsis conversion sequence
3322 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003323 //
John McCall0d1da222010-01-12 00:44:57 +00003324 // C++0x [over.best.ics]p10:
3325 // For the purpose of ranking implicit conversion sequences as
3326 // described in 13.3.3.2, the ambiguous conversion sequence is
3327 // treated as a user-defined sequence that is indistinguishable
3328 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003329
3330 // String literal to 'char *' conversion has been deprecated in C++03. It has
3331 // been removed from C++11. We still accept this conversion, if it happens at
3332 // the best viable function. Otherwise, this conversion is considered worse
3333 // than ellipsis conversion. Consider this as an extension; this is not in the
3334 // standard. For example:
3335 //
3336 // int &f(...); // #1
3337 // void f(char*); // #2
3338 // void g() { int &r = f("foo"); }
3339 //
3340 // In C++03, we pick #2 as the best viable function.
3341 // In C++11, we pick #1 as the best viable function, because ellipsis
3342 // conversion is better than string-literal to char* conversion (since there
3343 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3344 // convert arguments, #2 would be the best viable function in C++11.
3345 // If the best viable function has this conversion, a warning will be issued
3346 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3347
3348 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3349 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3350 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3351 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3352 ? ImplicitConversionSequence::Worse
3353 : ImplicitConversionSequence::Better;
3354
Douglas Gregor5ab11652010-04-17 22:01:05 +00003355 if (ICS1.getKindRank() < ICS2.getKindRank())
3356 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003357 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003358 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003359
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003360 // The following checks require both conversion sequences to be of
3361 // the same kind.
3362 if (ICS1.getKind() != ICS2.getKind())
3363 return ImplicitConversionSequence::Indistinguishable;
3364
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003365 ImplicitConversionSequence::CompareKind Result =
3366 ImplicitConversionSequence::Indistinguishable;
3367
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003368 // Two implicit conversion sequences of the same form are
3369 // indistinguishable conversion sequences unless one of the
3370 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003371 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003372 Result = CompareStandardConversionSequences(S,
3373 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003374 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003375 // User-defined conversion sequence U1 is a better conversion
3376 // sequence than another user-defined conversion sequence U2 if
3377 // they contain the same user-defined conversion function or
3378 // constructor and if the second standard conversion sequence of
3379 // U1 is better than the second standard conversion sequence of
3380 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003381 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003382 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003383 Result = CompareStandardConversionSequences(S,
3384 ICS1.UserDefined.After,
3385 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003386 else
3387 Result = compareConversionFunctions(S,
3388 ICS1.UserDefined.ConversionFunction,
3389 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003390 }
3391
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003392 // List-initialization sequence L1 is a better conversion sequence than
3393 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3394 // for some X and L2 does not.
3395 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003396 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003397 if (ICS1.isStdInitializerListElement() &&
3398 !ICS2.isStdInitializerListElement())
3399 return ImplicitConversionSequence::Better;
3400 if (!ICS1.isStdInitializerListElement() &&
3401 ICS2.isStdInitializerListElement())
3402 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003403 }
3404
3405 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003406}
3407
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003408static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3409 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3410 Qualifiers Quals;
3411 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003415 return Context.hasSameUnqualifiedType(T1, T2);
3416}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003418// Per 13.3.3.2p3, compare the given standard conversion sequences to
3419// determine if one is a proper subset of the other.
3420static ImplicitConversionSequence::CompareKind
3421compareStandardConversionSubsets(ASTContext &Context,
3422 const StandardConversionSequence& SCS1,
3423 const StandardConversionSequence& SCS2) {
3424 ImplicitConversionSequence::CompareKind Result
3425 = ImplicitConversionSequence::Indistinguishable;
3426
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003427 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003428 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003429 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3430 return ImplicitConversionSequence::Better;
3431 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3432 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003433
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003434 if (SCS1.Second != SCS2.Second) {
3435 if (SCS1.Second == ICK_Identity)
3436 Result = ImplicitConversionSequence::Better;
3437 else if (SCS2.Second == ICK_Identity)
3438 Result = ImplicitConversionSequence::Worse;
3439 else
3440 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003441 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003442 return ImplicitConversionSequence::Indistinguishable;
3443
3444 if (SCS1.Third == SCS2.Third) {
3445 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3446 : ImplicitConversionSequence::Indistinguishable;
3447 }
3448
3449 if (SCS1.Third == ICK_Identity)
3450 return Result == ImplicitConversionSequence::Worse
3451 ? ImplicitConversionSequence::Indistinguishable
3452 : ImplicitConversionSequence::Better;
3453
3454 if (SCS2.Third == ICK_Identity)
3455 return Result == ImplicitConversionSequence::Better
3456 ? ImplicitConversionSequence::Indistinguishable
3457 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003458
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003459 return ImplicitConversionSequence::Indistinguishable;
3460}
3461
Douglas Gregore696ebb2011-01-26 14:52:12 +00003462/// \brief Determine whether one of the given reference bindings is better
3463/// than the other based on what kind of bindings they are.
3464static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3465 const StandardConversionSequence &SCS2) {
3466 // C++0x [over.ics.rank]p3b4:
3467 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3468 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003470 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003472 // reference*.
3473 //
3474 // FIXME: Rvalue references. We're going rogue with the above edits,
3475 // because the semantics in the current C++0x working paper (N3225 at the
3476 // time of this writing) break the standard definition of std::forward
3477 // and std::reference_wrapper when dealing with references to functions.
3478 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003479 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3480 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3481 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482
Douglas Gregore696ebb2011-01-26 14:52:12 +00003483 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3484 SCS2.IsLvalueReference) ||
3485 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3486 !SCS2.IsLvalueReference);
3487}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003488
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003489/// CompareStandardConversionSequences - Compare two standard
3490/// conversion sequences to determine whether one is better than the
3491/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003492static ImplicitConversionSequence::CompareKind
3493CompareStandardConversionSequences(Sema &S,
3494 const StandardConversionSequence& SCS1,
3495 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003496{
3497 // Standard conversion sequence S1 is a better conversion sequence
3498 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3499
3500 // -- S1 is a proper subsequence of S2 (comparing the conversion
3501 // sequences in the canonical form defined by 13.3.3.1.1,
3502 // excluding any Lvalue Transformation; the identity conversion
3503 // sequence is considered to be a subsequence of any
3504 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003505 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003506 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003507 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003508
3509 // -- the rank of S1 is better than the rank of S2 (by the rules
3510 // defined below), or, if not that,
3511 ImplicitConversionRank Rank1 = SCS1.getRank();
3512 ImplicitConversionRank Rank2 = SCS2.getRank();
3513 if (Rank1 < Rank2)
3514 return ImplicitConversionSequence::Better;
3515 else if (Rank2 < Rank1)
3516 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003517
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003518 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3519 // are indistinguishable unless one of the following rules
3520 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003521
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003522 // A conversion that is not a conversion of a pointer, or
3523 // pointer to member, to bool is better than another conversion
3524 // that is such a conversion.
3525 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3526 return SCS2.isPointerConversionToBool()
3527 ? ImplicitConversionSequence::Better
3528 : ImplicitConversionSequence::Worse;
3529
Douglas Gregor5c407d92008-10-23 00:40:37 +00003530 // C++ [over.ics.rank]p4b2:
3531 //
3532 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003533 // conversion of B* to A* is better than conversion of B* to
3534 // void*, and conversion of A* to void* is better than conversion
3535 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003536 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003537 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003538 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003539 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003540 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3541 // Exactly one of the conversion sequences is a conversion to
3542 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003543 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3544 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003545 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3546 // Neither conversion sequence converts to a void pointer; compare
3547 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003548 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003549 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003550 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003551 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3552 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003553 // Both conversion sequences are conversions to void
3554 // pointers. Compare the source types to determine if there's an
3555 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003556 QualType FromType1 = SCS1.getFromType();
3557 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003558
3559 // Adjust the types we're converting from via the array-to-pointer
3560 // conversion, if we need to.
3561 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003562 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003563 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003564 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003565
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003566 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3567 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003568
John McCall5c32be02010-08-24 20:38:10 +00003569 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003570 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003571 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003572 return ImplicitConversionSequence::Worse;
3573
3574 // Objective-C++: If one interface is more specific than the
3575 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003576 const ObjCObjectPointerType* FromObjCPtr1
3577 = FromType1->getAs<ObjCObjectPointerType>();
3578 const ObjCObjectPointerType* FromObjCPtr2
3579 = FromType2->getAs<ObjCObjectPointerType>();
3580 if (FromObjCPtr1 && FromObjCPtr2) {
3581 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3582 FromObjCPtr2);
3583 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3584 FromObjCPtr1);
3585 if (AssignLeft != AssignRight) {
3586 return AssignLeft? ImplicitConversionSequence::Better
3587 : ImplicitConversionSequence::Worse;
3588 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003589 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003590 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003591
3592 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3593 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003594 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003595 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003596 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003597
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003598 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003599 // Check for a better reference binding based on the kind of bindings.
3600 if (isBetterReferenceBindingKind(SCS1, SCS2))
3601 return ImplicitConversionSequence::Better;
3602 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3603 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604
Sebastian Redlb28b4072009-03-22 23:49:27 +00003605 // C++ [over.ics.rank]p3b4:
3606 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3607 // which the references refer are the same type except for
3608 // top-level cv-qualifiers, and the type to which the reference
3609 // initialized by S2 refers is more cv-qualified than the type
3610 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003611 QualType T1 = SCS1.getToType(2);
3612 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003613 T1 = S.Context.getCanonicalType(T1);
3614 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003615 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003616 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3617 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003618 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003619 // Objective-C++ ARC: If the references refer to objects with different
3620 // lifetimes, prefer bindings that don't change lifetime.
3621 if (SCS1.ObjCLifetimeConversionBinding !=
3622 SCS2.ObjCLifetimeConversionBinding) {
3623 return SCS1.ObjCLifetimeConversionBinding
3624 ? ImplicitConversionSequence::Worse
3625 : ImplicitConversionSequence::Better;
3626 }
3627
Chandler Carruth8e543b32010-12-12 08:17:55 +00003628 // If the type is an array type, promote the element qualifiers to the
3629 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003630 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003631 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003632 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003633 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003634 if (T2.isMoreQualifiedThan(T1))
3635 return ImplicitConversionSequence::Better;
3636 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003637 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003638 }
3639 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003640
Francois Pichet08d2fa02011-09-18 21:37:37 +00003641 // In Microsoft mode, prefer an integral conversion to a
3642 // floating-to-integral conversion if the integral conversion
3643 // is between types of the same size.
3644 // For example:
3645 // void f(float);
3646 // void f(int);
3647 // int main {
3648 // long a;
3649 // f(a);
3650 // }
3651 // Here, MSVC will call f(int) instead of generating a compile error
3652 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003653 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3654 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003655 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003656 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003657 return ImplicitConversionSequence::Better;
3658
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003659 return ImplicitConversionSequence::Indistinguishable;
3660}
3661
3662/// CompareQualificationConversions - Compares two standard conversion
3663/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003664/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3665ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003666CompareQualificationConversions(Sema &S,
3667 const StandardConversionSequence& SCS1,
3668 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003669 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003670 // -- S1 and S2 differ only in their qualification conversion and
3671 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3672 // cv-qualification signature of type T1 is a proper subset of
3673 // the cv-qualification signature of type T2, and S1 is not the
3674 // deprecated string literal array-to-pointer conversion (4.2).
3675 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3676 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3677 return ImplicitConversionSequence::Indistinguishable;
3678
3679 // FIXME: the example in the standard doesn't use a qualification
3680 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003681 QualType T1 = SCS1.getToType(2);
3682 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003683 T1 = S.Context.getCanonicalType(T1);
3684 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003685 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003686 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3687 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003688
3689 // If the types are the same, we won't learn anything by unwrapped
3690 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003691 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003692 return ImplicitConversionSequence::Indistinguishable;
3693
Chandler Carruth607f38e2009-12-29 07:16:59 +00003694 // If the type is an array type, promote the element qualifiers to the type
3695 // for comparison.
3696 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003697 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003698 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003699 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003700
Mike Stump11289f42009-09-09 15:08:12 +00003701 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003702 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003703
3704 // Objective-C++ ARC:
3705 // Prefer qualification conversions not involving a change in lifetime
3706 // to qualification conversions that do not change lifetime.
3707 if (SCS1.QualificationIncludesObjCLifetime !=
3708 SCS2.QualificationIncludesObjCLifetime) {
3709 Result = SCS1.QualificationIncludesObjCLifetime
3710 ? ImplicitConversionSequence::Worse
3711 : ImplicitConversionSequence::Better;
3712 }
3713
John McCall5c32be02010-08-24 20:38:10 +00003714 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003715 // Within each iteration of the loop, we check the qualifiers to
3716 // determine if this still looks like a qualification
3717 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003718 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003719 // until there are no more pointers or pointers-to-members left
3720 // to unwrap. This essentially mimics what
3721 // IsQualificationConversion does, but here we're checking for a
3722 // strict subset of qualifiers.
3723 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3724 // The qualifiers are the same, so this doesn't tell us anything
3725 // about how the sequences rank.
3726 ;
3727 else if (T2.isMoreQualifiedThan(T1)) {
3728 // T1 has fewer qualifiers, so it could be the better sequence.
3729 if (Result == ImplicitConversionSequence::Worse)
3730 // Neither has qualifiers that are a subset of the other's
3731 // qualifiers.
3732 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003733
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003734 Result = ImplicitConversionSequence::Better;
3735 } else if (T1.isMoreQualifiedThan(T2)) {
3736 // T2 has fewer qualifiers, so it could be the better sequence.
3737 if (Result == ImplicitConversionSequence::Better)
3738 // Neither has qualifiers that are a subset of the other's
3739 // qualifiers.
3740 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003741
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003742 Result = ImplicitConversionSequence::Worse;
3743 } else {
3744 // Qualifiers are disjoint.
3745 return ImplicitConversionSequence::Indistinguishable;
3746 }
3747
3748 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003749 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003750 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003751 }
3752
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003753 // Check that the winning standard conversion sequence isn't using
3754 // the deprecated string literal array to pointer conversion.
3755 switch (Result) {
3756 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003757 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003758 Result = ImplicitConversionSequence::Indistinguishable;
3759 break;
3760
3761 case ImplicitConversionSequence::Indistinguishable:
3762 break;
3763
3764 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003765 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003766 Result = ImplicitConversionSequence::Indistinguishable;
3767 break;
3768 }
3769
3770 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003771}
3772
Douglas Gregor5c407d92008-10-23 00:40:37 +00003773/// CompareDerivedToBaseConversions - Compares two standard conversion
3774/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003775/// various kinds of derived-to-base conversions (C++
3776/// [over.ics.rank]p4b3). As part of these checks, we also look at
3777/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003778ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003779CompareDerivedToBaseConversions(Sema &S,
3780 const StandardConversionSequence& SCS1,
3781 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003782 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003783 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003784 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003785 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003786
3787 // Adjust the types we're converting from via the array-to-pointer
3788 // conversion, if we need to.
3789 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003790 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003791 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003792 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003793
3794 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003795 FromType1 = S.Context.getCanonicalType(FromType1);
3796 ToType1 = S.Context.getCanonicalType(ToType1);
3797 FromType2 = S.Context.getCanonicalType(FromType2);
3798 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003799
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003800 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003801 //
3802 // If class B is derived directly or indirectly from class A and
3803 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003804 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003805 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003806 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003807 SCS2.Second == ICK_Pointer_Conversion &&
3808 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3809 FromType1->isPointerType() && FromType2->isPointerType() &&
3810 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003811 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003812 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003813 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003814 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003815 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003816 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003817 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003818 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003819
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003820 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003821 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003822 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003823 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003824 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003825 return ImplicitConversionSequence::Worse;
3826 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003827
3828 // -- conversion of B* to A* is better than conversion of C* to A*,
3829 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003830 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003831 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003832 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003833 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003834 }
3835 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3836 SCS2.Second == ICK_Pointer_Conversion) {
3837 const ObjCObjectPointerType *FromPtr1
3838 = FromType1->getAs<ObjCObjectPointerType>();
3839 const ObjCObjectPointerType *FromPtr2
3840 = FromType2->getAs<ObjCObjectPointerType>();
3841 const ObjCObjectPointerType *ToPtr1
3842 = ToType1->getAs<ObjCObjectPointerType>();
3843 const ObjCObjectPointerType *ToPtr2
3844 = ToType2->getAs<ObjCObjectPointerType>();
3845
3846 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3847 // Apply the same conversion ranking rules for Objective-C pointer types
3848 // that we do for C++ pointers to class types. However, we employ the
3849 // Objective-C pseudo-subtyping relationship used for assignment of
3850 // Objective-C pointer types.
3851 bool FromAssignLeft
3852 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3853 bool FromAssignRight
3854 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3855 bool ToAssignLeft
3856 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3857 bool ToAssignRight
3858 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3859
3860 // A conversion to an a non-id object pointer type or qualified 'id'
3861 // type is better than a conversion to 'id'.
3862 if (ToPtr1->isObjCIdType() &&
3863 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3864 return ImplicitConversionSequence::Worse;
3865 if (ToPtr2->isObjCIdType() &&
3866 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3867 return ImplicitConversionSequence::Better;
3868
3869 // A conversion to a non-id object pointer type is better than a
3870 // conversion to a qualified 'id' type
3871 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3872 return ImplicitConversionSequence::Worse;
3873 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3874 return ImplicitConversionSequence::Better;
3875
3876 // A conversion to an a non-Class object pointer type or qualified 'Class'
3877 // type is better than a conversion to 'Class'.
3878 if (ToPtr1->isObjCClassType() &&
3879 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3880 return ImplicitConversionSequence::Worse;
3881 if (ToPtr2->isObjCClassType() &&
3882 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3883 return ImplicitConversionSequence::Better;
3884
3885 // A conversion to a non-Class object pointer type is better than a
3886 // conversion to a qualified 'Class' type.
3887 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3888 return ImplicitConversionSequence::Worse;
3889 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3890 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003891
Douglas Gregor058d3de2011-01-31 18:51:41 +00003892 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3893 if (S.Context.hasSameType(FromType1, FromType2) &&
3894 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3895 (ToAssignLeft != ToAssignRight))
3896 return ToAssignLeft? ImplicitConversionSequence::Worse
3897 : ImplicitConversionSequence::Better;
3898
3899 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3900 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3901 (FromAssignLeft != FromAssignRight))
3902 return FromAssignLeft? ImplicitConversionSequence::Better
3903 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003904 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003905 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003906
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003907 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003908 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3909 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3910 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003911 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003912 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003914 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003916 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003918 ToType2->getAs<MemberPointerType>();
3919 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3920 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3921 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3922 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3923 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3924 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3925 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3926 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003927 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003928 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003929 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003930 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003931 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003932 return ImplicitConversionSequence::Better;
3933 }
3934 // conversion of B::* to C::* is better than conversion of A::* to C::*
3935 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003936 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003937 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003938 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003939 return ImplicitConversionSequence::Worse;
3940 }
3941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003942
Douglas Gregor5ab11652010-04-17 22:01:05 +00003943 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003944 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003945 // -- binding of an expression of type C to a reference of type
3946 // B& is better than binding an expression of type C to a
3947 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003948 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3949 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3950 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003951 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003952 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003953 return ImplicitConversionSequence::Worse;
3954 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003955
Douglas Gregor2fe98832008-11-03 19:09:14 +00003956 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003957 // -- binding of an expression of type B to a reference of type
3958 // A& is better than binding an expression of type C to a
3959 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003960 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3961 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3962 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003963 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003964 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003965 return ImplicitConversionSequence::Worse;
3966 }
3967 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003968
Douglas Gregor5c407d92008-10-23 00:40:37 +00003969 return ImplicitConversionSequence::Indistinguishable;
3970}
3971
Douglas Gregor45bb4832013-03-26 23:36:30 +00003972/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3973/// C++ class.
3974static bool isTypeValid(QualType T) {
3975 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3976 return !Record->isInvalidDecl();
3977
3978 return true;
3979}
3980
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003981/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3982/// determine whether they are reference-related,
3983/// reference-compatible, reference-compatible with added
3984/// qualification, or incompatible, for use in C++ initialization by
3985/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3986/// type, and the first type (T1) is the pointee type of the reference
3987/// type being initialized.
3988Sema::ReferenceCompareResult
3989Sema::CompareReferenceRelationship(SourceLocation Loc,
3990 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003991 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003992 bool &ObjCConversion,
3993 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003994 assert(!OrigT1->isReferenceType() &&
3995 "T1 must be the pointee type of the reference type");
3996 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3997
3998 QualType T1 = Context.getCanonicalType(OrigT1);
3999 QualType T2 = Context.getCanonicalType(OrigT2);
4000 Qualifiers T1Quals, T2Quals;
4001 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4002 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4003
4004 // C++ [dcl.init.ref]p4:
4005 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4006 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4007 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004008 DerivedToBase = false;
4009 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004010 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004011 if (UnqualT1 == UnqualT2) {
4012 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004013 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004014 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4015 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004016 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004017 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4018 UnqualT2->isObjCObjectOrInterfaceType() &&
4019 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4020 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004021 else
4022 return Ref_Incompatible;
4023
4024 // At this point, we know that T1 and T2 are reference-related (at
4025 // least).
4026
4027 // If the type is an array type, promote the element qualifiers to the type
4028 // for comparison.
4029 if (isa<ArrayType>(T1) && T1Quals)
4030 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4031 if (isa<ArrayType>(T2) && T2Quals)
4032 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4033
4034 // C++ [dcl.init.ref]p4:
4035 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4036 // reference-related to T2 and cv1 is the same cv-qualification
4037 // as, or greater cv-qualification than, cv2. For purposes of
4038 // overload resolution, cases for which cv1 is greater
4039 // cv-qualification than cv2 are identified as
4040 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004041 //
4042 // Note that we also require equivalence of Objective-C GC and address-space
4043 // qualifiers when performing these computations, so that e.g., an int in
4044 // address space 1 is not reference-compatible with an int in address
4045 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004046 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4047 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004048 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4049 ObjCLifetimeConversion = true;
4050
John McCall31168b02011-06-15 23:02:42 +00004051 T1Quals.removeObjCLifetime();
4052 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004053 }
4054
Douglas Gregord517d552011-04-28 17:56:11 +00004055 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004056 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004057 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004058 return Ref_Compatible_With_Added_Qualification;
4059 else
4060 return Ref_Related;
4061}
4062
Douglas Gregor836a7e82010-08-11 02:15:33 +00004063/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004064/// with DeclType. Return true if something definite is found.
4065static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004066FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4067 QualType DeclType, SourceLocation DeclLoc,
4068 Expr *Init, QualType T2, bool AllowRvalues,
4069 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004070 assert(T2->isRecordType() && "Can only find conversions of record types.");
4071 CXXRecordDecl *T2RecordDecl
4072 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4073
4074 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004075 std::pair<CXXRecordDecl::conversion_iterator,
4076 CXXRecordDecl::conversion_iterator>
4077 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4078 for (CXXRecordDecl::conversion_iterator
4079 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004080 NamedDecl *D = *I;
4081 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4082 if (isa<UsingShadowDecl>(D))
4083 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4084
4085 FunctionTemplateDecl *ConvTemplate
4086 = dyn_cast<FunctionTemplateDecl>(D);
4087 CXXConversionDecl *Conv;
4088 if (ConvTemplate)
4089 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4090 else
4091 Conv = cast<CXXConversionDecl>(D);
4092
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004093 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004094 // explicit conversions, skip it.
4095 if (!AllowExplicit && Conv->isExplicit())
4096 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004097
Douglas Gregor836a7e82010-08-11 02:15:33 +00004098 if (AllowRvalues) {
4099 bool DerivedToBase = false;
4100 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004101 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004102
4103 // If we are initializing an rvalue reference, don't permit conversion
4104 // functions that return lvalues.
4105 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4106 const ReferenceType *RefType
4107 = Conv->getConversionType()->getAs<LValueReferenceType>();
4108 if (RefType && !RefType->getPointeeType()->isFunctionType())
4109 continue;
4110 }
4111
Douglas Gregor836a7e82010-08-11 02:15:33 +00004112 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004113 S.CompareReferenceRelationship(
4114 DeclLoc,
4115 Conv->getConversionType().getNonReferenceType()
4116 .getUnqualifiedType(),
4117 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004118 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004119 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004120 continue;
4121 } else {
4122 // If the conversion function doesn't return a reference type,
4123 // it can't be considered for this conversion. An rvalue reference
4124 // is only acceptable if its referencee is a function type.
4125
4126 const ReferenceType *RefType =
4127 Conv->getConversionType()->getAs<ReferenceType>();
4128 if (!RefType ||
4129 (!RefType->isLValueReferenceType() &&
4130 !RefType->getPointeeType()->isFunctionType()))
4131 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004132 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004133
Douglas Gregor836a7e82010-08-11 02:15:33 +00004134 if (ConvTemplate)
4135 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004136 Init, DeclType, CandidateSet,
4137 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004138 else
4139 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004140 DeclType, CandidateSet,
4141 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004142 }
4143
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004144 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4145
Sebastian Redld92badf2010-06-30 18:13:39 +00004146 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004147 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004148 case OR_Success:
4149 // C++ [over.ics.ref]p1:
4150 //
4151 // [...] If the parameter binds directly to the result of
4152 // applying a conversion function to the argument
4153 // expression, the implicit conversion sequence is a
4154 // user-defined conversion sequence (13.3.3.1.2), with the
4155 // second standard conversion sequence either an identity
4156 // conversion or, if the conversion function returns an
4157 // entity of a type that is a derived class of the parameter
4158 // type, a derived-to-base Conversion.
4159 if (!Best->FinalConversion.DirectBinding)
4160 return false;
4161
4162 ICS.setUserDefined();
4163 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4164 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004165 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004166 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004167 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004168 ICS.UserDefined.EllipsisConversion = false;
4169 assert(ICS.UserDefined.After.ReferenceBinding &&
4170 ICS.UserDefined.After.DirectBinding &&
4171 "Expected a direct reference binding!");
4172 return true;
4173
4174 case OR_Ambiguous:
4175 ICS.setAmbiguous();
4176 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4177 Cand != CandidateSet.end(); ++Cand)
4178 if (Cand->Viable)
4179 ICS.Ambiguous.addConversion(Cand->Function);
4180 return true;
4181
4182 case OR_No_Viable_Function:
4183 case OR_Deleted:
4184 // There was no suitable conversion, or we found a deleted
4185 // conversion; continue with other checks.
4186 return false;
4187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
David Blaikie8a40f702012-01-17 06:56:22 +00004189 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004190}
4191
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004192/// \brief Compute an implicit conversion sequence for reference
4193/// initialization.
4194static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004195TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004196 SourceLocation DeclLoc,
4197 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004198 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004199 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4200
4201 // Most paths end in a failed conversion.
4202 ImplicitConversionSequence ICS;
4203 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4204
4205 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4206 QualType T2 = Init->getType();
4207
4208 // If the initializer is the address of an overloaded function, try
4209 // to resolve the overloaded function. If all goes well, T2 is the
4210 // type of the resulting function.
4211 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4212 DeclAccessPair Found;
4213 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4214 false, Found))
4215 T2 = Fn->getType();
4216 }
4217
4218 // Compute some basic properties of the types and the initializer.
4219 bool isRValRef = DeclType->isRValueReferenceType();
4220 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004221 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004222 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004223 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004224 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004225 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004226 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004227
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004228
Sebastian Redld92badf2010-06-30 18:13:39 +00004229 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004230 // A reference to type "cv1 T1" is initialized by an expression
4231 // of type "cv2 T2" as follows:
4232
Sebastian Redld92badf2010-06-30 18:13:39 +00004233 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004234 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004235 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4236 // reference-compatible with "cv2 T2," or
4237 //
4238 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4239 if (InitCategory.isLValue() &&
4240 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004241 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004242 // When a parameter of reference type binds directly (8.5.3)
4243 // to an argument expression, the implicit conversion sequence
4244 // is the identity conversion, unless the argument expression
4245 // has a type that is a derived class of the parameter type,
4246 // in which case the implicit conversion sequence is a
4247 // derived-to-base Conversion (13.3.3.1).
4248 ICS.setStandard();
4249 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004250 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4251 : ObjCConversion? ICK_Compatible_Conversion
4252 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004253 ICS.Standard.Third = ICK_Identity;
4254 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4255 ICS.Standard.setToType(0, T2);
4256 ICS.Standard.setToType(1, T1);
4257 ICS.Standard.setToType(2, T1);
4258 ICS.Standard.ReferenceBinding = true;
4259 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004260 ICS.Standard.IsLvalueReference = !isRValRef;
4261 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4262 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004263 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004264 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004266 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004267
Sebastian Redld92badf2010-06-30 18:13:39 +00004268 // Nothing more to do: the inaccessibility/ambiguity check for
4269 // derived-to-base conversions is suppressed when we're
4270 // computing the implicit conversion sequence (C++
4271 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004272 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004273 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004274
Sebastian Redld92badf2010-06-30 18:13:39 +00004275 // -- has a class type (i.e., T2 is a class type), where T1 is
4276 // not reference-related to T2, and can be implicitly
4277 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4278 // is reference-compatible with "cv3 T3" 92) (this
4279 // conversion is selected by enumerating the applicable
4280 // conversion functions (13.3.1.6) and choosing the best
4281 // one through overload resolution (13.3)),
4282 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004284 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004285 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4286 Init, T2, /*AllowRvalues=*/false,
4287 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004288 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004289 }
4290 }
4291
Sebastian Redld92badf2010-06-30 18:13:39 +00004292 // -- Otherwise, the reference shall be an lvalue reference to a
4293 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004294 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004295 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004296 // We actually handle one oddity of C++ [over.ics.ref] at this
4297 // point, which is that, due to p2 (which short-circuits reference
4298 // binding by only attempting a simple conversion for non-direct
4299 // bindings) and p3's strange wording, we allow a const volatile
4300 // reference to bind to an rvalue. Hence the check for the presence
4301 // of "const" rather than checking for "const" being the only
4302 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004303 // This is also the point where rvalue references and lvalue inits no longer
4304 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004305 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004306 return ICS;
4307
Douglas Gregorf143cd52011-01-24 16:14:37 +00004308 // -- If the initializer expression
4309 //
4310 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004311 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004312 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4313 (InitCategory.isXValue() ||
4314 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4315 (InitCategory.isLValue() && T2->isFunctionType()))) {
4316 ICS.setStandard();
4317 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004319 : ObjCConversion? ICK_Compatible_Conversion
4320 : ICK_Identity;
4321 ICS.Standard.Third = ICK_Identity;
4322 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4323 ICS.Standard.setToType(0, T2);
4324 ICS.Standard.setToType(1, T1);
4325 ICS.Standard.setToType(2, T1);
4326 ICS.Standard.ReferenceBinding = true;
4327 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4328 // binding unless we're binding to a class prvalue.
4329 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4330 // allow the use of rvalue references in C++98/03 for the benefit of
4331 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004333 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004334 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004335 ICS.Standard.IsLvalueReference = !isRValRef;
4336 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004338 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004339 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004340 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004341 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004343 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344
Douglas Gregorf143cd52011-01-24 16:14:37 +00004345 // -- has a class type (i.e., T2 is a class type), where T1 is not
4346 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004347 // an xvalue, class prvalue, or function lvalue of type
4348 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004349 // "cv3 T3",
4350 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004352 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004354 // class subobject).
4355 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004357 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4358 Init, T2, /*AllowRvalues=*/true,
4359 AllowExplicit)) {
4360 // In the second case, if the reference is an rvalue reference
4361 // and the second standard conversion sequence of the
4362 // user-defined conversion sequence includes an lvalue-to-rvalue
4363 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004365 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4366 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4367
Douglas Gregor95273c32011-01-21 16:36:05 +00004368 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004369 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004371 // -- Otherwise, a temporary of type "cv1 T1" is created and
4372 // initialized from the initializer expression using the
4373 // rules for a non-reference copy initialization (8.5). The
4374 // reference is then bound to the temporary. If T1 is
4375 // reference-related to T2, cv1 must be the same
4376 // cv-qualification as, or greater cv-qualification than,
4377 // cv2; otherwise, the program is ill-formed.
4378 if (RefRelationship == Sema::Ref_Related) {
4379 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4380 // we would be reference-compatible or reference-compatible with
4381 // added qualification. But that wasn't the case, so the reference
4382 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004383 //
4384 // Note that we only want to check address spaces and cvr-qualifiers here.
4385 // ObjC GC and lifetime qualifiers aren't important.
4386 Qualifiers T1Quals = T1.getQualifiers();
4387 Qualifiers T2Quals = T2.getQualifiers();
4388 T1Quals.removeObjCGCAttr();
4389 T1Quals.removeObjCLifetime();
4390 T2Quals.removeObjCGCAttr();
4391 T2Quals.removeObjCLifetime();
4392 if (!T1Quals.compatiblyIncludes(T2Quals))
4393 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004394 }
4395
4396 // If at least one of the types is a class type, the types are not
4397 // related, and we aren't allowed any user conversions, the
4398 // reference binding fails. This case is important for breaking
4399 // recursion, since TryImplicitConversion below will attempt to
4400 // create a temporary through the use of a copy constructor.
4401 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4402 (T1->isRecordType() || T2->isRecordType()))
4403 return ICS;
4404
Douglas Gregorcba72b12011-01-21 05:18:22 +00004405 // If T1 is reference-related to T2 and the reference is an rvalue
4406 // reference, the initializer expression shall not be an lvalue.
4407 if (RefRelationship >= Sema::Ref_Related &&
4408 isRValRef && Init->Classify(S.Context).isLValue())
4409 return ICS;
4410
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004411 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004412 // When a parameter of reference type is not bound directly to
4413 // an argument expression, the conversion sequence is the one
4414 // required to convert the argument expression to the
4415 // underlying type of the reference according to
4416 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4417 // to copy-initializing a temporary of the underlying type with
4418 // the argument expression. Any difference in top-level
4419 // cv-qualification is subsumed by the initialization itself
4420 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004421 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4422 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004423 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004424 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004425 /*AllowObjCWritebackConversion=*/false,
4426 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004427
4428 // Of course, that's still a reference binding.
4429 if (ICS.isStandard()) {
4430 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004431 ICS.Standard.IsLvalueReference = !isRValRef;
4432 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4433 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004434 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004435 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004436 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004437 // Don't allow rvalue references to bind to lvalues.
4438 if (DeclType->isRValueReferenceType()) {
Alp Toker314cc812014-01-25 16:55:45 +00004439 if (const ReferenceType *RefType =
4440 ICS.UserDefined.ConversionFunction->getReturnType()
4441 ->getAs<LValueReferenceType>()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004442 if (!RefType->getPointeeType()->isFunctionType()) {
4443 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4444 DeclType);
4445 return ICS;
4446 }
4447 }
4448 }
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004449 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004450 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004451 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4452 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4453 ICS.UserDefined.After.BindsToRvalue = true;
4454 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4455 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004456 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004457
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004458 return ICS;
4459}
4460
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004461static ImplicitConversionSequence
4462TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4463 bool SuppressUserConversions,
4464 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004465 bool AllowObjCWritebackConversion,
4466 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004467
4468/// TryListConversion - Try to copy-initialize a value of type ToType from the
4469/// initializer list From.
4470static ImplicitConversionSequence
4471TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4472 bool SuppressUserConversions,
4473 bool InOverloadResolution,
4474 bool AllowObjCWritebackConversion) {
4475 // C++11 [over.ics.list]p1:
4476 // When an argument is an initializer list, it is not an expression and
4477 // special rules apply for converting it to a parameter type.
4478
4479 ImplicitConversionSequence Result;
4480 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4481
Sebastian Redl09edce02012-01-23 22:09:39 +00004482 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004483 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004484 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004485 return Result;
4486
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004487 // C++11 [over.ics.list]p2:
4488 // If the parameter type is std::initializer_list<X> or "array of X" and
4489 // all the elements can be implicitly converted to X, the implicit
4490 // conversion sequence is the worst conversion necessary to convert an
4491 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004492 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004493 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004494 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004495 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004496 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004497 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004498 if (!X.isNull()) {
4499 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4500 Expr *Init = From->getInit(i);
4501 ImplicitConversionSequence ICS =
4502 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4503 InOverloadResolution,
4504 AllowObjCWritebackConversion);
4505 // If a single element isn't convertible, fail.
4506 if (ICS.isBad()) {
4507 Result = ICS;
4508 break;
4509 }
4510 // Otherwise, look for the worst conversion.
4511 if (Result.isBad() ||
4512 CompareImplicitConversionSequences(S, ICS, Result) ==
4513 ImplicitConversionSequence::Worse)
4514 Result = ICS;
4515 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004516
4517 // For an empty list, we won't have computed any conversion sequence.
4518 // Introduce the identity conversion sequence.
4519 if (From->getNumInits() == 0) {
4520 Result.setStandard();
4521 Result.Standard.setAsIdentityConversion();
4522 Result.Standard.setFromType(ToType);
4523 Result.Standard.setAllToTypes(ToType);
4524 }
4525
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004526 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004527 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004528 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004529
4530 // C++11 [over.ics.list]p3:
4531 // Otherwise, if the parameter is a non-aggregate class X and overload
4532 // resolution chooses a single best constructor [...] the implicit
4533 // conversion sequence is a user-defined conversion sequence. If multiple
4534 // constructors are viable but none is better than the others, the
4535 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004536 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4537 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004538 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4539 /*AllowExplicit=*/false,
4540 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004541 AllowObjCWritebackConversion,
4542 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004543 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004544
4545 // C++11 [over.ics.list]p4:
4546 // Otherwise, if the parameter has an aggregate type which can be
4547 // initialized from the initializer list [...] the implicit conversion
4548 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004549 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004550 // Type is an aggregate, argument is an init list. At this point it comes
4551 // down to checking whether the initialization works.
4552 // FIXME: Find out whether this parameter is consumed or not.
4553 InitializedEntity Entity =
4554 InitializedEntity::InitializeParameter(S.Context, ToType,
4555 /*Consumed=*/false);
4556 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4557 Result.setUserDefined();
4558 Result.UserDefined.Before.setAsIdentityConversion();
4559 // Initializer lists don't have a type.
4560 Result.UserDefined.Before.setFromType(QualType());
4561 Result.UserDefined.Before.setAllToTypes(QualType());
4562
4563 Result.UserDefined.After.setAsIdentityConversion();
4564 Result.UserDefined.After.setFromType(ToType);
4565 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004566 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004567 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004568 return Result;
4569 }
4570
4571 // C++11 [over.ics.list]p5:
4572 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004573 if (ToType->isReferenceType()) {
4574 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4575 // mention initializer lists in any way. So we go by what list-
4576 // initialization would do and try to extrapolate from that.
4577
4578 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4579
4580 // If the initializer list has a single element that is reference-related
4581 // to the parameter type, we initialize the reference from that.
4582 if (From->getNumInits() == 1) {
4583 Expr *Init = From->getInit(0);
4584
4585 QualType T2 = Init->getType();
4586
4587 // If the initializer is the address of an overloaded function, try
4588 // to resolve the overloaded function. If all goes well, T2 is the
4589 // type of the resulting function.
4590 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4591 DeclAccessPair Found;
4592 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4593 Init, ToType, false, Found))
4594 T2 = Fn->getType();
4595 }
4596
4597 // Compute some basic properties of the types and the initializer.
4598 bool dummy1 = false;
4599 bool dummy2 = false;
4600 bool dummy3 = false;
4601 Sema::ReferenceCompareResult RefRelationship
4602 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4603 dummy2, dummy3);
4604
Richard Smith4d2bbd72013-09-06 01:22:42 +00004605 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004606 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4607 SuppressUserConversions,
4608 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004609 }
Sebastian Redldf888642011-12-03 14:54:30 +00004610 }
4611
4612 // Otherwise, we bind the reference to a temporary created from the
4613 // initializer list.
4614 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4615 InOverloadResolution,
4616 AllowObjCWritebackConversion);
4617 if (Result.isFailure())
4618 return Result;
4619 assert(!Result.isEllipsis() &&
4620 "Sub-initialization cannot result in ellipsis conversion.");
4621
4622 // Can we even bind to a temporary?
4623 if (ToType->isRValueReferenceType() ||
4624 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4625 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4626 Result.UserDefined.After;
4627 SCS.ReferenceBinding = true;
4628 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4629 SCS.BindsToRvalue = true;
4630 SCS.BindsToFunctionLvalue = false;
4631 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4632 SCS.ObjCLifetimeConversionBinding = false;
4633 } else
4634 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4635 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004636 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004637 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004638
4639 // C++11 [over.ics.list]p6:
4640 // Otherwise, if the parameter type is not a class:
4641 if (!ToType->isRecordType()) {
4642 // - if the initializer list has one element, the implicit conversion
4643 // sequence is the one required to convert the element to the
4644 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004645 unsigned NumInits = From->getNumInits();
4646 if (NumInits == 1)
4647 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4648 SuppressUserConversions,
4649 InOverloadResolution,
4650 AllowObjCWritebackConversion);
4651 // - if the initializer list has no elements, the implicit conversion
4652 // sequence is the identity conversion.
4653 else if (NumInits == 0) {
4654 Result.setStandard();
4655 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004656 Result.Standard.setFromType(ToType);
4657 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004658 }
4659 return Result;
4660 }
4661
4662 // C++11 [over.ics.list]p7:
4663 // In all cases other than those enumerated above, no conversion is possible
4664 return Result;
4665}
4666
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004667/// TryCopyInitialization - Try to copy-initialize a value of type
4668/// ToType from the expression From. Return the implicit conversion
4669/// sequence required to pass this argument, which may be a bad
4670/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004671/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004672/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004673static ImplicitConversionSequence
4674TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004676 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004677 bool AllowObjCWritebackConversion,
4678 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004679 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4680 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4681 InOverloadResolution,AllowObjCWritebackConversion);
4682
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004683 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004684 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004685 /*FIXME:*/From->getLocStart(),
4686 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004687 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004688
John McCall5c32be02010-08-24 20:38:10 +00004689 return TryImplicitConversion(S, From, ToType,
4690 SuppressUserConversions,
4691 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004692 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004693 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004694 AllowObjCWritebackConversion,
4695 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004696}
4697
Anna Zaks1b068122011-07-28 19:46:48 +00004698static bool TryCopyInitialization(const CanQualType FromQTy,
4699 const CanQualType ToQTy,
4700 Sema &S,
4701 SourceLocation Loc,
4702 ExprValueKind FromVK) {
4703 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4704 ImplicitConversionSequence ICS =
4705 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4706
4707 return !ICS.isBad();
4708}
4709
Douglas Gregor436424c2008-11-18 23:14:02 +00004710/// TryObjectArgumentInitialization - Try to initialize the object
4711/// parameter of the given member function (@c Method) from the
4712/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004713static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004714TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004715 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004716 CXXMethodDecl *Method,
4717 CXXRecordDecl *ActingContext) {
4718 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004719 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4720 // const volatile object.
4721 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4722 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004723 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004724
4725 // Set up the conversion sequence as a "bad" conversion, to allow us
4726 // to exit early.
4727 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004728
4729 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004730 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004731 FromType = PT->getPointeeType();
4732
Douglas Gregor02824322011-01-26 19:30:28 +00004733 // When we had a pointer, it's implicitly dereferenced, so we
4734 // better have an lvalue.
4735 assert(FromClassification.isLValue());
4736 }
4737
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004738 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004739
Douglas Gregor02824322011-01-26 19:30:28 +00004740 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004741 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004742 // parameter is
4743 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004744 // - "lvalue reference to cv X" for functions declared without a
4745 // ref-qualifier or with the & ref-qualifier
4746 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004747 // ref-qualifier
4748 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004749 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004750 // cv-qualification on the member function declaration.
4751 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004753 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004754 // (C++ [over.match.funcs]p5). We perform a simplified version of
4755 // reference binding here, that allows class rvalues to bind to
4756 // non-constant references.
4757
Douglas Gregor02824322011-01-26 19:30:28 +00004758 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004759 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004761 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004762 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004763 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004764 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004765 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004766 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004767
4768 // Check that we have either the same type or a derived type. It
4769 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004770 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004771 ImplicitConversionKind SecondKind;
4772 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4773 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004774 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004775 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004776 else {
John McCall65eb8792010-02-25 01:37:24 +00004777 ICS.setBad(BadConversionSequence::unrelated_class,
4778 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004779 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004780 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004781
Douglas Gregor02824322011-01-26 19:30:28 +00004782 // Check the ref-qualifier.
4783 switch (Method->getRefQualifier()) {
4784 case RQ_None:
4785 // Do nothing; we don't care about lvalueness or rvalueness.
4786 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787
Douglas Gregor02824322011-01-26 19:30:28 +00004788 case RQ_LValue:
4789 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4790 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004791 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004792 ImplicitParamType);
4793 return ICS;
4794 }
4795 break;
4796
4797 case RQ_RValue:
4798 if (!FromClassification.isRValue()) {
4799 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004801 ImplicitParamType);
4802 return ICS;
4803 }
4804 break;
4805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004806
Douglas Gregor436424c2008-11-18 23:14:02 +00004807 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004808 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004809 ICS.Standard.setAsIdentityConversion();
4810 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004811 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004812 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004813 ICS.Standard.ReferenceBinding = true;
4814 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004816 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004817 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4818 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4819 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004820 return ICS;
4821}
4822
4823/// PerformObjectArgumentInitialization - Perform initialization of
4824/// the implicit object parameter for the given Method with the given
4825/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004826ExprResult
4827Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004828 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004829 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004830 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004831 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004832 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004833 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004834
Douglas Gregor02824322011-01-26 19:30:28 +00004835 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004836 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004837 FromRecordType = PT->getPointeeType();
4838 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004839 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004840 } else {
4841 FromRecordType = From->getType();
4842 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004843 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004844 }
4845
John McCall6e9f8f62009-12-03 04:06:58 +00004846 // Note that we always use the true parent context when performing
4847 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004848 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004849 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4850 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004851 if (ICS.isBad()) {
4852 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4853 Qualifiers FromQs = FromRecordType.getQualifiers();
4854 Qualifiers ToQs = DestType.getQualifiers();
4855 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4856 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004857 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004858 diag::err_member_function_call_bad_cvr)
4859 << Method->getDeclName() << FromRecordType << (CVR - 1)
4860 << From->getSourceRange();
4861 Diag(Method->getLocation(), diag::note_previous_decl)
4862 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004863 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004864 }
4865 }
4866
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004867 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004868 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004869 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004870 }
Mike Stump11289f42009-09-09 15:08:12 +00004871
John Wiegley01296292011-04-08 18:41:53 +00004872 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4873 ExprResult FromRes =
4874 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4875 if (FromRes.isInvalid())
4876 return ExprError();
4877 From = FromRes.take();
4878 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004879
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004880 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004881 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004882 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004883 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004884}
4885
Douglas Gregor5fb53972009-01-14 15:45:31 +00004886/// TryContextuallyConvertToBool - Attempt to contextually convert the
4887/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004888static ImplicitConversionSequence
4889TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004890 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004891 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004892 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004893 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004894 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004895 /*AllowObjCWritebackConversion=*/false,
4896 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004897}
4898
4899/// PerformContextuallyConvertToBool - Perform a contextual conversion
4900/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004901ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004902 if (checkPlaceholderForOverload(*this, From))
4903 return ExprError();
4904
John McCall5c32be02010-08-24 20:38:10 +00004905 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004906 if (!ICS.isBad())
4907 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004908
Fariborz Jahanian76197412009-11-18 18:26:29 +00004909 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004910 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004911 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004912 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004913 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004914}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004915
Richard Smithf8379a02012-01-18 23:55:52 +00004916/// Check that the specified conversion is permitted in a converted constant
4917/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4918/// is acceptable.
4919static bool CheckConvertedConstantConversions(Sema &S,
4920 StandardConversionSequence &SCS) {
4921 // Since we know that the target type is an integral or unscoped enumeration
4922 // type, most conversion kinds are impossible. All possible First and Third
4923 // conversions are fine.
4924 switch (SCS.Second) {
4925 case ICK_Identity:
4926 case ICK_Integral_Promotion:
4927 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004928 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004929 return true;
4930
4931 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004932 // Conversion from an integral or unscoped enumeration type to bool is
4933 // classified as ICK_Boolean_Conversion, but it's also an integral
4934 // conversion, so it's permitted in a converted constant expression.
4935 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4936 SCS.getToType(2)->isBooleanType();
4937
Richard Smithf8379a02012-01-18 23:55:52 +00004938 case ICK_Floating_Integral:
4939 case ICK_Complex_Real:
4940 return false;
4941
4942 case ICK_Lvalue_To_Rvalue:
4943 case ICK_Array_To_Pointer:
4944 case ICK_Function_To_Pointer:
4945 case ICK_NoReturn_Adjustment:
4946 case ICK_Qualification:
4947 case ICK_Compatible_Conversion:
4948 case ICK_Vector_Conversion:
4949 case ICK_Vector_Splat:
4950 case ICK_Derived_To_Base:
4951 case ICK_Pointer_Conversion:
4952 case ICK_Pointer_Member:
4953 case ICK_Block_Pointer_Conversion:
4954 case ICK_Writeback_Conversion:
4955 case ICK_Floating_Promotion:
4956 case ICK_Complex_Promotion:
4957 case ICK_Complex_Conversion:
4958 case ICK_Floating_Conversion:
4959 case ICK_TransparentUnionConversion:
4960 llvm_unreachable("unexpected second conversion kind");
4961
4962 case ICK_Num_Conversion_Kinds:
4963 break;
4964 }
4965
4966 llvm_unreachable("unknown conversion kind");
4967}
4968
4969/// CheckConvertedConstantExpression - Check that the expression From is a
4970/// converted constant expression of type T, perform the conversion and produce
4971/// the converted expression, per C++11 [expr.const]p3.
4972ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4973 llvm::APSInt &Value,
4974 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004975 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004976 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4977
4978 if (checkPlaceholderForOverload(*this, From))
4979 return ExprError();
4980
4981 // C++11 [expr.const]p3 with proposed wording fixes:
4982 // A converted constant expression of type T is a core constant expression,
4983 // implicitly converted to a prvalue of type T, where the converted
4984 // expression is a literal constant expression and the implicit conversion
4985 // sequence contains only user-defined conversions, lvalue-to-rvalue
4986 // conversions, integral promotions, and integral conversions other than
4987 // narrowing conversions.
4988 ImplicitConversionSequence ICS =
4989 TryImplicitConversion(From, T,
4990 /*SuppressUserConversions=*/false,
4991 /*AllowExplicit=*/false,
4992 /*InOverloadResolution=*/false,
4993 /*CStyle=*/false,
4994 /*AllowObjcWritebackConversion=*/false);
4995 StandardConversionSequence *SCS = 0;
4996 switch (ICS.getKind()) {
4997 case ImplicitConversionSequence::StandardConversion:
4998 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004999 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005000 diag::err_typecheck_converted_constant_expression_disallowed)
5001 << From->getType() << From->getSourceRange() << T;
5002 SCS = &ICS.Standard;
5003 break;
5004 case ImplicitConversionSequence::UserDefinedConversion:
5005 // We are converting from class type to an integral or enumeration type, so
5006 // the Before sequence must be trivial.
5007 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005008 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005009 diag::err_typecheck_converted_constant_expression_disallowed)
5010 << From->getType() << From->getSourceRange() << T;
5011 SCS = &ICS.UserDefined.After;
5012 break;
5013 case ImplicitConversionSequence::AmbiguousConversion:
5014 case ImplicitConversionSequence::BadConversion:
5015 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005016 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005017 diag::err_typecheck_converted_constant_expression)
5018 << From->getType() << From->getSourceRange() << T;
5019 return ExprError();
5020
5021 case ImplicitConversionSequence::EllipsisConversion:
5022 llvm_unreachable("ellipsis conversion in converted constant expression");
5023 }
5024
5025 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5026 if (Result.isInvalid())
5027 return Result;
5028
5029 // Check for a narrowing implicit conversion.
5030 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005031 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005032 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5033 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005034 case NK_Variable_Narrowing:
5035 // Implicit conversion to a narrower type, and the value is not a constant
5036 // expression. We'll diagnose this in a moment.
5037 case NK_Not_Narrowing:
5038 break;
5039
5040 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005041 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005042 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005043 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005044 break;
5045
5046 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005047 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005048 << CCE << /*Constant*/0 << From->getType() << T;
5049 break;
5050 }
5051
5052 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005053 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005054 Expr::EvalResult Eval;
5055 Eval.Diag = &Notes;
5056
Douglas Gregorebe2db72013-04-08 23:24:07 +00005057 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005058 // The expression can't be folded, so we can't keep it at this position in
5059 // the AST.
5060 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005061 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005062 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005063
5064 if (Notes.empty()) {
5065 // It's a constant expression.
5066 return Result;
5067 }
Richard Smithf8379a02012-01-18 23:55:52 +00005068 }
5069
5070 // It's not a constant expression. Produce an appropriate diagnostic.
5071 if (Notes.size() == 1 &&
5072 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5073 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5074 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005075 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005076 << CCE << From->getSourceRange();
5077 for (unsigned I = 0; I < Notes.size(); ++I)
5078 Diag(Notes[I].first, Notes[I].second);
5079 }
Richard Smith911e1422012-01-30 22:27:01 +00005080 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005081}
5082
John McCallfec112d2011-09-09 06:11:02 +00005083/// dropPointerConversions - If the given standard conversion sequence
5084/// involves any pointer conversions, remove them. This may change
5085/// the result type of the conversion sequence.
5086static void dropPointerConversion(StandardConversionSequence &SCS) {
5087 if (SCS.Second == ICK_Pointer_Conversion) {
5088 SCS.Second = ICK_Identity;
5089 SCS.Third = ICK_Identity;
5090 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5091 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005092}
John McCall5c32be02010-08-24 20:38:10 +00005093
John McCallfec112d2011-09-09 06:11:02 +00005094/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5095/// convert the expression From to an Objective-C pointer type.
5096static ImplicitConversionSequence
5097TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5098 // Do an implicit conversion to 'id'.
5099 QualType Ty = S.Context.getObjCIdType();
5100 ImplicitConversionSequence ICS
5101 = TryImplicitConversion(S, From, Ty,
5102 // FIXME: Are these flags correct?
5103 /*SuppressUserConversions=*/false,
5104 /*AllowExplicit=*/true,
5105 /*InOverloadResolution=*/false,
5106 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005107 /*AllowObjCWritebackConversion=*/false,
5108 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005109
5110 // Strip off any final conversions to 'id'.
5111 switch (ICS.getKind()) {
5112 case ImplicitConversionSequence::BadConversion:
5113 case ImplicitConversionSequence::AmbiguousConversion:
5114 case ImplicitConversionSequence::EllipsisConversion:
5115 break;
5116
5117 case ImplicitConversionSequence::UserDefinedConversion:
5118 dropPointerConversion(ICS.UserDefined.After);
5119 break;
5120
5121 case ImplicitConversionSequence::StandardConversion:
5122 dropPointerConversion(ICS.Standard);
5123 break;
5124 }
5125
5126 return ICS;
5127}
5128
5129/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5130/// conversion of the expression From to an Objective-C pointer type.
5131ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005132 if (checkPlaceholderForOverload(*this, From))
5133 return ExprError();
5134
John McCall8b07ec22010-05-15 11:32:37 +00005135 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005136 ImplicitConversionSequence ICS =
5137 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005138 if (!ICS.isBad())
5139 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005140 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005141}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005142
Richard Smith8dd34252012-02-04 07:07:42 +00005143/// Determine whether the provided type is an integral type, or an enumeration
5144/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005145bool Sema::ICEConvertDiagnoser::match(QualType T) {
5146 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5147 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005148}
5149
Larisse Voufo236bec22013-06-10 06:50:24 +00005150static ExprResult
5151diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5152 Sema::ContextualImplicitConverter &Converter,
5153 QualType T, UnresolvedSetImpl &ViableConversions) {
5154
5155 if (Converter.Suppress)
5156 return ExprError();
5157
5158 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5159 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5160 CXXConversionDecl *Conv =
5161 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5162 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5163 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5164 }
5165 return SemaRef.Owned(From);
5166}
5167
5168static bool
5169diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5170 Sema::ContextualImplicitConverter &Converter,
5171 QualType T, bool HadMultipleCandidates,
5172 UnresolvedSetImpl &ExplicitConversions) {
5173 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5174 DeclAccessPair Found = ExplicitConversions[0];
5175 CXXConversionDecl *Conversion =
5176 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5177
5178 // The user probably meant to invoke the given explicit
5179 // conversion; use it.
5180 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5181 std::string TypeStr;
5182 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5183
5184 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5185 << FixItHint::CreateInsertion(From->getLocStart(),
5186 "static_cast<" + TypeStr + ">(")
5187 << FixItHint::CreateInsertion(
5188 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5189 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5190
5191 // If we aren't in a SFINAE context, build a call to the
5192 // explicit conversion function.
5193 if (SemaRef.isSFINAEContext())
5194 return true;
5195
5196 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5197 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5198 HadMultipleCandidates);
5199 if (Result.isInvalid())
5200 return true;
5201 // Record usage of conversion in an implicit cast.
5202 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5203 CK_UserDefinedConversion, Result.get(), 0,
5204 Result.get()->getValueKind());
5205 }
5206 return false;
5207}
5208
5209static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5210 Sema::ContextualImplicitConverter &Converter,
5211 QualType T, bool HadMultipleCandidates,
5212 DeclAccessPair &Found) {
5213 CXXConversionDecl *Conversion =
5214 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5215 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5216
5217 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5218 if (!Converter.SuppressConversion) {
5219 if (SemaRef.isSFINAEContext())
5220 return true;
5221
5222 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5223 << From->getSourceRange();
5224 }
5225
5226 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5227 HadMultipleCandidates);
5228 if (Result.isInvalid())
5229 return true;
5230 // Record usage of conversion in an implicit cast.
5231 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5232 CK_UserDefinedConversion, Result.get(), 0,
5233 Result.get()->getValueKind());
5234 return false;
5235}
5236
5237static ExprResult finishContextualImplicitConversion(
5238 Sema &SemaRef, SourceLocation Loc, Expr *From,
5239 Sema::ContextualImplicitConverter &Converter) {
5240 if (!Converter.match(From->getType()) && !Converter.Suppress)
5241 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5242 << From->getSourceRange();
5243
5244 return SemaRef.DefaultLvalueConversion(From);
5245}
5246
5247static void
5248collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5249 UnresolvedSetImpl &ViableConversions,
5250 OverloadCandidateSet &CandidateSet) {
5251 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5252 DeclAccessPair FoundDecl = ViableConversions[I];
5253 NamedDecl *D = FoundDecl.getDecl();
5254 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5255 if (isa<UsingShadowDecl>(D))
5256 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5257
5258 CXXConversionDecl *Conv;
5259 FunctionTemplateDecl *ConvTemplate;
5260 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5261 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5262 else
5263 Conv = cast<CXXConversionDecl>(D);
5264
5265 if (ConvTemplate)
5266 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005267 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5268 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005269 else
5270 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005271 ToType, CandidateSet,
5272 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005273 }
5274}
5275
Richard Smithccc11812013-05-21 19:05:48 +00005276/// \brief Attempt to convert the given expression to a type which is accepted
5277/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005278///
Richard Smithccc11812013-05-21 19:05:48 +00005279/// This routine will attempt to convert an expression of class type to a
5280/// type accepted by the specified converter. In C++11 and before, the class
5281/// must have a single non-explicit conversion function converting to a matching
5282/// type. In C++1y, there can be multiple such conversion functions, but only
5283/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005284///
Douglas Gregor4799d032010-06-30 00:20:43 +00005285/// \param Loc The source location of the construct that requires the
5286/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005287///
James Dennett18348b62012-06-22 08:52:37 +00005288/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005289///
Richard Smithccc11812013-05-21 19:05:48 +00005290/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005291///
Douglas Gregor4799d032010-06-30 00:20:43 +00005292/// \returns The expression, converted to an integral or enumeration type if
5293/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005294ExprResult Sema::PerformContextualImplicitConversion(
5295 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005296 // We can't perform any more checking for type-dependent expressions.
5297 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005298 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005299
Eli Friedman1da70392012-01-26 00:26:18 +00005300 // Process placeholders immediately.
5301 if (From->hasPlaceholderType()) {
5302 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005303 if (result.isInvalid())
5304 return result;
Eli Friedman1da70392012-01-26 00:26:18 +00005305 From = result.take();
5306 }
5307
Richard Smithccc11812013-05-21 19:05:48 +00005308 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005309 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005310 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005311 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005312
5313 // FIXME: Check for missing '()' if T is a function type?
5314
Richard Smithccc11812013-05-21 19:05:48 +00005315 // We can only perform contextual implicit conversions on objects of class
5316 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005317 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005318 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005319 if (!Converter.Suppress)
5320 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005321 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005322 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005323
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005324 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005325 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005326 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005327 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005328
5329 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5330 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5331
Craig Toppere14c0f82014-03-12 04:55:44 +00005332 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
Richard Smithccc11812013-05-21 19:05:48 +00005333 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005334 }
Richard Smithccc11812013-05-21 19:05:48 +00005335 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005336
5337 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005338 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005339
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005340 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005341 UnresolvedSet<4>
5342 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005343 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005344 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005345 CXXRecordDecl::conversion_iterator> Conversions =
5346 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005347
Larisse Voufo236bec22013-06-10 06:50:24 +00005348 bool HadMultipleCandidates =
5349 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005350
Larisse Voufo236bec22013-06-10 06:50:24 +00005351 // To check that there is only one target type, in C++1y:
5352 QualType ToType;
5353 bool HasUniqueTargetType = true;
5354
5355 // Collect explicit or viable (potentially in C++1y) conversions.
5356 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5357 E = Conversions.second;
5358 I != E; ++I) {
5359 NamedDecl *D = (*I)->getUnderlyingDecl();
5360 CXXConversionDecl *Conversion;
5361 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5362 if (ConvTemplate) {
5363 if (getLangOpts().CPlusPlus1y)
5364 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5365 else
5366 continue; // C++11 does not consider conversion operator templates(?).
5367 } else
5368 Conversion = cast<CXXConversionDecl>(D);
5369
5370 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5371 "Conversion operator templates are considered potentially "
5372 "viable in C++1y");
5373
5374 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5375 if (Converter.match(CurToType) || ConvTemplate) {
5376
5377 if (Conversion->isExplicit()) {
5378 // FIXME: For C++1y, do we need this restriction?
5379 // cf. diagnoseNoViableConversion()
5380 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005381 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005382 } else {
5383 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5384 if (ToType.isNull())
5385 ToType = CurToType.getUnqualifiedType();
5386 else if (HasUniqueTargetType &&
5387 (CurToType.getUnqualifiedType() != ToType))
5388 HasUniqueTargetType = false;
5389 }
5390 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005391 }
Richard Smith8dd34252012-02-04 07:07:42 +00005392 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005393 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005394
Larisse Voufo236bec22013-06-10 06:50:24 +00005395 if (getLangOpts().CPlusPlus1y) {
5396 // C++1y [conv]p6:
5397 // ... An expression e of class type E appearing in such a context
5398 // is said to be contextually implicitly converted to a specified
5399 // type T and is well-formed if and only if e can be implicitly
5400 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005401 // for conversion functions whose return type is cv T or reference to
5402 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005403 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005404
Larisse Voufo236bec22013-06-10 06:50:24 +00005405 // If no unique T is found:
5406 if (ToType.isNull()) {
5407 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5408 HadMultipleCandidates,
5409 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005410 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005411 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005413
Larisse Voufo236bec22013-06-10 06:50:24 +00005414 // If more than one unique Ts are found:
5415 if (!HasUniqueTargetType)
5416 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5417 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005418
Larisse Voufo236bec22013-06-10 06:50:24 +00005419 // If one unique T is found:
5420 // First, build a candidate set from the previously recorded
5421 // potentially viable conversions.
5422 OverloadCandidateSet CandidateSet(Loc);
5423 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5424 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005425
Larisse Voufo236bec22013-06-10 06:50:24 +00005426 // Then, perform overload resolution over the candidate set.
5427 OverloadCandidateSet::iterator Best;
5428 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5429 case OR_Success: {
5430 // Apply this conversion.
5431 DeclAccessPair Found =
5432 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5433 if (recordConversion(*this, Loc, From, Converter, T,
5434 HadMultipleCandidates, Found))
5435 return ExprError();
5436 break;
5437 }
5438 case OR_Ambiguous:
5439 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5440 ViableConversions);
5441 case OR_No_Viable_Function:
5442 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5443 HadMultipleCandidates,
5444 ExplicitConversions))
5445 return ExprError();
5446 // fall through 'OR_Deleted' case.
5447 case OR_Deleted:
5448 // We'll complain below about a non-integral condition type.
5449 break;
5450 }
5451 } else {
5452 switch (ViableConversions.size()) {
5453 case 0: {
5454 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5455 HadMultipleCandidates,
5456 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005457 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005458
Larisse Voufo236bec22013-06-10 06:50:24 +00005459 // We'll complain below about a non-integral condition type.
5460 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005461 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005462 case 1: {
5463 // Apply this conversion.
5464 DeclAccessPair Found = ViableConversions[0];
5465 if (recordConversion(*this, Loc, From, Converter, T,
5466 HadMultipleCandidates, Found))
5467 return ExprError();
5468 break;
5469 }
5470 default:
5471 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5472 ViableConversions);
5473 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005475
Larisse Voufo236bec22013-06-10 06:50:24 +00005476 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005477}
5478
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005479/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005480/// candidate functions, using the given function call arguments. If
5481/// @p SuppressUserConversions, then don't allow user-defined
5482/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005483///
James Dennett2a4d13c2012-06-15 07:13:21 +00005484/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005485/// based on an incomplete set of function arguments. This feature is used by
5486/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005487void
5488Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005489 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005490 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005491 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005492 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005493 bool PartialOverloading,
5494 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005495 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005496 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005497 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005498 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005499 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005500
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005501 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005502 if (!isa<CXXConstructorDecl>(Method)) {
5503 // If we get here, it's because we're calling a member function
5504 // that is named without a member access expression (e.g.,
5505 // "this->f") that was either written explicitly or created
5506 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005507 // function, e.g., X::f(). We use an empty type for the implied
5508 // object argument (C++ [over.call.func]p3), and the acting context
5509 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005510 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005511 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005512 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005513 return;
5514 }
5515 // We treat a constructor like a non-member function, since its object
5516 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005517 }
5518
Douglas Gregorff7028a2009-11-13 23:59:09 +00005519 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005520 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005521
Richard Smith8b86f2d2013-11-04 01:48:18 +00005522 // C++11 [class.copy]p11: [DR1402]
5523 // A defaulted move constructor that is defined as deleted is ignored by
5524 // overload resolution.
5525 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5526 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5527 Constructor->isMoveConstructor())
5528 return;
5529
Douglas Gregor27381f32009-11-23 12:27:39 +00005530 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005531 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005532
Richard Smith8b86f2d2013-11-04 01:48:18 +00005533 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005534 // C++ [class.copy]p3:
5535 // A member function template is never instantiated to perform the copy
5536 // of a class object to an object of its class type.
5537 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005538 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005539 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005540 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5541 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005542 return;
5543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005544
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005545 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005546 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005547 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005548 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005549 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005550 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005551 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005552 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005553
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005554 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005555
5556 // (C++ 13.3.2p2): A candidate function having fewer than m
5557 // parameters is viable only if it has an ellipsis in its parameter
5558 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005559 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005560 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005561 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005562 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005563 return;
5564 }
5565
5566 // (C++ 13.3.2p2): A candidate function having more than m parameters
5567 // is viable only if the (m+1)st parameter has a default argument
5568 // (8.3.6). For the purposes of overload resolution, the
5569 // parameter list is truncated on the right, so that there are
5570 // exactly m parameters.
5571 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005572 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005573 // Not enough arguments.
5574 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005575 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005576 return;
5577 }
5578
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005579 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005580 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005581 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5582 if (CheckCUDATarget(Caller, Function)) {
5583 Candidate.Viable = false;
5584 Candidate.FailureKind = ovl_fail_bad_target;
5585 return;
5586 }
5587
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005588 // Determine the implicit conversion sequences for each of the
5589 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005590 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005591 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005592 // (C++ 13.3.2p3): for F to be a viable function, there shall
5593 // exist for each argument an implicit conversion sequence
5594 // (13.3.3.1) that converts that argument to the corresponding
5595 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005596 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005597 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005598 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005599 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005600 /*InOverloadResolution=*/true,
5601 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005602 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005603 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005604 if (Candidate.Conversions[ArgIdx].isBad()) {
5605 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005606 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005607 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005608 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005609 } else {
5610 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5611 // argument for which there is no corresponding parameter is
5612 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005613 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005614 }
5615 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005616
5617 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5618 Candidate.Viable = false;
5619 Candidate.FailureKind = ovl_fail_enable_if;
5620 Candidate.DeductionFailure.Data = FailedAttr;
5621 return;
5622 }
5623}
5624
5625static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5626
5627EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5628 bool MissingImplicitThis) {
5629 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5630 // we need to find the first failing one.
5631 if (!Function->hasAttrs())
5632 return 0;
5633 AttrVec Attrs = Function->getAttrs();
5634 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5635 IsNotEnableIfAttr);
5636 if (Attrs.begin() == E)
5637 return 0;
5638 std::reverse(Attrs.begin(), E);
5639
5640 SFINAETrap Trap(*this);
5641
5642 // Convert the arguments.
5643 SmallVector<Expr *, 16> ConvertedArgs;
5644 bool InitializationFailed = false;
5645 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5646 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
Nick Lewyckyb8336b72014-02-28 05:26:13 +00005647 !cast<CXXMethodDecl>(Function)->isStatic() &&
5648 !isa<CXXConstructorDecl>(Function)) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005649 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5650 ExprResult R =
5651 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5652 Method, Method);
5653 if (R.isInvalid()) {
5654 InitializationFailed = true;
5655 break;
5656 }
5657 ConvertedArgs.push_back(R.take());
5658 } else {
5659 ExprResult R =
5660 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5661 Context,
5662 Function->getParamDecl(i)),
5663 SourceLocation(),
5664 Args[i]);
5665 if (R.isInvalid()) {
5666 InitializationFailed = true;
5667 break;
5668 }
5669 ConvertedArgs.push_back(R.take());
5670 }
5671 }
5672
5673 if (InitializationFailed || Trap.hasErrorOccurred())
5674 return cast<EnableIfAttr>(Attrs[0]);
5675
5676 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5677 APValue Result;
5678 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5679 if (!EIA->getCond()->EvaluateWithSubstitution(
5680 Result, Context, Function,
5681 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(),
5682 ConvertedArgs.size())) ||
5683 !Result.isInt() || !Result.getInt().getBoolValue()) {
5684 return EIA;
5685 }
5686 }
5687 return 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005688}
5689
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005690/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005691/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005692void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005693 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005694 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005695 bool SuppressUserConversions,
5696 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005697 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005698 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005700 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005701 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005702 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005703 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005704 Args.slice(1), CandidateSet,
5705 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005706 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005707 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005708 SuppressUserConversions);
5709 } else {
John McCalla0296f72010-03-19 07:35:19 +00005710 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005711 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5712 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005713 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005714 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005715 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005716 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005717 Args[0]->Classify(Context), Args.slice(1),
5718 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005719 else
John McCalla0296f72010-03-19 07:35:19 +00005720 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005721 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005722 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005723 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005724 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005725}
5726
John McCallf0f1cf02009-11-17 07:50:12 +00005727/// AddMethodCandidate - Adds a named decl (which is some kind of
5728/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005729void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005730 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005731 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005732 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005733 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005734 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005735 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005736 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005737
5738 if (isa<UsingShadowDecl>(Decl))
5739 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005740
John McCallf0f1cf02009-11-17 07:50:12 +00005741 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5742 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5743 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005744 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5745 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005746 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005747 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005748 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005749 } else {
John McCalla0296f72010-03-19 07:35:19 +00005750 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005751 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005752 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005753 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005754 }
5755}
5756
Douglas Gregor436424c2008-11-18 23:14:02 +00005757/// AddMethodCandidate - Adds the given C++ member function to the set
5758/// of candidate functions, using the given function call arguments
5759/// and the object argument (@c Object). For example, in a call
5760/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5761/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5762/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005763/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005764void
John McCalla0296f72010-03-19 07:35:19 +00005765Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005766 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005767 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005768 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005769 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005770 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005771 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005772 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005773 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005774 assert(!isa<CXXConstructorDecl>(Method) &&
5775 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005776
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005777 if (!CandidateSet.isNewCandidate(Method))
5778 return;
5779
Richard Smith8b86f2d2013-11-04 01:48:18 +00005780 // C++11 [class.copy]p23: [DR1402]
5781 // A defaulted move assignment operator that is defined as deleted is
5782 // ignored by overload resolution.
5783 if (Method->isDefaulted() && Method->isDeleted() &&
5784 Method->isMoveAssignmentOperator())
5785 return;
5786
Douglas Gregor27381f32009-11-23 12:27:39 +00005787 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005788 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005789
Douglas Gregor436424c2008-11-18 23:14:02 +00005790 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005791 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005792 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005793 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005794 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005795 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005796 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005797
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005798 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005799
5800 // (C++ 13.3.2p2): A candidate function having fewer than m
5801 // parameters is viable only if it has an ellipsis in its parameter
5802 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005803 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005804 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005805 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005806 return;
5807 }
5808
5809 // (C++ 13.3.2p2): A candidate function having more than m parameters
5810 // is viable only if the (m+1)st parameter has a default argument
5811 // (8.3.6). For the purposes of overload resolution, the
5812 // parameter list is truncated on the right, so that there are
5813 // exactly m parameters.
5814 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005815 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005816 // Not enough arguments.
5817 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005818 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005819 return;
5820 }
5821
5822 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005823
John McCall6e9f8f62009-12-03 04:06:58 +00005824 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005825 // The implicit object argument is ignored.
5826 Candidate.IgnoreObjectArgument = true;
5827 else {
5828 // Determine the implicit conversion sequence for the object
5829 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005830 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005831 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5832 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005833 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005834 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005835 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005836 return;
5837 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005838 }
5839
5840 // Determine the implicit conversion sequences for each of the
5841 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005842 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005843 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005844 // (C++ 13.3.2p3): for F to be a viable function, there shall
5845 // exist for each argument an implicit conversion sequence
5846 // (13.3.3.1) that converts that argument to the corresponding
5847 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005848 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005849 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005850 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005851 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005852 /*InOverloadResolution=*/true,
5853 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005854 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005855 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005856 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005857 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005858 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005859 }
5860 } else {
5861 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5862 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005863 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005864 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005865 }
5866 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005867
5868 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5869 Candidate.Viable = false;
5870 Candidate.FailureKind = ovl_fail_enable_if;
5871 Candidate.DeductionFailure.Data = FailedAttr;
5872 return;
5873 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005874}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005875
Douglas Gregor97628d62009-08-21 00:16:32 +00005876/// \brief Add a C++ member function template as a candidate to the candidate
5877/// set, using template argument deduction to produce an appropriate member
5878/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005879void
Douglas Gregor97628d62009-08-21 00:16:32 +00005880Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005881 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005882 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005883 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005884 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005885 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005886 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005887 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005888 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005889 if (!CandidateSet.isNewCandidate(MethodTmpl))
5890 return;
5891
Douglas Gregor97628d62009-08-21 00:16:32 +00005892 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005893 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005894 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005895 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005896 // candidate functions in the usual way.113) A given name can refer to one
5897 // or more function templates and also to a set of overloaded non-template
5898 // functions. In such a case, the candidate functions generated from each
5899 // function template are combined with the set of non-template candidate
5900 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005901 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005902 FunctionDecl *Specialization = 0;
5903 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005904 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5905 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005906 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005907 Candidate.FoundDecl = FoundDecl;
5908 Candidate.Function = MethodTmpl->getTemplatedDecl();
5909 Candidate.Viable = false;
5910 Candidate.FailureKind = ovl_fail_bad_deduction;
5911 Candidate.IsSurrogate = false;
5912 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005913 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005914 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005915 Info);
5916 return;
5917 }
Mike Stump11289f42009-09-09 15:08:12 +00005918
Douglas Gregor97628d62009-08-21 00:16:32 +00005919 // Add the function template specialization produced by template argument
5920 // deduction as a candidate.
5921 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005922 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005923 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005924 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005925 ActingContext, ObjectType, ObjectClassification, Args,
5926 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005927}
5928
Douglas Gregor05155d82009-08-21 23:19:43 +00005929/// \brief Add a C++ function template specialization as a candidate
5930/// in the candidate set, using template argument deduction to produce
5931/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005932void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005933Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005934 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005935 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005936 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005937 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005938 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005939 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5940 return;
5941
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005942 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005943 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005944 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005945 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005946 // candidate functions in the usual way.113) A given name can refer to one
5947 // or more function templates and also to a set of overloaded non-template
5948 // functions. In such a case, the candidate functions generated from each
5949 // function template are combined with the set of non-template candidate
5950 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005951 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005952 FunctionDecl *Specialization = 0;
5953 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005954 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5955 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005956 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005957 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005958 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5959 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005960 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005961 Candidate.IsSurrogate = false;
5962 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005963 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005964 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005965 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005966 return;
5967 }
Mike Stump11289f42009-09-09 15:08:12 +00005968
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005969 // Add the function template specialization produced by template argument
5970 // deduction as a candidate.
5971 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005972 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005973 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005974}
Mike Stump11289f42009-09-09 15:08:12 +00005975
Douglas Gregor4b60a152013-11-07 22:34:54 +00005976/// Determine whether this is an allowable conversion from the result
5977/// of an explicit conversion operator to the expected type, per C++
5978/// [over.match.conv]p1 and [over.match.ref]p1.
5979///
5980/// \param ConvType The return type of the conversion function.
5981///
5982/// \param ToType The type we are converting to.
5983///
5984/// \param AllowObjCPointerConversion Allow a conversion from one
5985/// Objective-C pointer to another.
5986///
5987/// \returns true if the conversion is allowable, false otherwise.
5988static bool isAllowableExplicitConversion(Sema &S,
5989 QualType ConvType, QualType ToType,
5990 bool AllowObjCPointerConversion) {
5991 QualType ToNonRefType = ToType.getNonReferenceType();
5992
5993 // Easy case: the types are the same.
5994 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
5995 return true;
5996
5997 // Allow qualification conversions.
5998 bool ObjCLifetimeConversion;
5999 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6000 ObjCLifetimeConversion))
6001 return true;
6002
6003 // If we're not allowed to consider Objective-C pointer conversions,
6004 // we're done.
6005 if (!AllowObjCPointerConversion)
6006 return false;
6007
6008 // Is this an Objective-C pointer conversion?
6009 bool IncompatibleObjC = false;
6010 QualType ConvertedType;
6011 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6012 IncompatibleObjC);
6013}
6014
Douglas Gregora1f013e2008-11-07 22:36:19 +00006015/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006016/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006017/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006018/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006019/// (which may or may not be the same type as the type that the
6020/// conversion function produces).
6021void
6022Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006023 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006024 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006025 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006026 OverloadCandidateSet& CandidateSet,
6027 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006028 assert(!Conversion->getDescribedFunctionTemplate() &&
6029 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006030 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006031 if (!CandidateSet.isNewCandidate(Conversion))
6032 return;
6033
Richard Smith2a7d4812013-05-04 07:00:32 +00006034 // If the conversion function has an undeduced return type, trigger its
6035 // deduction now.
6036 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6037 if (DeduceReturnType(Conversion, From->getExprLoc()))
6038 return;
6039 ConvType = Conversion->getConversionType().getNonReferenceType();
6040 }
6041
Richard Smith089c3162013-09-21 21:55:46 +00006042 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6043 // operator is only a candidate if its return type is the target type or
6044 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006045 if (Conversion->isExplicit() &&
6046 !isAllowableExplicitConversion(*this, ConvType, ToType,
6047 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006048 return;
6049
Douglas Gregor27381f32009-11-23 12:27:39 +00006050 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006051 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006052
Douglas Gregora1f013e2008-11-07 22:36:19 +00006053 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006054 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006055 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006056 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006057 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006058 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006059 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006060 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006061 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006062 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006063 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006064
Douglas Gregor6affc782010-08-19 15:37:02 +00006065 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006066 // For conversion functions, the function is considered to be a member of
6067 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006068 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006069 //
6070 // Determine the implicit conversion sequence for the implicit
6071 // object parameter.
6072 QualType ImplicitParamType = From->getType();
6073 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6074 ImplicitParamType = FromPtrType->getPointeeType();
6075 CXXRecordDecl *ConversionContext
6076 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006077
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006078 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006079 = TryObjectArgumentInitialization(*this, From->getType(),
6080 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006081 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006082
John McCall0d1da222010-01-12 00:44:57 +00006083 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006084 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006085 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006086 return;
6087 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006088
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006089 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006090 // derived to base as such conversions are given Conversion Rank. They only
6091 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6092 QualType FromCanon
6093 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6094 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6095 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6096 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006097 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006098 return;
6099 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100
Douglas Gregora1f013e2008-11-07 22:36:19 +00006101 // To determine what the conversion from the result of calling the
6102 // conversion function to the type we're eventually trying to
6103 // convert to (ToType), we need to synthesize a call to the
6104 // conversion function and attempt copy initialization from it. This
6105 // makes sure that we get the right semantics with respect to
6106 // lvalues/rvalues and the type. Fortunately, we can allocate this
6107 // call on the stack and we don't need its arguments to be
6108 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006109 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006110 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006111 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6112 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006113 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006114 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006115
Richard Smith48d24642011-07-13 22:53:21 +00006116 QualType ConversionType = Conversion->getConversionType();
6117 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006118 Candidate.Viable = false;
6119 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6120 return;
6121 }
6122
Richard Smith48d24642011-07-13 22:53:21 +00006123 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006124
Mike Stump11289f42009-09-09 15:08:12 +00006125 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006126 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6127 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006128 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006129 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006130 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006131 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006132 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006133 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006134 /*InOverloadResolution=*/false,
6135 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006136
John McCall0d1da222010-01-12 00:44:57 +00006137 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006138 case ImplicitConversionSequence::StandardConversion:
6139 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006140
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006141 // C++ [over.ics.user]p3:
6142 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006143 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006144 // shall have exact match rank.
6145 if (Conversion->getPrimaryTemplate() &&
6146 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6147 Candidate.Viable = false;
6148 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006149 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006150 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006151
Douglas Gregorcba72b12011-01-21 05:18:22 +00006152 // C++0x [dcl.init.ref]p5:
6153 // In the second case, if the reference is an rvalue reference and
6154 // the second standard conversion sequence of the user-defined
6155 // conversion sequence includes an lvalue-to-rvalue conversion, the
6156 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006157 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006158 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6159 Candidate.Viable = false;
6160 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006161 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006162 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006163 break;
6164
6165 case ImplicitConversionSequence::BadConversion:
6166 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006167 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006168 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006169
6170 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006171 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006172 "Can only end up with a standard conversion sequence or failure");
6173 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006174
6175 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6176 Candidate.Viable = false;
6177 Candidate.FailureKind = ovl_fail_enable_if;
6178 Candidate.DeductionFailure.Data = FailedAttr;
6179 return;
6180 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006181}
6182
Douglas Gregor05155d82009-08-21 23:19:43 +00006183/// \brief Adds a conversion function template specialization
6184/// candidate to the overload set, using template argument deduction
6185/// to deduce the template arguments of the conversion function
6186/// template from the type that we are converting to (C++
6187/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006188void
Douglas Gregor05155d82009-08-21 23:19:43 +00006189Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006190 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006191 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006192 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006193 OverloadCandidateSet &CandidateSet,
6194 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006195 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6196 "Only conversion function templates permitted here");
6197
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006198 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6199 return;
6200
Craig Toppere6706e42012-09-19 02:26:47 +00006201 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00006202 CXXConversionDecl *Specialization = 0;
6203 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006204 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006205 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006206 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006207 Candidate.FoundDecl = FoundDecl;
6208 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6209 Candidate.Viable = false;
6210 Candidate.FailureKind = ovl_fail_bad_deduction;
6211 Candidate.IsSurrogate = false;
6212 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006213 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006214 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006215 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006216 return;
6217 }
Mike Stump11289f42009-09-09 15:08:12 +00006218
Douglas Gregor05155d82009-08-21 23:19:43 +00006219 // Add the conversion function template specialization produced by
6220 // template argument deduction as a candidate.
6221 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006222 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006223 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006224}
6225
Douglas Gregorab7897a2008-11-19 22:57:39 +00006226/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6227/// converts the given @c Object to a function pointer via the
6228/// conversion function @c Conversion, and then attempts to call it
6229/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6230/// the type of function that we'll eventually be calling.
6231void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006232 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006233 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006234 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006235 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006236 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006237 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006238 if (!CandidateSet.isNewCandidate(Conversion))
6239 return;
6240
Douglas Gregor27381f32009-11-23 12:27:39 +00006241 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006242 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006243
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006244 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006245 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006246 Candidate.Function = 0;
6247 Candidate.Surrogate = Conversion;
6248 Candidate.Viable = true;
6249 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006250 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006251 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006252
6253 // Determine the implicit conversion sequence for the implicit
6254 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006255 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006256 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006257 Object->Classify(Context),
6258 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006259 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006260 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006261 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006262 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006263 return;
6264 }
6265
6266 // The first conversion is actually a user-defined conversion whose
6267 // first conversion is ObjectInit's standard conversion (which is
6268 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006269 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006270 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006271 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006272 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006273 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006274 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006275 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006276 = Candidate.Conversions[0].UserDefined.Before;
6277 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6278
Mike Stump11289f42009-09-09 15:08:12 +00006279 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006280 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006281
6282 // (C++ 13.3.2p2): A candidate function having fewer than m
6283 // parameters is viable only if it has an ellipsis in its parameter
6284 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006285 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006286 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006287 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006288 return;
6289 }
6290
6291 // Function types don't have any default arguments, so just check if
6292 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006293 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006294 // Not enough arguments.
6295 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006296 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006297 return;
6298 }
6299
6300 // Determine the implicit conversion sequences for each of the
6301 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006302 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006303 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006304 // (C++ 13.3.2p3): for F to be a viable function, there shall
6305 // exist for each argument an implicit conversion sequence
6306 // (13.3.3.1) that converts that argument to the corresponding
6307 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006308 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006309 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006310 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006311 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006312 /*InOverloadResolution=*/false,
6313 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006314 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006315 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006316 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006317 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006318 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006319 }
6320 } else {
6321 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6322 // argument for which there is no corresponding parameter is
6323 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006324 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006325 }
6326 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006327
6328 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6329 Candidate.Viable = false;
6330 Candidate.FailureKind = ovl_fail_enable_if;
6331 Candidate.DeductionFailure.Data = FailedAttr;
6332 return;
6333 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006334}
6335
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006336/// \brief Add overload candidates for overloaded operators that are
6337/// member functions.
6338///
6339/// Add the overloaded operator candidates that are member functions
6340/// for the operator Op that was used in an operator expression such
6341/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6342/// CandidateSet will store the added overload candidates. (C++
6343/// [over.match.oper]).
6344void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6345 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006346 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006347 OverloadCandidateSet& CandidateSet,
6348 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006349 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6350
6351 // C++ [over.match.oper]p3:
6352 // For a unary operator @ with an operand of a type whose
6353 // cv-unqualified version is T1, and for a binary operator @ with
6354 // a left operand of a type whose cv-unqualified version is T1 and
6355 // a right operand of a type whose cv-unqualified version is T2,
6356 // three sets of candidate functions, designated member
6357 // candidates, non-member candidates and built-in candidates, are
6358 // constructed as follows:
6359 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006360
Richard Smith0feaf0c2013-04-20 12:41:22 +00006361 // -- If T1 is a complete class type or a class currently being
6362 // defined, the set of member candidates is the result of the
6363 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6364 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006365 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006366 // Complete the type if it can be completed.
6367 RequireCompleteType(OpLoc, T1, 0);
6368 // If the type is neither complete nor being defined, bail out now.
6369 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006370 return;
Mike Stump11289f42009-09-09 15:08:12 +00006371
John McCall27b18f82009-11-17 02:14:36 +00006372 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6373 LookupQualifiedName(Operators, T1Rec->getDecl());
6374 Operators.suppressDiagnostics();
6375
Mike Stump11289f42009-09-09 15:08:12 +00006376 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006377 OperEnd = Operators.end();
6378 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006379 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006380 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006381 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006382 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006383 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006384 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006385 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006386}
6387
Douglas Gregora11693b2008-11-12 17:17:38 +00006388/// AddBuiltinCandidate - Add a candidate for a built-in
6389/// operator. ResultTy and ParamTys are the result and parameter types
6390/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006391/// arguments being passed to the candidate. IsAssignmentOperator
6392/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006393/// operator. NumContextualBoolArguments is the number of arguments
6394/// (at the beginning of the argument list) that will be contextually
6395/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006396void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006397 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006398 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006399 bool IsAssignmentOperator,
6400 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006401 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006402 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006403
Douglas Gregora11693b2008-11-12 17:17:38 +00006404 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006405 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00006406 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00006407 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006408 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006409 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006410 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006411 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006412 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6413
6414 // Determine the implicit conversion sequences for each of the
6415 // arguments.
6416 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006417 Candidate.ExplicitCallArguments = Args.size();
6418 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006419 // C++ [over.match.oper]p4:
6420 // For the built-in assignment operators, conversions of the
6421 // left operand are restricted as follows:
6422 // -- no temporaries are introduced to hold the left operand, and
6423 // -- no user-defined conversions are applied to the left
6424 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006425 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006426 //
6427 // We block these conversions by turning off user-defined
6428 // conversions, since that is the only way that initialization of
6429 // a reference to a non-class type can occur from something that
6430 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006431 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006432 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006433 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006434 Candidate.Conversions[ArgIdx]
6435 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006436 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006437 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006438 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006439 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006440 /*InOverloadResolution=*/false,
6441 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006442 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006443 }
John McCall0d1da222010-01-12 00:44:57 +00006444 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006445 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006446 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006447 break;
6448 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006449 }
6450}
6451
Craig Toppercd7b0332013-07-01 06:29:40 +00006452namespace {
6453
Douglas Gregora11693b2008-11-12 17:17:38 +00006454/// BuiltinCandidateTypeSet - A set of types that will be used for the
6455/// candidate operator functions for built-in operators (C++
6456/// [over.built]). The types are separated into pointer types and
6457/// enumeration types.
6458class BuiltinCandidateTypeSet {
6459 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006460 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006461
6462 /// PointerTypes - The set of pointer types that will be used in the
6463 /// built-in candidates.
6464 TypeSet PointerTypes;
6465
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006466 /// MemberPointerTypes - The set of member pointer types that will be
6467 /// used in the built-in candidates.
6468 TypeSet MemberPointerTypes;
6469
Douglas Gregora11693b2008-11-12 17:17:38 +00006470 /// EnumerationTypes - The set of enumeration types that will be
6471 /// used in the built-in candidates.
6472 TypeSet EnumerationTypes;
6473
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006474 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006475 /// candidates.
6476 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006477
6478 /// \brief A flag indicating non-record types are viable candidates
6479 bool HasNonRecordTypes;
6480
6481 /// \brief A flag indicating whether either arithmetic or enumeration types
6482 /// were present in the candidate set.
6483 bool HasArithmeticOrEnumeralTypes;
6484
Douglas Gregor80af3132011-05-21 23:15:46 +00006485 /// \brief A flag indicating whether the nullptr type was present in the
6486 /// candidate set.
6487 bool HasNullPtrType;
6488
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006489 /// Sema - The semantic analysis instance where we are building the
6490 /// candidate type set.
6491 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006492
Douglas Gregora11693b2008-11-12 17:17:38 +00006493 /// Context - The AST context in which we will build the type sets.
6494 ASTContext &Context;
6495
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006496 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6497 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006498 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006499
6500public:
6501 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006502 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006503
Mike Stump11289f42009-09-09 15:08:12 +00006504 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006505 : HasNonRecordTypes(false),
6506 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006507 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006508 SemaRef(SemaRef),
6509 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006510
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006511 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006512 SourceLocation Loc,
6513 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006514 bool AllowExplicitConversions,
6515 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006516
6517 /// pointer_begin - First pointer type found;
6518 iterator pointer_begin() { return PointerTypes.begin(); }
6519
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006520 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006521 iterator pointer_end() { return PointerTypes.end(); }
6522
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006523 /// member_pointer_begin - First member pointer type found;
6524 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6525
6526 /// member_pointer_end - Past the last member pointer type found;
6527 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6528
Douglas Gregora11693b2008-11-12 17:17:38 +00006529 /// enumeration_begin - First enumeration type found;
6530 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6531
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006532 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006533 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006534
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006535 iterator vector_begin() { return VectorTypes.begin(); }
6536 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006537
6538 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6539 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006540 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006541};
6542
Craig Toppercd7b0332013-07-01 06:29:40 +00006543} // end anonymous namespace
6544
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006545/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006546/// the set of pointer types along with any more-qualified variants of
6547/// that type. For example, if @p Ty is "int const *", this routine
6548/// will add "int const *", "int const volatile *", "int const
6549/// restrict *", and "int const volatile restrict *" to the set of
6550/// pointer types. Returns true if the add of @p Ty itself succeeded,
6551/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006552///
6553/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006554bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006555BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6556 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006557
Douglas Gregora11693b2008-11-12 17:17:38 +00006558 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006559 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006560 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006562 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006563 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006564 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006565 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006566 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6567 PointeeTy = PTy->getPointeeType();
6568 buildObjCPtr = true;
6569 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006570 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006571 }
6572
Sebastian Redl4990a632009-11-18 20:39:26 +00006573 // Don't add qualified variants of arrays. For one, they're not allowed
6574 // (the qualifier would sink to the element type), and for another, the
6575 // only overload situation where it matters is subscript or pointer +- int,
6576 // and those shouldn't have qualifier variants anyway.
6577 if (PointeeTy->isArrayType())
6578 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006579
John McCall8ccfcb52009-09-24 19:53:00 +00006580 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006581 bool hasVolatile = VisibleQuals.hasVolatile();
6582 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006583
John McCall8ccfcb52009-09-24 19:53:00 +00006584 // Iterate through all strict supersets of BaseCVR.
6585 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6586 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006587 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006588 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006589
6590 // Skip over restrict if no restrict found anywhere in the types, or if
6591 // the type cannot be restrict-qualified.
6592 if ((CVR & Qualifiers::Restrict) &&
6593 (!hasRestrict ||
6594 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6595 continue;
6596
6597 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006598 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006599
6600 // Build qualified pointer type.
6601 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006602 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006603 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006604 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006605 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6606
6607 // Insert qualified pointer type.
6608 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006609 }
6610
6611 return true;
6612}
6613
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006614/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6615/// to the set of pointer types along with any more-qualified variants of
6616/// that type. For example, if @p Ty is "int const *", this routine
6617/// will add "int const *", "int const volatile *", "int const
6618/// restrict *", and "int const volatile restrict *" to the set of
6619/// pointer types. Returns true if the add of @p Ty itself succeeded,
6620/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006621///
6622/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006623bool
6624BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6625 QualType Ty) {
6626 // Insert this type.
6627 if (!MemberPointerTypes.insert(Ty))
6628 return false;
6629
John McCall8ccfcb52009-09-24 19:53:00 +00006630 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6631 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006632
John McCall8ccfcb52009-09-24 19:53:00 +00006633 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006634 // Don't add qualified variants of arrays. For one, they're not allowed
6635 // (the qualifier would sink to the element type), and for another, the
6636 // only overload situation where it matters is subscript or pointer +- int,
6637 // and those shouldn't have qualifier variants anyway.
6638 if (PointeeTy->isArrayType())
6639 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006640 const Type *ClassTy = PointerTy->getClass();
6641
6642 // Iterate through all strict supersets of the pointee type's CVR
6643 // qualifiers.
6644 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6645 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6646 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006647
John McCall8ccfcb52009-09-24 19:53:00 +00006648 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006649 MemberPointerTypes.insert(
6650 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006651 }
6652
6653 return true;
6654}
6655
Douglas Gregora11693b2008-11-12 17:17:38 +00006656/// AddTypesConvertedFrom - Add each of the types to which the type @p
6657/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006658/// primarily interested in pointer types and enumeration types. We also
6659/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006660/// AllowUserConversions is true if we should look at the conversion
6661/// functions of a class type, and AllowExplicitConversions if we
6662/// should also include the explicit conversion functions of a class
6663/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006664void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006665BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006666 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006667 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006668 bool AllowExplicitConversions,
6669 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006670 // Only deal with canonical types.
6671 Ty = Context.getCanonicalType(Ty);
6672
6673 // Look through reference types; they aren't part of the type of an
6674 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006675 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006676 Ty = RefTy->getPointeeType();
6677
John McCall33ddac02011-01-19 10:06:00 +00006678 // If we're dealing with an array type, decay to the pointer.
6679 if (Ty->isArrayType())
6680 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6681
6682 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006683 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006684
Chandler Carruth00a38332010-12-13 01:44:01 +00006685 // Flag if we ever add a non-record type.
6686 const RecordType *TyRec = Ty->getAs<RecordType>();
6687 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6688
Chandler Carruth00a38332010-12-13 01:44:01 +00006689 // Flag if we encounter an arithmetic type.
6690 HasArithmeticOrEnumeralTypes =
6691 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6692
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006693 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6694 PointerTypes.insert(Ty);
6695 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006696 // Insert our type, and its more-qualified variants, into the set
6697 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006698 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006699 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006700 } else if (Ty->isMemberPointerType()) {
6701 // Member pointers are far easier, since the pointee can't be converted.
6702 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6703 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006704 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006705 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006706 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006707 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006708 // We treat vector types as arithmetic types in many contexts as an
6709 // extension.
6710 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006711 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006712 } else if (Ty->isNullPtrType()) {
6713 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006714 } else if (AllowUserConversions && TyRec) {
6715 // No conversion functions in incomplete types.
6716 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6717 return;
Mike Stump11289f42009-09-09 15:08:12 +00006718
Chandler Carruth00a38332010-12-13 01:44:01 +00006719 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006720 std::pair<CXXRecordDecl::conversion_iterator,
6721 CXXRecordDecl::conversion_iterator>
6722 Conversions = ClassDecl->getVisibleConversionFunctions();
6723 for (CXXRecordDecl::conversion_iterator
6724 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006725 NamedDecl *D = I.getDecl();
6726 if (isa<UsingShadowDecl>(D))
6727 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006728
Chandler Carruth00a38332010-12-13 01:44:01 +00006729 // Skip conversion function templates; they don't tell us anything
6730 // about which builtin types we can convert to.
6731 if (isa<FunctionTemplateDecl>(D))
6732 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006733
Chandler Carruth00a38332010-12-13 01:44:01 +00006734 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6735 if (AllowExplicitConversions || !Conv->isExplicit()) {
6736 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6737 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006738 }
6739 }
6740 }
6741}
6742
Douglas Gregor84605ae2009-08-24 13:43:27 +00006743/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6744/// the volatile- and non-volatile-qualified assignment operators for the
6745/// given type to the candidate set.
6746static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6747 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006748 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006749 OverloadCandidateSet &CandidateSet) {
6750 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006751
Douglas Gregor84605ae2009-08-24 13:43:27 +00006752 // T& operator=(T&, T)
6753 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6754 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006755 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006756 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006757
Douglas Gregor84605ae2009-08-24 13:43:27 +00006758 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6759 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006760 ParamTypes[0]
6761 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006762 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006764 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006765 }
6766}
Mike Stump11289f42009-09-09 15:08:12 +00006767
Sebastian Redl1054fae2009-10-25 17:03:50 +00006768/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6769/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006770static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6771 Qualifiers VRQuals;
6772 const RecordType *TyRec;
6773 if (const MemberPointerType *RHSMPType =
6774 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006775 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006776 else
6777 TyRec = ArgExpr->getType()->getAs<RecordType>();
6778 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006779 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006780 VRQuals.addVolatile();
6781 VRQuals.addRestrict();
6782 return VRQuals;
6783 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006784
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006785 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006786 if (!ClassDecl->hasDefinition())
6787 return VRQuals;
6788
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006789 std::pair<CXXRecordDecl::conversion_iterator,
6790 CXXRecordDecl::conversion_iterator>
6791 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006793 for (CXXRecordDecl::conversion_iterator
6794 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006795 NamedDecl *D = I.getDecl();
6796 if (isa<UsingShadowDecl>(D))
6797 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6798 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006799 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6800 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6801 CanTy = ResTypeRef->getPointeeType();
6802 // Need to go down the pointer/mempointer chain and add qualifiers
6803 // as see them.
6804 bool done = false;
6805 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006806 if (CanTy.isRestrictQualified())
6807 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006808 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6809 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006810 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006811 CanTy->getAs<MemberPointerType>())
6812 CanTy = ResTypeMPtr->getPointeeType();
6813 else
6814 done = true;
6815 if (CanTy.isVolatileQualified())
6816 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006817 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6818 return VRQuals;
6819 }
6820 }
6821 }
6822 return VRQuals;
6823}
John McCall52872982010-11-13 05:51:15 +00006824
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006825namespace {
John McCall52872982010-11-13 05:51:15 +00006826
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006827/// \brief Helper class to manage the addition of builtin operator overload
6828/// candidates. It provides shared state and utility methods used throughout
6829/// the process, as well as a helper method to add each group of builtin
6830/// operator overloads from the standard to a candidate set.
6831class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006832 // Common instance state available to all overload candidate addition methods.
6833 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006834 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006835 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006836 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006837 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006838 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006839
Chandler Carruthc6586e52010-12-12 10:35:00 +00006840 // Define some constants used to index and iterate over the arithemetic types
6841 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006842 // The "promoted arithmetic types" are the arithmetic
6843 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006844 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006845 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006846 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006847 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006848 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006849 LastPromotedArithmeticType = 11;
6850 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006851
Chandler Carruthc6586e52010-12-12 10:35:00 +00006852 /// \brief Get the canonical type for a given arithmetic type index.
6853 CanQualType getArithmeticType(unsigned index) {
6854 assert(index < NumArithmeticTypes);
6855 static CanQualType ASTContext::* const
6856 ArithmeticTypes[NumArithmeticTypes] = {
6857 // Start of promoted types.
6858 &ASTContext::FloatTy,
6859 &ASTContext::DoubleTy,
6860 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006861
Chandler Carruthc6586e52010-12-12 10:35:00 +00006862 // Start of integral types.
6863 &ASTContext::IntTy,
6864 &ASTContext::LongTy,
6865 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006866 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006867 &ASTContext::UnsignedIntTy,
6868 &ASTContext::UnsignedLongTy,
6869 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006870 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006871 // End of promoted types.
6872
6873 &ASTContext::BoolTy,
6874 &ASTContext::CharTy,
6875 &ASTContext::WCharTy,
6876 &ASTContext::Char16Ty,
6877 &ASTContext::Char32Ty,
6878 &ASTContext::SignedCharTy,
6879 &ASTContext::ShortTy,
6880 &ASTContext::UnsignedCharTy,
6881 &ASTContext::UnsignedShortTy,
6882 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006883 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006884 };
6885 return S.Context.*ArithmeticTypes[index];
6886 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006887
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006888 /// \brief Gets the canonical type resulting from the usual arithemetic
6889 /// converions for the given arithmetic types.
6890 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6891 // Accelerator table for performing the usual arithmetic conversions.
6892 // The rules are basically:
6893 // - if either is floating-point, use the wider floating-point
6894 // - if same signedness, use the higher rank
6895 // - if same size, use unsigned of the higher rank
6896 // - use the larger type
6897 // These rules, together with the axiom that higher ranks are
6898 // never smaller, are sufficient to precompute all of these results
6899 // *except* when dealing with signed types of higher rank.
6900 // (we could precompute SLL x UI for all known platforms, but it's
6901 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006902 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006903 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006904 Dep=-1,
6905 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006906 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006907 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006908 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006909/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6910/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6911/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6912/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6913/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6914/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6915/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6916/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6917/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6918/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6919/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006920 };
6921
6922 assert(L < LastPromotedArithmeticType);
6923 assert(R < LastPromotedArithmeticType);
6924 int Idx = ConversionsTable[L][R];
6925
6926 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006927 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006928
6929 // Slow path: we need to compare widths.
6930 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006931 CanQualType LT = getArithmeticType(L),
6932 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006933 unsigned LW = S.Context.getIntWidth(LT),
6934 RW = S.Context.getIntWidth(RT);
6935
6936 // If they're different widths, use the signed type.
6937 if (LW > RW) return LT;
6938 else if (LW < RW) return RT;
6939
6940 // Otherwise, use the unsigned type of the signed type's rank.
6941 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6942 assert(L == SLL || R == SLL);
6943 return S.Context.UnsignedLongLongTy;
6944 }
6945
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006946 /// \brief Helper method to factor out the common pattern of adding overloads
6947 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006948 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006949 bool HasVolatile,
6950 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006951 QualType ParamTypes[2] = {
6952 S.Context.getLValueReferenceType(CandidateTy),
6953 S.Context.IntTy
6954 };
6955
6956 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00006957 if (Args.size() == 1)
6958 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006959 else
Richard Smithe54c3072013-05-05 15:51:06 +00006960 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006961
6962 // Use a heuristic to reduce number of builtin candidates in the set:
6963 // add volatile version only if there are conversions to a volatile type.
6964 if (HasVolatile) {
6965 ParamTypes[0] =
6966 S.Context.getLValueReferenceType(
6967 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00006968 if (Args.size() == 1)
6969 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006970 else
Richard Smithe54c3072013-05-05 15:51:06 +00006971 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006972 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006973
6974 // Add restrict version only if there are conversions to a restrict type
6975 // and our candidate type is a non-restrict-qualified pointer.
6976 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6977 !CandidateTy.isRestrictQualified()) {
6978 ParamTypes[0]
6979 = S.Context.getLValueReferenceType(
6980 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00006981 if (Args.size() == 1)
6982 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006983 else
Richard Smithe54c3072013-05-05 15:51:06 +00006984 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006985
6986 if (HasVolatile) {
6987 ParamTypes[0]
6988 = S.Context.getLValueReferenceType(
6989 S.Context.getCVRQualifiedType(CandidateTy,
6990 (Qualifiers::Volatile |
6991 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00006992 if (Args.size() == 1)
6993 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006994 else
Richard Smithe54c3072013-05-05 15:51:06 +00006995 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006996 }
6997 }
6998
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006999 }
7000
7001public:
7002 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007003 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007004 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007005 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007006 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007007 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007008 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007009 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007010 HasArithmeticOrEnumeralCandidateType(
7011 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007012 CandidateTypes(CandidateTypes),
7013 CandidateSet(CandidateSet) {
7014 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007015 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007016 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007017 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007018 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007019 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007020 assert(getArithmeticType(FirstPromotedArithmeticType)
7021 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007022 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007023 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007024 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007025 "Invalid last promoted arithmetic type");
7026 }
7027
7028 // C++ [over.built]p3:
7029 //
7030 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7031 // is either volatile or empty, there exist candidate operator
7032 // functions of the form
7033 //
7034 // VQ T& operator++(VQ T&);
7035 // T operator++(VQ T&, int);
7036 //
7037 // C++ [over.built]p4:
7038 //
7039 // For every pair (T, VQ), where T is an arithmetic type other
7040 // than bool, and VQ is either volatile or empty, there exist
7041 // candidate operator functions of the form
7042 //
7043 // VQ T& operator--(VQ T&);
7044 // T operator--(VQ T&, int);
7045 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007046 if (!HasArithmeticOrEnumeralCandidateType)
7047 return;
7048
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007049 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7050 Arith < NumArithmeticTypes; ++Arith) {
7051 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007052 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007053 VisibleTypeConversionsQuals.hasVolatile(),
7054 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007055 }
7056 }
7057
7058 // C++ [over.built]p5:
7059 //
7060 // For every pair (T, VQ), where T is a cv-qualified or
7061 // cv-unqualified object type, and VQ is either volatile or
7062 // empty, there exist candidate operator functions of the form
7063 //
7064 // T*VQ& operator++(T*VQ&);
7065 // T*VQ& operator--(T*VQ&);
7066 // T* operator++(T*VQ&, int);
7067 // T* operator--(T*VQ&, int);
7068 void addPlusPlusMinusMinusPointerOverloads() {
7069 for (BuiltinCandidateTypeSet::iterator
7070 Ptr = CandidateTypes[0].pointer_begin(),
7071 PtrEnd = CandidateTypes[0].pointer_end();
7072 Ptr != PtrEnd; ++Ptr) {
7073 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007074 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007075 continue;
7076
7077 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007078 (!(*Ptr).isVolatileQualified() &&
7079 VisibleTypeConversionsQuals.hasVolatile()),
7080 (!(*Ptr).isRestrictQualified() &&
7081 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007082 }
7083 }
7084
7085 // C++ [over.built]p6:
7086 // For every cv-qualified or cv-unqualified object type T, there
7087 // exist candidate operator functions of the form
7088 //
7089 // T& operator*(T*);
7090 //
7091 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007092 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007093 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007094 // T& operator*(T*);
7095 void addUnaryStarPointerOverloads() {
7096 for (BuiltinCandidateTypeSet::iterator
7097 Ptr = CandidateTypes[0].pointer_begin(),
7098 PtrEnd = CandidateTypes[0].pointer_end();
7099 Ptr != PtrEnd; ++Ptr) {
7100 QualType ParamTy = *Ptr;
7101 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007102 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7103 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007104
Douglas Gregor02824322011-01-26 19:30:28 +00007105 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7106 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7107 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007108
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007109 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007110 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007111 }
7112 }
7113
7114 // C++ [over.built]p9:
7115 // For every promoted arithmetic type T, there exist candidate
7116 // operator functions of the form
7117 //
7118 // T operator+(T);
7119 // T operator-(T);
7120 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007121 if (!HasArithmeticOrEnumeralCandidateType)
7122 return;
7123
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007124 for (unsigned Arith = FirstPromotedArithmeticType;
7125 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007126 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007127 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007128 }
7129
7130 // Extension: We also add these operators for vector types.
7131 for (BuiltinCandidateTypeSet::iterator
7132 Vec = CandidateTypes[0].vector_begin(),
7133 VecEnd = CandidateTypes[0].vector_end();
7134 Vec != VecEnd; ++Vec) {
7135 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007136 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007137 }
7138 }
7139
7140 // C++ [over.built]p8:
7141 // For every type T, there exist candidate operator functions of
7142 // the form
7143 //
7144 // T* operator+(T*);
7145 void addUnaryPlusPointerOverloads() {
7146 for (BuiltinCandidateTypeSet::iterator
7147 Ptr = CandidateTypes[0].pointer_begin(),
7148 PtrEnd = CandidateTypes[0].pointer_end();
7149 Ptr != PtrEnd; ++Ptr) {
7150 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007151 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007152 }
7153 }
7154
7155 // C++ [over.built]p10:
7156 // For every promoted integral type T, there exist candidate
7157 // operator functions of the form
7158 //
7159 // T operator~(T);
7160 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007161 if (!HasArithmeticOrEnumeralCandidateType)
7162 return;
7163
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007164 for (unsigned Int = FirstPromotedIntegralType;
7165 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007166 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007167 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007168 }
7169
7170 // Extension: We also add this operator for vector types.
7171 for (BuiltinCandidateTypeSet::iterator
7172 Vec = CandidateTypes[0].vector_begin(),
7173 VecEnd = CandidateTypes[0].vector_end();
7174 Vec != VecEnd; ++Vec) {
7175 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007176 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007177 }
7178 }
7179
7180 // C++ [over.match.oper]p16:
7181 // For every pointer to member type T, there exist candidate operator
7182 // functions of the form
7183 //
7184 // bool operator==(T,T);
7185 // bool operator!=(T,T);
7186 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7187 /// Set of (canonical) types that we've already handled.
7188 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7189
Richard Smithe54c3072013-05-05 15:51:06 +00007190 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007191 for (BuiltinCandidateTypeSet::iterator
7192 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7193 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7194 MemPtr != MemPtrEnd;
7195 ++MemPtr) {
7196 // Don't add the same builtin candidate twice.
7197 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7198 continue;
7199
7200 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007201 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007202 }
7203 }
7204 }
7205
7206 // C++ [over.built]p15:
7207 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007208 // For every T, where T is an enumeration type, a pointer type, or
7209 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007210 //
7211 // bool operator<(T, T);
7212 // bool operator>(T, T);
7213 // bool operator<=(T, T);
7214 // bool operator>=(T, T);
7215 // bool operator==(T, T);
7216 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007217 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007218 // C++ [over.match.oper]p3:
7219 // [...]the built-in candidates include all of the candidate operator
7220 // functions defined in 13.6 that, compared to the given operator, [...]
7221 // do not have the same parameter-type-list as any non-template non-member
7222 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007223 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007224 // Note that in practice, this only affects enumeration types because there
7225 // aren't any built-in candidates of record type, and a user-defined operator
7226 // must have an operand of record or enumeration type. Also, the only other
7227 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007228 // cannot be overloaded for enumeration types, so this is the only place
7229 // where we must suppress candidates like this.
7230 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7231 UserDefinedBinaryOperators;
7232
Richard Smithe54c3072013-05-05 15:51:06 +00007233 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007234 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7235 CandidateTypes[ArgIdx].enumeration_end()) {
7236 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7237 CEnd = CandidateSet.end();
7238 C != CEnd; ++C) {
7239 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7240 continue;
7241
Eli Friedman14f082b2012-09-18 21:52:24 +00007242 if (C->Function->isFunctionTemplateSpecialization())
7243 continue;
7244
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007245 QualType FirstParamType =
7246 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7247 QualType SecondParamType =
7248 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7249
7250 // Skip if either parameter isn't of enumeral type.
7251 if (!FirstParamType->isEnumeralType() ||
7252 !SecondParamType->isEnumeralType())
7253 continue;
7254
7255 // Add this operator to the set of known user-defined operators.
7256 UserDefinedBinaryOperators.insert(
7257 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7258 S.Context.getCanonicalType(SecondParamType)));
7259 }
7260 }
7261 }
7262
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007263 /// Set of (canonical) types that we've already handled.
7264 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7265
Richard Smithe54c3072013-05-05 15:51:06 +00007266 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007267 for (BuiltinCandidateTypeSet::iterator
7268 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7269 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7270 Ptr != PtrEnd; ++Ptr) {
7271 // Don't add the same builtin candidate twice.
7272 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7273 continue;
7274
7275 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007276 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007277 }
7278 for (BuiltinCandidateTypeSet::iterator
7279 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7280 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7281 Enum != EnumEnd; ++Enum) {
7282 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7283
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007284 // Don't add the same builtin candidate twice, or if a user defined
7285 // candidate exists.
7286 if (!AddedTypes.insert(CanonType) ||
7287 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7288 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007289 continue;
7290
7291 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007292 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007293 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007294
7295 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7296 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7297 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007298 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007299 NullPtrTy))) {
7300 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007301 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007302 CandidateSet);
7303 }
7304 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007305 }
7306 }
7307
7308 // C++ [over.built]p13:
7309 //
7310 // For every cv-qualified or cv-unqualified object type T
7311 // there exist candidate operator functions of the form
7312 //
7313 // T* operator+(T*, ptrdiff_t);
7314 // T& operator[](T*, ptrdiff_t); [BELOW]
7315 // T* operator-(T*, ptrdiff_t);
7316 // T* operator+(ptrdiff_t, T*);
7317 // T& operator[](ptrdiff_t, T*); [BELOW]
7318 //
7319 // C++ [over.built]p14:
7320 //
7321 // For every T, where T is a pointer to object type, there
7322 // exist candidate operator functions of the form
7323 //
7324 // ptrdiff_t operator-(T, T);
7325 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7326 /// Set of (canonical) types that we've already handled.
7327 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7328
7329 for (int Arg = 0; Arg < 2; ++Arg) {
7330 QualType AsymetricParamTypes[2] = {
7331 S.Context.getPointerDiffType(),
7332 S.Context.getPointerDiffType(),
7333 };
7334 for (BuiltinCandidateTypeSet::iterator
7335 Ptr = CandidateTypes[Arg].pointer_begin(),
7336 PtrEnd = CandidateTypes[Arg].pointer_end();
7337 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007338 QualType PointeeTy = (*Ptr)->getPointeeType();
7339 if (!PointeeTy->isObjectType())
7340 continue;
7341
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007342 AsymetricParamTypes[Arg] = *Ptr;
7343 if (Arg == 0 || Op == OO_Plus) {
7344 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7345 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007346 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007347 }
7348 if (Op == OO_Minus) {
7349 // ptrdiff_t operator-(T, T);
7350 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7351 continue;
7352
7353 QualType ParamTypes[2] = { *Ptr, *Ptr };
7354 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007355 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007356 }
7357 }
7358 }
7359 }
7360
7361 // C++ [over.built]p12:
7362 //
7363 // For every pair of promoted arithmetic types L and R, there
7364 // exist candidate operator functions of the form
7365 //
7366 // LR operator*(L, R);
7367 // LR operator/(L, R);
7368 // LR operator+(L, R);
7369 // LR operator-(L, R);
7370 // bool operator<(L, R);
7371 // bool operator>(L, R);
7372 // bool operator<=(L, R);
7373 // bool operator>=(L, R);
7374 // bool operator==(L, R);
7375 // bool operator!=(L, R);
7376 //
7377 // where LR is the result of the usual arithmetic conversions
7378 // between types L and R.
7379 //
7380 // C++ [over.built]p24:
7381 //
7382 // For every pair of promoted arithmetic types L and R, there exist
7383 // candidate operator functions of the form
7384 //
7385 // LR operator?(bool, L, R);
7386 //
7387 // where LR is the result of the usual arithmetic conversions
7388 // between types L and R.
7389 // Our candidates ignore the first parameter.
7390 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007391 if (!HasArithmeticOrEnumeralCandidateType)
7392 return;
7393
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007394 for (unsigned Left = FirstPromotedArithmeticType;
7395 Left < LastPromotedArithmeticType; ++Left) {
7396 for (unsigned Right = FirstPromotedArithmeticType;
7397 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007398 QualType LandR[2] = { getArithmeticType(Left),
7399 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007400 QualType Result =
7401 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007402 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007403 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007404 }
7405 }
7406
7407 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7408 // conditional operator for vector types.
7409 for (BuiltinCandidateTypeSet::iterator
7410 Vec1 = CandidateTypes[0].vector_begin(),
7411 Vec1End = CandidateTypes[0].vector_end();
7412 Vec1 != Vec1End; ++Vec1) {
7413 for (BuiltinCandidateTypeSet::iterator
7414 Vec2 = CandidateTypes[1].vector_begin(),
7415 Vec2End = CandidateTypes[1].vector_end();
7416 Vec2 != Vec2End; ++Vec2) {
7417 QualType LandR[2] = { *Vec1, *Vec2 };
7418 QualType Result = S.Context.BoolTy;
7419 if (!isComparison) {
7420 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7421 Result = *Vec1;
7422 else
7423 Result = *Vec2;
7424 }
7425
Richard Smithe54c3072013-05-05 15:51:06 +00007426 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007427 }
7428 }
7429 }
7430
7431 // C++ [over.built]p17:
7432 //
7433 // For every pair of promoted integral types L and R, there
7434 // exist candidate operator functions of the form
7435 //
7436 // LR operator%(L, R);
7437 // LR operator&(L, R);
7438 // LR operator^(L, R);
7439 // LR operator|(L, R);
7440 // L operator<<(L, R);
7441 // L operator>>(L, R);
7442 //
7443 // where LR is the result of the usual arithmetic conversions
7444 // between types L and R.
7445 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007446 if (!HasArithmeticOrEnumeralCandidateType)
7447 return;
7448
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007449 for (unsigned Left = FirstPromotedIntegralType;
7450 Left < LastPromotedIntegralType; ++Left) {
7451 for (unsigned Right = FirstPromotedIntegralType;
7452 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007453 QualType LandR[2] = { getArithmeticType(Left),
7454 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007455 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7456 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007457 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007458 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007459 }
7460 }
7461 }
7462
7463 // C++ [over.built]p20:
7464 //
7465 // For every pair (T, VQ), where T is an enumeration or
7466 // pointer to member type and VQ is either volatile or
7467 // empty, there exist candidate operator functions of the form
7468 //
7469 // VQ T& operator=(VQ T&, T);
7470 void addAssignmentMemberPointerOrEnumeralOverloads() {
7471 /// Set of (canonical) types that we've already handled.
7472 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7473
7474 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7475 for (BuiltinCandidateTypeSet::iterator
7476 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7477 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7478 Enum != EnumEnd; ++Enum) {
7479 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7480 continue;
7481
Richard Smithe54c3072013-05-05 15:51:06 +00007482 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007483 }
7484
7485 for (BuiltinCandidateTypeSet::iterator
7486 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7487 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7488 MemPtr != MemPtrEnd; ++MemPtr) {
7489 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7490 continue;
7491
Richard Smithe54c3072013-05-05 15:51:06 +00007492 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007493 }
7494 }
7495 }
7496
7497 // C++ [over.built]p19:
7498 //
7499 // For every pair (T, VQ), where T is any type and VQ is either
7500 // volatile or empty, there exist candidate operator functions
7501 // of the form
7502 //
7503 // T*VQ& operator=(T*VQ&, T*);
7504 //
7505 // C++ [over.built]p21:
7506 //
7507 // For every pair (T, VQ), where T is a cv-qualified or
7508 // cv-unqualified object type and VQ is either volatile or
7509 // empty, there exist candidate operator functions of the form
7510 //
7511 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7512 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7513 void addAssignmentPointerOverloads(bool isEqualOp) {
7514 /// Set of (canonical) types that we've already handled.
7515 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7516
7517 for (BuiltinCandidateTypeSet::iterator
7518 Ptr = CandidateTypes[0].pointer_begin(),
7519 PtrEnd = CandidateTypes[0].pointer_end();
7520 Ptr != PtrEnd; ++Ptr) {
7521 // If this is operator=, keep track of the builtin candidates we added.
7522 if (isEqualOp)
7523 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007524 else if (!(*Ptr)->getPointeeType()->isObjectType())
7525 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007526
7527 // non-volatile version
7528 QualType ParamTypes[2] = {
7529 S.Context.getLValueReferenceType(*Ptr),
7530 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7531 };
Richard Smithe54c3072013-05-05 15:51:06 +00007532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007533 /*IsAssigmentOperator=*/ isEqualOp);
7534
Douglas Gregor5bee2582012-06-04 00:15:09 +00007535 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7536 VisibleTypeConversionsQuals.hasVolatile();
7537 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007538 // volatile version
7539 ParamTypes[0] =
7540 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007541 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007542 /*IsAssigmentOperator=*/isEqualOp);
7543 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007544
7545 if (!(*Ptr).isRestrictQualified() &&
7546 VisibleTypeConversionsQuals.hasRestrict()) {
7547 // restrict version
7548 ParamTypes[0]
7549 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007550 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007551 /*IsAssigmentOperator=*/isEqualOp);
7552
7553 if (NeedVolatile) {
7554 // volatile restrict version
7555 ParamTypes[0]
7556 = S.Context.getLValueReferenceType(
7557 S.Context.getCVRQualifiedType(*Ptr,
7558 (Qualifiers::Volatile |
7559 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007560 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007561 /*IsAssigmentOperator=*/isEqualOp);
7562 }
7563 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007564 }
7565
7566 if (isEqualOp) {
7567 for (BuiltinCandidateTypeSet::iterator
7568 Ptr = CandidateTypes[1].pointer_begin(),
7569 PtrEnd = CandidateTypes[1].pointer_end();
7570 Ptr != PtrEnd; ++Ptr) {
7571 // Make sure we don't add the same candidate twice.
7572 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7573 continue;
7574
Chandler Carruth8e543b32010-12-12 08:17:55 +00007575 QualType ParamTypes[2] = {
7576 S.Context.getLValueReferenceType(*Ptr),
7577 *Ptr,
7578 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007579
7580 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007581 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007582 /*IsAssigmentOperator=*/true);
7583
Douglas Gregor5bee2582012-06-04 00:15:09 +00007584 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7585 VisibleTypeConversionsQuals.hasVolatile();
7586 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007587 // volatile version
7588 ParamTypes[0] =
7589 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007590 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7591 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007593
7594 if (!(*Ptr).isRestrictQualified() &&
7595 VisibleTypeConversionsQuals.hasRestrict()) {
7596 // restrict version
7597 ParamTypes[0]
7598 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007599 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7600 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007601
7602 if (NeedVolatile) {
7603 // volatile restrict version
7604 ParamTypes[0]
7605 = S.Context.getLValueReferenceType(
7606 S.Context.getCVRQualifiedType(*Ptr,
7607 (Qualifiers::Volatile |
7608 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007609 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7610 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007611 }
7612 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007613 }
7614 }
7615 }
7616
7617 // C++ [over.built]p18:
7618 //
7619 // For every triple (L, VQ, R), where L is an arithmetic type,
7620 // VQ is either volatile or empty, and R is a promoted
7621 // arithmetic type, there exist candidate operator functions of
7622 // the form
7623 //
7624 // VQ L& operator=(VQ L&, R);
7625 // VQ L& operator*=(VQ L&, R);
7626 // VQ L& operator/=(VQ L&, R);
7627 // VQ L& operator+=(VQ L&, R);
7628 // VQ L& operator-=(VQ L&, R);
7629 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007630 if (!HasArithmeticOrEnumeralCandidateType)
7631 return;
7632
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007633 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7634 for (unsigned Right = FirstPromotedArithmeticType;
7635 Right < LastPromotedArithmeticType; ++Right) {
7636 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007637 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007638
7639 // Add this built-in operator as a candidate (VQ is empty).
7640 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007641 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007642 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007643 /*IsAssigmentOperator=*/isEqualOp);
7644
7645 // Add this built-in operator as a candidate (VQ is 'volatile').
7646 if (VisibleTypeConversionsQuals.hasVolatile()) {
7647 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007648 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007649 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007650 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 /*IsAssigmentOperator=*/isEqualOp);
7652 }
7653 }
7654 }
7655
7656 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7657 for (BuiltinCandidateTypeSet::iterator
7658 Vec1 = CandidateTypes[0].vector_begin(),
7659 Vec1End = CandidateTypes[0].vector_end();
7660 Vec1 != Vec1End; ++Vec1) {
7661 for (BuiltinCandidateTypeSet::iterator
7662 Vec2 = CandidateTypes[1].vector_begin(),
7663 Vec2End = CandidateTypes[1].vector_end();
7664 Vec2 != Vec2End; ++Vec2) {
7665 QualType ParamTypes[2];
7666 ParamTypes[1] = *Vec2;
7667 // Add this built-in operator as a candidate (VQ is empty).
7668 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007669 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007670 /*IsAssigmentOperator=*/isEqualOp);
7671
7672 // Add this built-in operator as a candidate (VQ is 'volatile').
7673 if (VisibleTypeConversionsQuals.hasVolatile()) {
7674 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7675 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007676 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007677 /*IsAssigmentOperator=*/isEqualOp);
7678 }
7679 }
7680 }
7681 }
7682
7683 // C++ [over.built]p22:
7684 //
7685 // For every triple (L, VQ, R), where L is an integral type, VQ
7686 // is either volatile or empty, and R is a promoted integral
7687 // type, there exist candidate operator functions of the form
7688 //
7689 // VQ L& operator%=(VQ L&, R);
7690 // VQ L& operator<<=(VQ L&, R);
7691 // VQ L& operator>>=(VQ L&, R);
7692 // VQ L& operator&=(VQ L&, R);
7693 // VQ L& operator^=(VQ L&, R);
7694 // VQ L& operator|=(VQ L&, R);
7695 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007696 if (!HasArithmeticOrEnumeralCandidateType)
7697 return;
7698
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007699 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7700 for (unsigned Right = FirstPromotedIntegralType;
7701 Right < LastPromotedIntegralType; ++Right) {
7702 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007703 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007704
7705 // Add this built-in operator as a candidate (VQ is empty).
7706 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007707 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007708 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007709 if (VisibleTypeConversionsQuals.hasVolatile()) {
7710 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007711 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007712 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7713 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007714 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007715 }
7716 }
7717 }
7718 }
7719
7720 // C++ [over.operator]p23:
7721 //
7722 // There also exist candidate operator functions of the form
7723 //
7724 // bool operator!(bool);
7725 // bool operator&&(bool, bool);
7726 // bool operator||(bool, bool);
7727 void addExclaimOverload() {
7728 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007729 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007730 /*IsAssignmentOperator=*/false,
7731 /*NumContextualBoolArguments=*/1);
7732 }
7733 void addAmpAmpOrPipePipeOverload() {
7734 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007735 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007736 /*IsAssignmentOperator=*/false,
7737 /*NumContextualBoolArguments=*/2);
7738 }
7739
7740 // C++ [over.built]p13:
7741 //
7742 // For every cv-qualified or cv-unqualified object type T there
7743 // exist candidate operator functions of the form
7744 //
7745 // T* operator+(T*, ptrdiff_t); [ABOVE]
7746 // T& operator[](T*, ptrdiff_t);
7747 // T* operator-(T*, ptrdiff_t); [ABOVE]
7748 // T* operator+(ptrdiff_t, T*); [ABOVE]
7749 // T& operator[](ptrdiff_t, T*);
7750 void addSubscriptOverloads() {
7751 for (BuiltinCandidateTypeSet::iterator
7752 Ptr = CandidateTypes[0].pointer_begin(),
7753 PtrEnd = CandidateTypes[0].pointer_end();
7754 Ptr != PtrEnd; ++Ptr) {
7755 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7756 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007757 if (!PointeeType->isObjectType())
7758 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007759
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007760 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7761
7762 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007763 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007764 }
7765
7766 for (BuiltinCandidateTypeSet::iterator
7767 Ptr = CandidateTypes[1].pointer_begin(),
7768 PtrEnd = CandidateTypes[1].pointer_end();
7769 Ptr != PtrEnd; ++Ptr) {
7770 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7771 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007772 if (!PointeeType->isObjectType())
7773 continue;
7774
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007775 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7776
7777 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007778 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007779 }
7780 }
7781
7782 // C++ [over.built]p11:
7783 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7784 // C1 is the same type as C2 or is a derived class of C2, T is an object
7785 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7786 // there exist candidate operator functions of the form
7787 //
7788 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7789 //
7790 // where CV12 is the union of CV1 and CV2.
7791 void addArrowStarOverloads() {
7792 for (BuiltinCandidateTypeSet::iterator
7793 Ptr = CandidateTypes[0].pointer_begin(),
7794 PtrEnd = CandidateTypes[0].pointer_end();
7795 Ptr != PtrEnd; ++Ptr) {
7796 QualType C1Ty = (*Ptr);
7797 QualType C1;
7798 QualifierCollector Q1;
7799 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7800 if (!isa<RecordType>(C1))
7801 continue;
7802 // heuristic to reduce number of builtin candidates in the set.
7803 // Add volatile/restrict version only if there are conversions to a
7804 // volatile/restrict type.
7805 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7806 continue;
7807 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7808 continue;
7809 for (BuiltinCandidateTypeSet::iterator
7810 MemPtr = CandidateTypes[1].member_pointer_begin(),
7811 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7812 MemPtr != MemPtrEnd; ++MemPtr) {
7813 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7814 QualType C2 = QualType(mptr->getClass(), 0);
7815 C2 = C2.getUnqualifiedType();
7816 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7817 break;
7818 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7819 // build CV12 T&
7820 QualType T = mptr->getPointeeType();
7821 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7822 T.isVolatileQualified())
7823 continue;
7824 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7825 T.isRestrictQualified())
7826 continue;
7827 T = Q1.apply(S.Context, T);
7828 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007829 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007830 }
7831 }
7832 }
7833
7834 // Note that we don't consider the first argument, since it has been
7835 // contextually converted to bool long ago. The candidates below are
7836 // therefore added as binary.
7837 //
7838 // C++ [over.built]p25:
7839 // For every type T, where T is a pointer, pointer-to-member, or scoped
7840 // enumeration type, there exist candidate operator functions of the form
7841 //
7842 // T operator?(bool, T, T);
7843 //
7844 void addConditionalOperatorOverloads() {
7845 /// Set of (canonical) types that we've already handled.
7846 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7847
7848 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7849 for (BuiltinCandidateTypeSet::iterator
7850 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7851 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7852 Ptr != PtrEnd; ++Ptr) {
7853 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7854 continue;
7855
7856 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007857 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007858 }
7859
7860 for (BuiltinCandidateTypeSet::iterator
7861 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7862 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7863 MemPtr != MemPtrEnd; ++MemPtr) {
7864 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7865 continue;
7866
7867 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007868 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007869 }
7870
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007871 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007872 for (BuiltinCandidateTypeSet::iterator
7873 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7874 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7875 Enum != EnumEnd; ++Enum) {
7876 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7877 continue;
7878
7879 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7880 continue;
7881
7882 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007883 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007884 }
7885 }
7886 }
7887 }
7888};
7889
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007890} // end anonymous namespace
7891
7892/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7893/// operator overloads to the candidate set (C++ [over.built]), based
7894/// on the operator @p Op and the arguments given. For example, if the
7895/// operator is a binary '+', this routine might add "int
7896/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00007897void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7898 SourceLocation OpLoc,
7899 ArrayRef<Expr *> Args,
7900 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007901 // Find all of the types that the arguments can convert to, but only
7902 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007903 // that make use of these types. Also record whether we encounter non-record
7904 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007905 Qualifiers VisibleTypeConversionsQuals;
7906 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00007907 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007908 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007909
7910 bool HasNonRecordCandidateType = false;
7911 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007912 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00007913 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007914 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7915 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7916 OpLoc,
7917 true,
7918 (Op == OO_Exclaim ||
7919 Op == OO_AmpAmp ||
7920 Op == OO_PipePipe),
7921 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007922 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7923 CandidateTypes[ArgIdx].hasNonRecordTypes();
7924 HasArithmeticOrEnumeralCandidateType =
7925 HasArithmeticOrEnumeralCandidateType ||
7926 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007927 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007928
Chandler Carruth00a38332010-12-13 01:44:01 +00007929 // Exit early when no non-record types have been added to the candidate set
7930 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007931 //
7932 // We can't exit early for !, ||, or &&, since there we have always have
7933 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007934 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007935 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007936 return;
7937
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007938 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007939 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007940 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007941 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007942 CandidateTypes, CandidateSet);
7943
7944 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007945 switch (Op) {
7946 case OO_None:
7947 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007948 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007949
Chandler Carruth5184de02010-12-12 08:51:33 +00007950 case OO_New:
7951 case OO_Delete:
7952 case OO_Array_New:
7953 case OO_Array_Delete:
7954 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007955 llvm_unreachable(
7956 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007957
7958 case OO_Comma:
7959 case OO_Arrow:
7960 // C++ [over.match.oper]p3:
7961 // -- For the operator ',', the unary operator '&', or the
7962 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007963 break;
7964
7965 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007966 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007967 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007968 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007969
7970 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007971 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007972 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007973 } else {
7974 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7975 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7976 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007977 break;
7978
Chandler Carruth5184de02010-12-12 08:51:33 +00007979 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007980 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007981 OpBuilder.addUnaryStarPointerOverloads();
7982 else
7983 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7984 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007985
Chandler Carruth5184de02010-12-12 08:51:33 +00007986 case OO_Slash:
7987 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007988 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007989
7990 case OO_PlusPlus:
7991 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007992 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7993 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007994 break;
7995
Douglas Gregor84605ae2009-08-24 13:43:27 +00007996 case OO_EqualEqual:
7997 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007998 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007999 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008000
Douglas Gregora11693b2008-11-12 17:17:38 +00008001 case OO_Less:
8002 case OO_Greater:
8003 case OO_LessEqual:
8004 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008005 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008006 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8007 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008008
Douglas Gregora11693b2008-11-12 17:17:38 +00008009 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008010 case OO_Caret:
8011 case OO_Pipe:
8012 case OO_LessLess:
8013 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008014 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008015 break;
8016
Chandler Carruth5184de02010-12-12 08:51:33 +00008017 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008018 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008019 // C++ [over.match.oper]p3:
8020 // -- For the operator ',', the unary operator '&', or the
8021 // operator '->', the built-in candidates set is empty.
8022 break;
8023
8024 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8025 break;
8026
8027 case OO_Tilde:
8028 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8029 break;
8030
Douglas Gregora11693b2008-11-12 17:17:38 +00008031 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008032 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008033 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008034
8035 case OO_PlusEqual:
8036 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008037 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008038 // Fall through.
8039
8040 case OO_StarEqual:
8041 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008042 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008043 break;
8044
8045 case OO_PercentEqual:
8046 case OO_LessLessEqual:
8047 case OO_GreaterGreaterEqual:
8048 case OO_AmpEqual:
8049 case OO_CaretEqual:
8050 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008051 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008052 break;
8053
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008054 case OO_Exclaim:
8055 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008056 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008057
Douglas Gregora11693b2008-11-12 17:17:38 +00008058 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008059 case OO_PipePipe:
8060 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008061 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008062
8063 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008064 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008065 break;
8066
8067 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008068 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008069 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008070
8071 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008073 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8074 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008075 }
8076}
8077
Douglas Gregore254f902009-02-04 00:32:51 +00008078/// \brief Add function candidates found via argument-dependent lookup
8079/// to the set of overloading candidates.
8080///
8081/// This routine performs argument-dependent name lookup based on the
8082/// given function name (which may also be an operator name) and adds
8083/// all of the overload candidates found by ADL to the overload
8084/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008085void
Douglas Gregore254f902009-02-04 00:32:51 +00008086Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00008087 bool Operator, SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008088 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008089 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008090 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008091 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008092 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008093
John McCall91f61fc2010-01-26 06:04:06 +00008094 // FIXME: This approach for uniquing ADL results (and removing
8095 // redundant candidates from the set) relies on pointer-equality,
8096 // which means we need to key off the canonical decl. However,
8097 // always going back to the canonical decl might not get us the
8098 // right set of default arguments. What default arguments are
8099 // we supposed to consider on ADL candidates, anyway?
8100
Douglas Gregorcabea402009-09-22 15:41:20 +00008101 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00008102 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008103
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008104 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008105 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8106 CandEnd = CandidateSet.end();
8107 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008108 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008109 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008110 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008111 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008112 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008113
8114 // For each of the ADL candidates we found, add it to the overload
8115 // set.
John McCall8fe68082010-01-26 07:16:45 +00008116 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008117 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008118 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008119 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008120 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008121
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008122 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8123 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008124 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008125 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008126 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008127 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008128 }
Douglas Gregore254f902009-02-04 00:32:51 +00008129}
8130
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008131/// isBetterOverloadCandidate - Determines whether the first overload
8132/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008133bool
John McCall5c32be02010-08-24 20:38:10 +00008134isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008135 const OverloadCandidate &Cand1,
8136 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008137 SourceLocation Loc,
8138 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008139 // Define viable functions to be better candidates than non-viable
8140 // functions.
8141 if (!Cand2.Viable)
8142 return Cand1.Viable;
8143 else if (!Cand1.Viable)
8144 return false;
8145
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008146 // C++ [over.match.best]p1:
8147 //
8148 // -- if F is a static member function, ICS1(F) is defined such
8149 // that ICS1(F) is neither better nor worse than ICS1(G) for
8150 // any function G, and, symmetrically, ICS1(G) is neither
8151 // better nor worse than ICS1(F).
8152 unsigned StartArg = 0;
8153 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8154 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008155
Douglas Gregord3cb3562009-07-07 23:38:56 +00008156 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008157 // A viable function F1 is defined to be a better function than another
8158 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008159 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008160 unsigned NumArgs = Cand1.NumConversions;
8161 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008162 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008163 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008164 switch (CompareImplicitConversionSequences(S,
8165 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008166 Cand2.Conversions[ArgIdx])) {
8167 case ImplicitConversionSequence::Better:
8168 // Cand1 has a better conversion sequence.
8169 HasBetterConversion = true;
8170 break;
8171
8172 case ImplicitConversionSequence::Worse:
8173 // Cand1 can't be better than Cand2.
8174 return false;
8175
8176 case ImplicitConversionSequence::Indistinguishable:
8177 // Do nothing.
8178 break;
8179 }
8180 }
8181
Mike Stump11289f42009-09-09 15:08:12 +00008182 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008183 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008184 if (HasBetterConversion)
8185 return true;
8186
Mike Stump11289f42009-09-09 15:08:12 +00008187 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00008188 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00008189 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00008190 Cand2.Function && Cand2.Function->getPrimaryTemplate())
8191 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008192
8193 // -- F1 and F2 are function template specializations, and the function
8194 // template for F1 is more specialized than the template for F2
8195 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00008196 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00008197 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00008198 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00008199 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00008200 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8201 Cand2.Function->getPrimaryTemplate(),
8202 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008203 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00008204 : TPOC_Call,
Richard Smithe5b52202013-09-11 00:52:39 +00008205 Cand1.ExplicitCallArguments,
8206 Cand2.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00008207 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00008208 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008209
Douglas Gregora1f013e2008-11-07 22:36:19 +00008210 // -- the context is an initialization by user-defined conversion
8211 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8212 // from the return type of F1 to the destination type (i.e.,
8213 // the type of the entity being initialized) is a better
8214 // conversion sequence than the standard conversion sequence
8215 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008216 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008217 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008218 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008219 // First check whether we prefer one of the conversion functions over the
8220 // other. This only distinguishes the results in non-standard, extension
8221 // cases such as the conversion from a lambda closure type to a function
8222 // pointer or block.
8223 ImplicitConversionSequence::CompareKind FuncResult
8224 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8225 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8226 return FuncResult;
8227
John McCall5c32be02010-08-24 20:38:10 +00008228 switch (CompareStandardConversionSequences(S,
8229 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00008230 Cand2.FinalConversion)) {
8231 case ImplicitConversionSequence::Better:
8232 // Cand1 has a better conversion sequence.
8233 return true;
8234
8235 case ImplicitConversionSequence::Worse:
8236 // Cand1 can't be better than Cand2.
8237 return false;
8238
8239 case ImplicitConversionSequence::Indistinguishable:
8240 // Do nothing
8241 break;
8242 }
8243 }
8244
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008245 // Check for enable_if value-based overload resolution.
8246 if (Cand1.Function && Cand2.Function &&
8247 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8248 Cand2.Function->hasAttr<EnableIfAttr>())) {
8249 // FIXME: The next several lines are just
8250 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8251 // instead of reverse order which is how they're stored in the AST.
8252 AttrVec Cand1Attrs;
8253 AttrVec::iterator Cand1E = Cand1Attrs.end();
8254 if (Cand1.Function->hasAttrs()) {
8255 Cand1Attrs = Cand1.Function->getAttrs();
8256 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8257 IsNotEnableIfAttr);
8258 std::reverse(Cand1Attrs.begin(), Cand1E);
8259 }
8260
8261 AttrVec Cand2Attrs;
8262 AttrVec::iterator Cand2E = Cand2Attrs.end();
8263 if (Cand2.Function->hasAttrs()) {
8264 Cand2Attrs = Cand2.Function->getAttrs();
8265 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8266 IsNotEnableIfAttr);
8267 std::reverse(Cand2Attrs.begin(), Cand2E);
8268 }
8269 for (AttrVec::iterator
8270 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin();
8271 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) {
8272 if (Cand1I == Cand1E)
8273 return false;
8274 if (Cand2I == Cand2E)
8275 return true;
8276 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8277 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID,
8278 S.getASTContext(), true);
8279 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID,
8280 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008281 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008282 return false;
8283 }
8284 }
8285
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008286 return false;
8287}
8288
Mike Stump11289f42009-09-09 15:08:12 +00008289/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008290/// within an overload candidate set.
8291///
James Dennettffad8b72012-06-22 08:10:18 +00008292/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008293/// which overload resolution occurs.
8294///
James Dennettffad8b72012-06-22 08:10:18 +00008295/// \param Best If overload resolution was successful or found a deleted
8296/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008297///
8298/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008299OverloadingResult
8300OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008301 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008302 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008303 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008304 Best = end();
8305 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8306 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008307 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008308 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008309 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008310 }
8311
8312 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008313 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008314 return OR_No_Viable_Function;
8315
8316 // Make sure that this function is better than every other viable
8317 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008318 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008319 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008320 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008321 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008322 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008323 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008324 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008325 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008326 }
Mike Stump11289f42009-09-09 15:08:12 +00008327
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008328 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008329 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008330 (Best->Function->isDeleted() ||
8331 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008332 return OR_Deleted;
8333
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008334 return OR_Success;
8335}
8336
John McCall53262c92010-01-12 02:15:36 +00008337namespace {
8338
8339enum OverloadCandidateKind {
8340 oc_function,
8341 oc_method,
8342 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008343 oc_function_template,
8344 oc_method_template,
8345 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008346 oc_implicit_default_constructor,
8347 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008348 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008349 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008350 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008351 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008352};
8353
John McCalle1ac8d12010-01-13 00:25:19 +00008354OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8355 FunctionDecl *Fn,
8356 std::string &Description) {
8357 bool isTemplate = false;
8358
8359 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8360 isTemplate = true;
8361 Description = S.getTemplateArgumentBindingsText(
8362 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8363 }
John McCallfd0b2f82010-01-06 09:43:14 +00008364
8365 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008366 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008367 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008368
Sebastian Redl08905022011-02-05 19:23:19 +00008369 if (Ctor->getInheritedConstructor())
8370 return oc_implicit_inherited_constructor;
8371
Alexis Hunt119c10e2011-05-25 23:16:36 +00008372 if (Ctor->isDefaultConstructor())
8373 return oc_implicit_default_constructor;
8374
8375 if (Ctor->isMoveConstructor())
8376 return oc_implicit_move_constructor;
8377
8378 assert(Ctor->isCopyConstructor() &&
8379 "unexpected sort of implicit constructor");
8380 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008381 }
8382
8383 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8384 // This actually gets spelled 'candidate function' for now, but
8385 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008386 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008387 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008388
Alexis Hunt119c10e2011-05-25 23:16:36 +00008389 if (Meth->isMoveAssignmentOperator())
8390 return oc_implicit_move_assignment;
8391
Douglas Gregor12695102012-02-10 08:36:38 +00008392 if (Meth->isCopyAssignmentOperator())
8393 return oc_implicit_copy_assignment;
8394
8395 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8396 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008397 }
8398
John McCalle1ac8d12010-01-13 00:25:19 +00008399 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008400}
8401
Larisse Voufo98b20f12013-07-19 23:00:19 +00008402void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008403 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8404 if (!Ctor) return;
8405
8406 Ctor = Ctor->getInheritedConstructor();
8407 if (!Ctor) return;
8408
8409 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8410}
8411
John McCall53262c92010-01-12 02:15:36 +00008412} // end anonymous namespace
8413
8414// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008415void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008416 std::string FnDesc;
8417 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008418 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8419 << (unsigned) K << FnDesc;
8420 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8421 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008422 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008423}
8424
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008425// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008426// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008427void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008428 assert(OverloadedExpr->getType() == Context.OverloadTy);
8429
8430 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8431 OverloadExpr *OvlExpr = Ovl.Expression;
8432
8433 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8434 IEnd = OvlExpr->decls_end();
8435 I != IEnd; ++I) {
8436 if (FunctionTemplateDecl *FunTmpl =
8437 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008438 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008439 } else if (FunctionDecl *Fun
8440 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008441 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008442 }
8443 }
8444}
8445
John McCall0d1da222010-01-12 00:44:57 +00008446/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8447/// "lead" diagnostic; it will be given two arguments, the source and
8448/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008449void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8450 Sema &S,
8451 SourceLocation CaretLoc,
8452 const PartialDiagnostic &PDiag) const {
8453 S.Diag(CaretLoc, PDiag)
8454 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008455 // FIXME: The note limiting machinery is borrowed from
8456 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8457 // refactoring here.
8458 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8459 unsigned CandsShown = 0;
8460 AmbiguousConversionSequence::const_iterator I, E;
8461 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8462 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8463 break;
8464 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008465 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008466 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008467 if (I != E)
8468 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008469}
8470
John McCall0d1da222010-01-12 00:44:57 +00008471namespace {
8472
John McCall6a61b522010-01-13 09:16:55 +00008473void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8474 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8475 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008476 assert(Cand->Function && "for now, candidate must be a function");
8477 FunctionDecl *Fn = Cand->Function;
8478
8479 // There's a conversion slot for the object argument if this is a
8480 // non-constructor method. Note that 'I' corresponds the
8481 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008482 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008483 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008484 if (I == 0)
8485 isObjectArgument = true;
8486 else
8487 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008488 }
8489
John McCalle1ac8d12010-01-13 00:25:19 +00008490 std::string FnDesc;
8491 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8492
John McCall6a61b522010-01-13 09:16:55 +00008493 Expr *FromExpr = Conv.Bad.FromExpr;
8494 QualType FromTy = Conv.Bad.getFromType();
8495 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008496
John McCallfb7ad0f2010-02-02 02:42:52 +00008497 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008498 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008499 Expr *E = FromExpr->IgnoreParens();
8500 if (isa<UnaryOperator>(E))
8501 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008502 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008503
8504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8505 << (unsigned) FnKind << FnDesc
8506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8507 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008508 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008509 return;
8510 }
8511
John McCall6d174642010-01-23 08:10:49 +00008512 // Do some hand-waving analysis to see if the non-viability is due
8513 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008514 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8515 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8516 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8517 CToTy = RT->getPointeeType();
8518 else {
8519 // TODO: detect and diagnose the full richness of const mismatches.
8520 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8521 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8522 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8523 }
8524
8525 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8526 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008527 Qualifiers FromQs = CFromTy.getQualifiers();
8528 Qualifiers ToQs = CToTy.getQualifiers();
8529
8530 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8532 << (unsigned) FnKind << FnDesc
8533 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8534 << FromTy
8535 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8536 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008537 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008538 return;
8539 }
8540
John McCall31168b02011-06-15 23:02:42 +00008541 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008542 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008543 << (unsigned) FnKind << FnDesc
8544 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8545 << FromTy
8546 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8547 << (unsigned) isObjectArgument << I+1;
8548 MaybeEmitInheritedConstructorNote(S, Fn);
8549 return;
8550 }
8551
Douglas Gregoraec25842011-04-26 23:16:46 +00008552 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8553 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8554 << (unsigned) FnKind << FnDesc
8555 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8556 << FromTy
8557 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8558 << (unsigned) isObjectArgument << I+1;
8559 MaybeEmitInheritedConstructorNote(S, Fn);
8560 return;
8561 }
8562
John McCall47000992010-01-14 03:28:57 +00008563 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8564 assert(CVR && "unexpected qualifiers mismatch");
8565
8566 if (isObjectArgument) {
8567 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8568 << (unsigned) FnKind << FnDesc
8569 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8570 << FromTy << (CVR - 1);
8571 } else {
8572 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8573 << (unsigned) FnKind << FnDesc
8574 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8575 << FromTy << (CVR - 1) << I+1;
8576 }
Sebastian Redl08905022011-02-05 19:23:19 +00008577 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008578 return;
8579 }
8580
Sebastian Redla72462c2011-09-24 17:48:32 +00008581 // Special diagnostic for failure to convert an initializer list, since
8582 // telling the user that it has type void is not useful.
8583 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8585 << (unsigned) FnKind << FnDesc
8586 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8587 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8588 MaybeEmitInheritedConstructorNote(S, Fn);
8589 return;
8590 }
8591
John McCall6d174642010-01-23 08:10:49 +00008592 // Diagnose references or pointers to incomplete types differently,
8593 // since it's far from impossible that the incompleteness triggered
8594 // the failure.
8595 QualType TempFromTy = FromTy.getNonReferenceType();
8596 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8597 TempFromTy = PTy->getPointeeType();
8598 if (TempFromTy->isIncompleteType()) {
8599 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8600 << (unsigned) FnKind << FnDesc
8601 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8602 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008603 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008604 return;
8605 }
8606
Douglas Gregor56f2e342010-06-30 23:01:39 +00008607 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008608 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008609 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8610 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8611 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8612 FromPtrTy->getPointeeType()) &&
8613 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8614 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008615 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008616 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008617 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008618 }
8619 } else if (const ObjCObjectPointerType *FromPtrTy
8620 = FromTy->getAs<ObjCObjectPointerType>()) {
8621 if (const ObjCObjectPointerType *ToPtrTy
8622 = ToTy->getAs<ObjCObjectPointerType>())
8623 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8624 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8625 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8626 FromPtrTy->getPointeeType()) &&
8627 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008628 BaseToDerivedConversion = 2;
8629 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008630 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8631 !FromTy->isIncompleteType() &&
8632 !ToRefTy->getPointeeType()->isIncompleteType() &&
8633 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8634 BaseToDerivedConversion = 3;
8635 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8636 ToTy.getNonReferenceType().getCanonicalType() ==
8637 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008638 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8639 << (unsigned) FnKind << FnDesc
8640 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8641 << (unsigned) isObjectArgument << I + 1;
8642 MaybeEmitInheritedConstructorNote(S, Fn);
8643 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008644 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008646
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008647 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008648 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008649 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008650 << (unsigned) FnKind << FnDesc
8651 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008652 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008653 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008654 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008655 return;
8656 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008657
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008658 if (isa<ObjCObjectPointerType>(CFromTy) &&
8659 isa<PointerType>(CToTy)) {
8660 Qualifiers FromQs = CFromTy.getQualifiers();
8661 Qualifiers ToQs = CToTy.getQualifiers();
8662 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8664 << (unsigned) FnKind << FnDesc
8665 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8666 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8667 MaybeEmitInheritedConstructorNote(S, Fn);
8668 return;
8669 }
8670 }
8671
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008672 // Emit the generic diagnostic and, optionally, add the hints to it.
8673 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8674 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008675 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008676 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8677 << (unsigned) (Cand->Fix.Kind);
8678
8679 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008680 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8681 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008682 FDiag << *HI;
8683 S.Diag(Fn->getLocation(), FDiag);
8684
Sebastian Redl08905022011-02-05 19:23:19 +00008685 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008686}
8687
Larisse Voufo98b20f12013-07-19 23:00:19 +00008688/// Additional arity mismatch diagnosis specific to a function overload
8689/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8690/// over a candidate in any candidate set.
8691bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8692 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008693 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008694 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008695
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008696 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008697 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008698 // right number of arguments, because only overloaded operators have
8699 // the weird behavior of overloading member and non-member functions.
8700 // Just don't report anything.
8701 if (Fn->isInvalidDecl() &&
8702 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008703 return true;
8704
8705 if (NumArgs < MinParams) {
8706 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8707 (Cand->FailureKind == ovl_fail_bad_deduction &&
8708 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8709 } else {
8710 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8711 (Cand->FailureKind == ovl_fail_bad_deduction &&
8712 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8713 }
8714
8715 return false;
8716}
8717
8718/// General arity mismatch diagnosis over a candidate in a candidate set.
8719void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8720 assert(isa<FunctionDecl>(D) &&
8721 "The templated declaration should at least be a function"
8722 " when diagnosing bad template argument deduction due to too many"
8723 " or too few arguments");
8724
8725 FunctionDecl *Fn = cast<FunctionDecl>(D);
8726
8727 // TODO: treat calls to a missing default constructor as a special case
8728 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8729 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008730
John McCall6a61b522010-01-13 09:16:55 +00008731 // at least / at most / exactly
8732 unsigned mode, modeCount;
8733 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008734 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8735 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008736 mode = 0; // "at least"
8737 else
8738 mode = 2; // "exactly"
8739 modeCount = MinParams;
8740 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008741 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008742 mode = 1; // "at most"
8743 else
8744 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008745 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008746 }
8747
8748 std::string Description;
8749 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8750
Richard Smith10ff50d2012-05-11 05:16:41 +00008751 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8752 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8753 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8754 << Fn->getParamDecl(0) << NumFormalArgs;
8755 else
8756 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8757 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8758 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008759 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008760}
8761
Larisse Voufo98b20f12013-07-19 23:00:19 +00008762/// Arity mismatch diagnosis specific to a function overload candidate.
8763void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8764 unsigned NumFormalArgs) {
8765 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8766 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8767}
Larisse Voufo47c08452013-07-19 22:53:23 +00008768
Larisse Voufo98b20f12013-07-19 23:00:19 +00008769TemplateDecl *getDescribedTemplate(Decl *Templated) {
8770 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8771 return FD->getDescribedFunctionTemplate();
8772 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8773 return RD->getDescribedClassTemplate();
8774
8775 llvm_unreachable("Unsupported: Getting the described template declaration"
8776 " for bad deduction diagnosis");
8777}
8778
8779/// Diagnose a failed template-argument deduction.
8780void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8781 DeductionFailureInfo &DeductionFailure,
8782 unsigned NumArgs) {
8783 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008784 NamedDecl *ParamD;
8785 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8786 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8787 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008788 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008789 case Sema::TDK_Success:
8790 llvm_unreachable("TDK_success while diagnosing bad deduction");
8791
8792 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008793 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008794 S.Diag(Templated->getLocation(),
8795 diag::note_ovl_candidate_incomplete_deduction)
8796 << ParamD->getDeclName();
8797 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008798 return;
8799 }
8800
John McCall42d7d192010-08-05 09:05:08 +00008801 case Sema::TDK_Underqualified: {
8802 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8803 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8804
Larisse Voufo98b20f12013-07-19 23:00:19 +00008805 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008806
8807 // Param will have been canonicalized, but it should just be a
8808 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008809 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008810 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008811 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008812 assert(S.Context.hasSameType(Param, NonCanonParam));
8813
8814 // Arg has also been canonicalized, but there's nothing we can do
8815 // about that. It also doesn't matter as much, because it won't
8816 // have any template parameters in it (because deduction isn't
8817 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008818 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008819
Larisse Voufo98b20f12013-07-19 23:00:19 +00008820 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8821 << ParamD->getDeclName() << Arg << NonCanonParam;
8822 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008823 return;
8824 }
8825
8826 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008827 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008828 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008829 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008830 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008831 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008832 which = 1;
8833 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008834 which = 2;
8835 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008836
Larisse Voufo98b20f12013-07-19 23:00:19 +00008837 S.Diag(Templated->getLocation(),
8838 diag::note_ovl_candidate_inconsistent_deduction)
8839 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8840 << *DeductionFailure.getSecondArg();
8841 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008842 return;
8843 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008844
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008845 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008846 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008847 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008848 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008849 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008850 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008851 else {
8852 int index = 0;
8853 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8854 index = TTP->getIndex();
8855 else if (NonTypeTemplateParmDecl *NTTP
8856 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8857 index = NTTP->getIndex();
8858 else
8859 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008860 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008861 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008862 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008863 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008864 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008865 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008866
Douglas Gregor02eb4832010-05-08 18:13:28 +00008867 case Sema::TDK_TooManyArguments:
8868 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008869 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008870 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008871
8872 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008873 S.Diag(Templated->getLocation(),
8874 diag::note_ovl_candidate_instantiation_depth);
8875 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008876 return;
8877
8878 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008879 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008880 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008881 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008882 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008883 TemplateArgString = " ";
8884 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00008885 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00008886 }
8887
Richard Smith6f8d2c62012-05-09 05:17:00 +00008888 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008889 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008890 if (PDiag && PDiag->second.getDiagID() ==
8891 diag::err_typename_nested_not_found_enable_if) {
8892 // FIXME: Use the source range of the condition, and the fully-qualified
8893 // name of the enable_if template. These are both present in PDiag.
8894 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8895 << "'enable_if'" << TemplateArgString;
8896 return;
8897 }
8898
Richard Smith9ca64612012-05-07 09:03:25 +00008899 // Format the SFINAE diagnostic into the argument string.
8900 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8901 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008902 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008903 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008904 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008905 SFINAEArgString = ": ";
8906 R = SourceRange(PDiag->first, PDiag->first);
8907 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8908 }
8909
Larisse Voufo98b20f12013-07-19 23:00:19 +00008910 S.Diag(Templated->getLocation(),
8911 diag::note_ovl_candidate_substitution_failure)
8912 << TemplateArgString << SFINAEArgString << R;
8913 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008914 return;
8915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008916
Richard Smith8c6eeb92013-01-31 04:03:12 +00008917 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008918 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8919 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00008920 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008921 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00008922 return;
8923 }
8924
Richard Trieue3732352013-04-08 21:11:40 +00008925 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00008926 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008927 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8928 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00008929 if (FirstTA.getKind() == TemplateArgument::Template &&
8930 SecondTA.getKind() == TemplateArgument::Template) {
8931 TemplateName FirstTN = FirstTA.getAsTemplate();
8932 TemplateName SecondTN = SecondTA.getAsTemplate();
8933 if (FirstTN.getKind() == TemplateName::Template &&
8934 SecondTN.getKind() == TemplateName::Template) {
8935 if (FirstTN.getAsTemplateDecl()->getName() ==
8936 SecondTN.getAsTemplateDecl()->getName()) {
8937 // FIXME: This fixes a bad diagnostic where both templates are named
8938 // the same. This particular case is a bit difficult since:
8939 // 1) It is passed as a string to the diagnostic printer.
8940 // 2) The diagnostic printer only attempts to find a better
8941 // name for types, not decls.
8942 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008943 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00008944 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8945 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8946 return;
8947 }
8948 }
8949 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00008950 // FIXME: For generic lambda parameters, check if the function is a lambda
8951 // call operator, and if so, emit a prettier and more informative
8952 // diagnostic that mentions 'auto' and lambda in addition to
8953 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008954 S.Diag(Templated->getLocation(),
8955 diag::note_ovl_candidate_non_deduced_mismatch)
8956 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00008957 return;
Richard Trieue3732352013-04-08 21:11:40 +00008958 }
John McCall8b9ed552010-02-01 18:53:26 +00008959 // TODO: diagnose these individually, then kill off
8960 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00008961 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008962 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8963 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008964 return;
8965 }
8966}
8967
Larisse Voufo98b20f12013-07-19 23:00:19 +00008968/// Diagnose a failed template-argument deduction, for function calls.
8969void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8970 unsigned TDK = Cand->DeductionFailure.Result;
8971 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8972 if (CheckArityMismatch(S, Cand, NumArgs))
8973 return;
8974 }
8975 DiagnoseBadDeduction(S, Cand->Function, // pattern
8976 Cand->DeductionFailure, NumArgs);
8977}
8978
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008979/// CUDA: diagnose an invalid call across targets.
8980void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8981 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8982 FunctionDecl *Callee = Cand->Function;
8983
8984 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8985 CalleeTarget = S.IdentifyCUDATarget(Callee);
8986
8987 std::string FnDesc;
8988 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8989
8990 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8991 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8992}
8993
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008994void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
8995 FunctionDecl *Callee = Cand->Function;
8996 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
8997
8998 S.Diag(Callee->getLocation(),
8999 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9000 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9001}
9002
John McCall8b9ed552010-02-01 18:53:26 +00009003/// Generates a 'note' diagnostic for an overload candidate. We've
9004/// already generated a primary error at the call site.
9005///
9006/// It really does need to be a single diagnostic with its caret
9007/// pointed at the candidate declaration. Yes, this creates some
9008/// major challenges of technical writing. Yes, this makes pointing
9009/// out problems with specific arguments quite awkward. It's still
9010/// better than generating twenty screens of text for every failed
9011/// overload.
9012///
9013/// It would be great to be able to express per-candidate problems
9014/// more richly for those diagnostic clients that cared, but we'd
9015/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00009016void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009017 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009018 FunctionDecl *Fn = Cand->Function;
9019
John McCall12f97bc2010-01-08 04:41:39 +00009020 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009021 if (Cand->Viable && (Fn->isDeleted() ||
9022 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009023 std::string FnDesc;
9024 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009025
9026 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009027 << FnKind << FnDesc
9028 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009029 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009030 return;
John McCall12f97bc2010-01-08 04:41:39 +00009031 }
9032
John McCalle1ac8d12010-01-13 00:25:19 +00009033 // We don't really have anything else to say about viable candidates.
9034 if (Cand->Viable) {
9035 S.NoteOverloadCandidate(Fn);
9036 return;
9037 }
John McCall0d1da222010-01-12 00:44:57 +00009038
John McCall6a61b522010-01-13 09:16:55 +00009039 switch (Cand->FailureKind) {
9040 case ovl_fail_too_many_arguments:
9041 case ovl_fail_too_few_arguments:
9042 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009043
John McCall6a61b522010-01-13 09:16:55 +00009044 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009045 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009046
John McCallfe796dd2010-01-23 05:17:32 +00009047 case ovl_fail_trivial_conversion:
9048 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009049 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009050 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009051
John McCall65eb8792010-02-25 01:37:24 +00009052 case ovl_fail_bad_conversion: {
9053 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009054 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009055 if (Cand->Conversions[I].isBad())
9056 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009057
John McCall6a61b522010-01-13 09:16:55 +00009058 // FIXME: this currently happens when we're called from SemaInit
9059 // when user-conversion overload fails. Figure out how to handle
9060 // those conditions and diagnose them well.
9061 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009062 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009063
9064 case ovl_fail_bad_target:
9065 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009066
9067 case ovl_fail_enable_if:
9068 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009069 }
John McCalld3224162010-01-08 00:58:21 +00009070}
9071
9072void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9073 // Desugar the type of the surrogate down to a function type,
9074 // retaining as many typedefs as possible while still showing
9075 // the function type (and, therefore, its parameter types).
9076 QualType FnType = Cand->Surrogate->getConversionType();
9077 bool isLValueReference = false;
9078 bool isRValueReference = false;
9079 bool isPointer = false;
9080 if (const LValueReferenceType *FnTypeRef =
9081 FnType->getAs<LValueReferenceType>()) {
9082 FnType = FnTypeRef->getPointeeType();
9083 isLValueReference = true;
9084 } else if (const RValueReferenceType *FnTypeRef =
9085 FnType->getAs<RValueReferenceType>()) {
9086 FnType = FnTypeRef->getPointeeType();
9087 isRValueReference = true;
9088 }
9089 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9090 FnType = FnTypePtr->getPointeeType();
9091 isPointer = true;
9092 }
9093 // Desugar down to a function type.
9094 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9095 // Reconstruct the pointer/reference as appropriate.
9096 if (isPointer) FnType = S.Context.getPointerType(FnType);
9097 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9098 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9099
9100 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9101 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009102 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009103}
9104
9105void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009106 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009107 SourceLocation OpLoc,
9108 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009109 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009110 std::string TypeStr("operator");
9111 TypeStr += Opc;
9112 TypeStr += "(";
9113 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009114 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009115 TypeStr += ")";
9116 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9117 } else {
9118 TypeStr += ", ";
9119 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9120 TypeStr += ")";
9121 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9122 }
9123}
9124
9125void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9126 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009127 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009128 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9129 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009130 if (ICS.isBad()) break; // all meaningless after first invalid
9131 if (!ICS.isAmbiguous()) continue;
9132
John McCall5c32be02010-08-24 20:38:10 +00009133 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009134 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009135 }
9136}
9137
Larisse Voufo98b20f12013-07-19 23:00:19 +00009138static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009139 if (Cand->Function)
9140 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009141 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009142 return Cand->Surrogate->getLocation();
9143 return SourceLocation();
9144}
9145
Larisse Voufo98b20f12013-07-19 23:00:19 +00009146static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009147 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009148 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009149 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009150
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009151 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009152 case Sema::TDK_Incomplete:
9153 return 1;
9154
9155 case Sema::TDK_Underqualified:
9156 case Sema::TDK_Inconsistent:
9157 return 2;
9158
9159 case Sema::TDK_SubstitutionFailure:
9160 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009161 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009162 return 3;
9163
9164 case Sema::TDK_InstantiationDepth:
9165 case Sema::TDK_FailedOverloadResolution:
9166 return 4;
9167
9168 case Sema::TDK_InvalidExplicitArguments:
9169 return 5;
9170
9171 case Sema::TDK_TooManyArguments:
9172 case Sema::TDK_TooFewArguments:
9173 return 6;
9174 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009175 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009176}
9177
John McCallad2587a2010-01-12 00:48:53 +00009178struct CompareOverloadCandidatesForDisplay {
9179 Sema &S;
9180 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00009181
9182 bool operator()(const OverloadCandidate *L,
9183 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009184 // Fast-path this check.
9185 if (L == R) return false;
9186
John McCall12f97bc2010-01-08 04:41:39 +00009187 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009188 if (L->Viable) {
9189 if (!R->Viable) return true;
9190
9191 // TODO: introduce a tri-valued comparison for overload
9192 // candidates. Would be more worthwhile if we had a sort
9193 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009194 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9195 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009196 } else if (R->Viable)
9197 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009198
John McCall3712d9e2010-01-15 23:32:50 +00009199 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009200
John McCall3712d9e2010-01-15 23:32:50 +00009201 // Criteria by which we can sort non-viable candidates:
9202 if (!L->Viable) {
9203 // 1. Arity mismatches come after other candidates.
9204 if (L->FailureKind == ovl_fail_too_many_arguments ||
9205 L->FailureKind == ovl_fail_too_few_arguments)
9206 return false;
9207 if (R->FailureKind == ovl_fail_too_many_arguments ||
9208 R->FailureKind == ovl_fail_too_few_arguments)
9209 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009210
John McCallfe796dd2010-01-23 05:17:32 +00009211 // 2. Bad conversions come first and are ordered by the number
9212 // of bad conversions and quality of good conversions.
9213 if (L->FailureKind == ovl_fail_bad_conversion) {
9214 if (R->FailureKind != ovl_fail_bad_conversion)
9215 return true;
9216
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009217 // The conversion that can be fixed with a smaller number of changes,
9218 // comes first.
9219 unsigned numLFixes = L->Fix.NumConversionsFixed;
9220 unsigned numRFixes = R->Fix.NumConversionsFixed;
9221 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9222 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009223 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009224 if (numLFixes < numRFixes)
9225 return true;
9226 else
9227 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009228 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009229
John McCallfe796dd2010-01-23 05:17:32 +00009230 // If there's any ordering between the defined conversions...
9231 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009232 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009233
9234 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009235 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009236 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009237 switch (CompareImplicitConversionSequences(S,
9238 L->Conversions[I],
9239 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009240 case ImplicitConversionSequence::Better:
9241 leftBetter++;
9242 break;
9243
9244 case ImplicitConversionSequence::Worse:
9245 leftBetter--;
9246 break;
9247
9248 case ImplicitConversionSequence::Indistinguishable:
9249 break;
9250 }
9251 }
9252 if (leftBetter > 0) return true;
9253 if (leftBetter < 0) return false;
9254
9255 } else if (R->FailureKind == ovl_fail_bad_conversion)
9256 return false;
9257
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009258 if (L->FailureKind == ovl_fail_bad_deduction) {
9259 if (R->FailureKind != ovl_fail_bad_deduction)
9260 return true;
9261
9262 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9263 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009264 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009265 } else if (R->FailureKind == ovl_fail_bad_deduction)
9266 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009267
John McCall3712d9e2010-01-15 23:32:50 +00009268 // TODO: others?
9269 }
9270
9271 // Sort everything else by location.
9272 SourceLocation LLoc = GetLocationForCandidate(L);
9273 SourceLocation RLoc = GetLocationForCandidate(R);
9274
9275 // Put candidates without locations (e.g. builtins) at the end.
9276 if (LLoc.isInvalid()) return false;
9277 if (RLoc.isInvalid()) return true;
9278
9279 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009280 }
9281};
9282
John McCallfe796dd2010-01-23 05:17:32 +00009283/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009284/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009285void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009286 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009287 assert(!Cand->Viable);
9288
9289 // Don't do anything on failures other than bad conversion.
9290 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9291
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009292 // We only want the FixIts if all the arguments can be corrected.
9293 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009294 // Use a implicit copy initialization to check conversion fixes.
9295 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009296
John McCallfe796dd2010-01-23 05:17:32 +00009297 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009298 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009299 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009300 while (true) {
9301 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9302 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009303 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009304 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009305 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009306 }
John McCallfe796dd2010-01-23 05:17:32 +00009307 }
9308
9309 if (ConvIdx == ConvCount)
9310 return;
9311
John McCall65eb8792010-02-25 01:37:24 +00009312 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9313 "remaining conversion is initialized?");
9314
Douglas Gregoradc7a702010-04-16 17:45:54 +00009315 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009316 // operation somehow.
9317 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009318
9319 const FunctionProtoType* Proto;
9320 unsigned ArgIdx = ConvIdx;
9321
9322 if (Cand->IsSurrogate) {
9323 QualType ConvType
9324 = Cand->Surrogate->getConversionType().getNonReferenceType();
9325 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9326 ConvType = ConvPtrType->getPointeeType();
9327 Proto = ConvType->getAs<FunctionProtoType>();
9328 ArgIdx--;
9329 } else if (Cand->Function) {
9330 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9331 if (isa<CXXMethodDecl>(Cand->Function) &&
9332 !isa<CXXConstructorDecl>(Cand->Function))
9333 ArgIdx--;
9334 } else {
9335 // Builtin binary operator with a bad first conversion.
9336 assert(ConvCount <= 3);
9337 for (; ConvIdx != ConvCount; ++ConvIdx)
9338 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009339 = TryCopyInitialization(S, Args[ConvIdx],
9340 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009341 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009342 /*InOverloadResolution*/ true,
9343 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009344 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009345 return;
9346 }
9347
9348 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009349 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009350 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009351 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009352 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9353 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9354 /*InOverloadResolution=*/true,
9355 /*AllowObjCWritebackConversion=*/
9356 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009357 // Store the FixIt in the candidate if it exists.
9358 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009359 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009360 }
John McCallfe796dd2010-01-23 05:17:32 +00009361 else
9362 Cand->Conversions[ConvIdx].setEllipsis();
9363 }
9364}
9365
John McCalld3224162010-01-08 00:58:21 +00009366} // end anonymous namespace
9367
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009368/// PrintOverloadCandidates - When overload resolution fails, prints
9369/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009370/// set.
John McCall5c32be02010-08-24 20:38:10 +00009371void OverloadCandidateSet::NoteCandidates(Sema &S,
9372 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009373 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009374 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009375 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009376 // Sort the candidates by viability and position. Sorting directly would
9377 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009378 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009379 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9380 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009381 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009382 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009383 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009384 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009385 if (Cand->Function || Cand->IsSurrogate)
9386 Cands.push_back(Cand);
9387 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9388 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009389 }
9390 }
9391
John McCallad2587a2010-01-12 00:48:53 +00009392 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00009393 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009394
John McCall0d1da222010-01-12 00:44:57 +00009395 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009396
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009397 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009398 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009399 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009400 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9401 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009402
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009403 // Set an arbitrary limit on the number of candidate functions we'll spam
9404 // the user with. FIXME: This limit should depend on details of the
9405 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009406 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009407 break;
9408 }
9409 ++CandsShown;
9410
John McCalld3224162010-01-08 00:58:21 +00009411 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009412 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009413 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009414 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009415 else {
9416 assert(Cand->Viable &&
9417 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009418 // Generally we only see ambiguities including viable builtin
9419 // operators if overload resolution got screwed up by an
9420 // ambiguous user-defined conversion.
9421 //
9422 // FIXME: It's quite possible for different conversions to see
9423 // different ambiguities, though.
9424 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009425 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009426 ReportedAmbiguousConversions = true;
9427 }
John McCalld3224162010-01-08 00:58:21 +00009428
John McCall0d1da222010-01-12 00:44:57 +00009429 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009430 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009431 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009432 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009433
9434 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009435 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009436}
9437
Larisse Voufo98b20f12013-07-19 23:00:19 +00009438static SourceLocation
9439GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9440 return Cand->Specialization ? Cand->Specialization->getLocation()
9441 : SourceLocation();
9442}
9443
9444struct CompareTemplateSpecCandidatesForDisplay {
9445 Sema &S;
9446 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9447
9448 bool operator()(const TemplateSpecCandidate *L,
9449 const TemplateSpecCandidate *R) {
9450 // Fast-path this check.
9451 if (L == R)
9452 return false;
9453
9454 // Assuming that both candidates are not matches...
9455
9456 // Sort by the ranking of deduction failures.
9457 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9458 return RankDeductionFailure(L->DeductionFailure) <
9459 RankDeductionFailure(R->DeductionFailure);
9460
9461 // Sort everything else by location.
9462 SourceLocation LLoc = GetLocationForCandidate(L);
9463 SourceLocation RLoc = GetLocationForCandidate(R);
9464
9465 // Put candidates without locations (e.g. builtins) at the end.
9466 if (LLoc.isInvalid())
9467 return false;
9468 if (RLoc.isInvalid())
9469 return true;
9470
9471 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9472 }
9473};
9474
9475/// Diagnose a template argument deduction failure.
9476/// We are treating these failures as overload failures due to bad
9477/// deductions.
9478void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9479 DiagnoseBadDeduction(S, Specialization, // pattern
9480 DeductionFailure, /*NumArgs=*/0);
9481}
9482
9483void TemplateSpecCandidateSet::destroyCandidates() {
9484 for (iterator i = begin(), e = end(); i != e; ++i) {
9485 i->DeductionFailure.Destroy();
9486 }
9487}
9488
9489void TemplateSpecCandidateSet::clear() {
9490 destroyCandidates();
9491 Candidates.clear();
9492}
9493
9494/// NoteCandidates - When no template specialization match is found, prints
9495/// diagnostic messages containing the non-matching specializations that form
9496/// the candidate set.
9497/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9498/// OCD == OCD_AllCandidates and Cand->Viable == false.
9499void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9500 // Sort the candidates by position (assuming no candidate is a match).
9501 // Sorting directly would be prohibitive, so we make a set of pointers
9502 // and sort those.
9503 SmallVector<TemplateSpecCandidate *, 32> Cands;
9504 Cands.reserve(size());
9505 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9506 if (Cand->Specialization)
9507 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009508 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009509 // in general, want to list every possible builtin candidate.
9510 }
9511
9512 std::sort(Cands.begin(), Cands.end(),
9513 CompareTemplateSpecCandidatesForDisplay(S));
9514
9515 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9516 // for generalization purposes (?).
9517 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9518
9519 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9520 unsigned CandsShown = 0;
9521 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9522 TemplateSpecCandidate *Cand = *I;
9523
9524 // Set an arbitrary limit on the number of candidates we'll spam
9525 // the user with. FIXME: This limit should depend on details of the
9526 // candidate list.
9527 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9528 break;
9529 ++CandsShown;
9530
9531 assert(Cand->Specialization &&
9532 "Non-matching built-in candidates are not added to Cands.");
9533 Cand->NoteDeductionFailure(S);
9534 }
9535
9536 if (I != E)
9537 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9538}
9539
Douglas Gregorb491ed32011-02-19 21:32:49 +00009540// [PossiblyAFunctionType] --> [Return]
9541// NonFunctionType --> NonFunctionType
9542// R (A) --> R(A)
9543// R (*)(A) --> R (A)
9544// R (&)(A) --> R (A)
9545// R (S::*)(A) --> R (A)
9546QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9547 QualType Ret = PossiblyAFunctionType;
9548 if (const PointerType *ToTypePtr =
9549 PossiblyAFunctionType->getAs<PointerType>())
9550 Ret = ToTypePtr->getPointeeType();
9551 else if (const ReferenceType *ToTypeRef =
9552 PossiblyAFunctionType->getAs<ReferenceType>())
9553 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009554 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009555 PossiblyAFunctionType->getAs<MemberPointerType>())
9556 Ret = MemTypePtr->getPointeeType();
9557 Ret =
9558 Context.getCanonicalType(Ret).getUnqualifiedType();
9559 return Ret;
9560}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009561
Douglas Gregorb491ed32011-02-19 21:32:49 +00009562// A helper class to help with address of function resolution
9563// - allows us to avoid passing around all those ugly parameters
9564class AddressOfFunctionResolver
9565{
9566 Sema& S;
9567 Expr* SourceExpr;
9568 const QualType& TargetType;
9569 QualType TargetFunctionType; // Extracted function type from target type
9570
9571 bool Complain;
9572 //DeclAccessPair& ResultFunctionAccessPair;
9573 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009574
Douglas Gregorb491ed32011-02-19 21:32:49 +00009575 bool TargetTypeIsNonStaticMemberFunction;
9576 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009577 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009578
Douglas Gregorb491ed32011-02-19 21:32:49 +00009579 OverloadExpr::FindResult OvlExprInfo;
9580 OverloadExpr *OvlExpr;
9581 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009582 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009583 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009584
Douglas Gregorb491ed32011-02-19 21:32:49 +00009585public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009586 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9587 const QualType &TargetType, bool Complain)
9588 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9589 Complain(Complain), Context(S.getASTContext()),
9590 TargetTypeIsNonStaticMemberFunction(
9591 !!TargetType->getAs<MemberPointerType>()),
9592 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009593 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009594 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9595 OvlExpr(OvlExprInfo.Expression),
9596 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009597 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009598
David Majnemera4f7c7a2013-08-01 06:13:59 +00009599 if (TargetFunctionType->isFunctionType()) {
9600 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9601 if (!UME->isImplicitAccess() &&
9602 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9603 StaticMemberFunctionFromBoundPointer = true;
9604 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9605 DeclAccessPair dap;
9606 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9607 OvlExpr, false, &dap)) {
9608 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9609 if (!Method->isStatic()) {
9610 // If the target type is a non-function type and the function found
9611 // is a non-static member function, pretend as if that was the
9612 // target, it's the only possible type to end up with.
9613 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009614
David Majnemera4f7c7a2013-08-01 06:13:59 +00009615 // And skip adding the function if its not in the proper form.
9616 // We'll diagnose this due to an empty set of functions.
9617 if (!OvlExprInfo.HasFormOfMemberPointer)
9618 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009619 }
9620
David Majnemera4f7c7a2013-08-01 06:13:59 +00009621 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009622 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009623 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009624 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009625
9626 if (OvlExpr->hasExplicitTemplateArgs())
9627 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009628
Douglas Gregorb491ed32011-02-19 21:32:49 +00009629 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9630 // C++ [over.over]p4:
9631 // If more than one function is selected, [...]
9632 if (Matches.size() > 1) {
9633 if (FoundNonTemplateFunction)
9634 EliminateAllTemplateMatches();
9635 else
9636 EliminateAllExceptMostSpecializedTemplate();
9637 }
9638 }
9639 }
9640
9641private:
9642 bool isTargetTypeAFunction() const {
9643 return TargetFunctionType->isFunctionType();
9644 }
9645
9646 // [ToType] [Return]
9647
9648 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9649 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9650 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9651 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9652 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9653 }
9654
9655 // return true if any matching specializations were found
9656 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9657 const DeclAccessPair& CurAccessFunPair) {
9658 if (CXXMethodDecl *Method
9659 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9660 // Skip non-static function templates when converting to pointer, and
9661 // static when converting to member pointer.
9662 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9663 return false;
9664 }
9665 else if (TargetTypeIsNonStaticMemberFunction)
9666 return false;
9667
9668 // C++ [over.over]p2:
9669 // If the name is a function template, template argument deduction is
9670 // done (14.8.2.2), and if the argument deduction succeeds, the
9671 // resulting template argument list is used to generate a single
9672 // function template specialization, which is added to the set of
9673 // overloaded functions considered.
9674 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009675 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009676 if (Sema::TemplateDeductionResult Result
9677 = S.DeduceTemplateArguments(FunctionTemplate,
9678 &OvlExplicitTemplateArgs,
9679 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009680 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009681 // Make a note of the failed deduction for diagnostics.
9682 FailedCandidates.addCandidate()
9683 .set(FunctionTemplate->getTemplatedDecl(),
9684 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009685 return false;
9686 }
9687
Douglas Gregor19a41f12013-04-17 08:45:07 +00009688 // Template argument deduction ensures that we have an exact match or
9689 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009690 // This function template specicalization works.
9691 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009692 assert(S.isSameOrCompatibleFunctionType(
9693 Context.getCanonicalType(Specialization->getType()),
9694 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009695 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9696 return true;
9697 }
9698
9699 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9700 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009701 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009702 // Skip non-static functions when converting to pointer, and static
9703 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009704 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9705 return false;
9706 }
9707 else if (TargetTypeIsNonStaticMemberFunction)
9708 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009709
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009710 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009711 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009712 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9713 if (S.CheckCUDATarget(Caller, FunDecl))
9714 return false;
9715
Richard Smith2a7d4812013-05-04 07:00:32 +00009716 // If any candidate has a placeholder return type, trigger its deduction
9717 // now.
9718 if (S.getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +00009719 FunDecl->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +00009720 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9721 return false;
9722
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009723 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009724 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9725 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009726 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9727 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009728 Matches.push_back(std::make_pair(CurAccessFunPair,
9729 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009730 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009731 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009732 }
Mike Stump11289f42009-09-09 15:08:12 +00009733 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009734
9735 return false;
9736 }
9737
9738 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9739 bool Ret = false;
9740
9741 // If the overload expression doesn't have the form of a pointer to
9742 // member, don't try to convert it to a pointer-to-member type.
9743 if (IsInvalidFormOfPointerToMemberFunction())
9744 return false;
9745
9746 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9747 E = OvlExpr->decls_end();
9748 I != E; ++I) {
9749 // Look through any using declarations to find the underlying function.
9750 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9751
9752 // C++ [over.over]p3:
9753 // Non-member functions and static member functions match
9754 // targets of type "pointer-to-function" or "reference-to-function."
9755 // Nonstatic member functions match targets of
9756 // type "pointer-to-member-function."
9757 // Note that according to DR 247, the containing class does not matter.
9758 if (FunctionTemplateDecl *FunctionTemplate
9759 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9760 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9761 Ret = true;
9762 }
9763 // If we have explicit template arguments supplied, skip non-templates.
9764 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9765 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9766 Ret = true;
9767 }
9768 assert(Ret || Matches.empty());
9769 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009770 }
9771
Douglas Gregorb491ed32011-02-19 21:32:49 +00009772 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009773 // [...] and any given function template specialization F1 is
9774 // eliminated if the set contains a second function template
9775 // specialization whose function template is more specialized
9776 // than the function template of F1 according to the partial
9777 // ordering rules of 14.5.5.2.
9778
9779 // The algorithm specified above is quadratic. We instead use a
9780 // two-pass algorithm (similar to the one used to identify the
9781 // best viable function in an overload set) that identifies the
9782 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009783
9784 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9785 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9786 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009787
Larisse Voufo98b20f12013-07-19 23:00:19 +00009788 // TODO: It looks like FailedCandidates does not serve much purpose
9789 // here, since the no_viable diagnostic has index 0.
9790 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009791 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009792 SourceExpr->getLocStart(), S.PDiag(),
9793 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9794 .second->getDeclName(),
9795 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9796 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009797
Douglas Gregorb491ed32011-02-19 21:32:49 +00009798 if (Result != MatchesCopy.end()) {
9799 // Make it the first and only element
9800 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9801 Matches[0].second = cast<FunctionDecl>(*Result);
9802 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009803 }
9804 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009805
Douglas Gregorb491ed32011-02-19 21:32:49 +00009806 void EliminateAllTemplateMatches() {
9807 // [...] any function template specializations in the set are
9808 // eliminated if the set also contains a non-template function, [...]
9809 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9810 if (Matches[I].second->getPrimaryTemplate() == 0)
9811 ++I;
9812 else {
9813 Matches[I] = Matches[--N];
9814 Matches.set_size(N);
9815 }
9816 }
9817 }
9818
9819public:
9820 void ComplainNoMatchesFound() const {
9821 assert(Matches.empty());
9822 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9823 << OvlExpr->getName() << TargetFunctionType
9824 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009825 if (FailedCandidates.empty())
9826 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9827 else {
9828 // We have some deduction failure messages. Use them to diagnose
9829 // the function templates, and diagnose the non-template candidates
9830 // normally.
9831 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9832 IEnd = OvlExpr->decls_end();
9833 I != IEnd; ++I)
9834 if (FunctionDecl *Fun =
9835 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9836 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9837 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9838 }
9839 }
9840
Douglas Gregorb491ed32011-02-19 21:32:49 +00009841 bool IsInvalidFormOfPointerToMemberFunction() const {
9842 return TargetTypeIsNonStaticMemberFunction &&
9843 !OvlExprInfo.HasFormOfMemberPointer;
9844 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009845
Douglas Gregorb491ed32011-02-19 21:32:49 +00009846 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9847 // TODO: Should we condition this on whether any functions might
9848 // have matched, or is it more appropriate to do that in callers?
9849 // TODO: a fixit wouldn't hurt.
9850 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9851 << TargetType << OvlExpr->getSourceRange();
9852 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009853
9854 bool IsStaticMemberFunctionFromBoundPointer() const {
9855 return StaticMemberFunctionFromBoundPointer;
9856 }
9857
9858 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9859 S.Diag(OvlExpr->getLocStart(),
9860 diag::err_invalid_form_pointer_member_function)
9861 << OvlExpr->getSourceRange();
9862 }
9863
Douglas Gregorb491ed32011-02-19 21:32:49 +00009864 void ComplainOfInvalidConversion() const {
9865 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9866 << OvlExpr->getName() << TargetType;
9867 }
9868
9869 void ComplainMultipleMatchesFound() const {
9870 assert(Matches.size() > 1);
9871 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9872 << OvlExpr->getName()
9873 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009874 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009875 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009876
9877 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9878
Douglas Gregorb491ed32011-02-19 21:32:49 +00009879 int getNumMatches() const { return Matches.size(); }
9880
9881 FunctionDecl* getMatchingFunctionDecl() const {
9882 if (Matches.size() != 1) return 0;
9883 return Matches[0].second;
9884 }
9885
9886 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9887 if (Matches.size() != 1) return 0;
9888 return &Matches[0].first;
9889 }
9890};
9891
9892/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9893/// an overloaded function (C++ [over.over]), where @p From is an
9894/// expression with overloaded function type and @p ToType is the type
9895/// we're trying to resolve to. For example:
9896///
9897/// @code
9898/// int f(double);
9899/// int f(int);
9900///
9901/// int (*pfd)(double) = f; // selects f(double)
9902/// @endcode
9903///
9904/// This routine returns the resulting FunctionDecl if it could be
9905/// resolved, and NULL otherwise. When @p Complain is true, this
9906/// routine will emit diagnostics if there is an error.
9907FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009908Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9909 QualType TargetType,
9910 bool Complain,
9911 DeclAccessPair &FoundResult,
9912 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009913 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009914
9915 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9916 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009917 int NumMatches = Resolver.getNumMatches();
9918 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009919 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009920 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9921 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9922 else
9923 Resolver.ComplainNoMatchesFound();
9924 }
9925 else if (NumMatches > 1 && Complain)
9926 Resolver.ComplainMultipleMatchesFound();
9927 else if (NumMatches == 1) {
9928 Fn = Resolver.getMatchingFunctionDecl();
9929 assert(Fn);
9930 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +00009931 if (Complain) {
9932 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9933 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9934 else
9935 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9936 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009937 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009938
9939 if (pHadMultipleCandidates)
9940 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009941 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009942}
9943
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009944/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009945/// resolve that overloaded function expression down to a single function.
9946///
9947/// This routine can only resolve template-ids that refer to a single function
9948/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009949/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009950/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +00009951///
9952/// If no template-ids are found, no diagnostics are emitted and NULL is
9953/// returned.
John McCall0009fcc2011-04-26 20:42:42 +00009954FunctionDecl *
9955Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9956 bool Complain,
9957 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009958 // C++ [over.over]p1:
9959 // [...] [Note: any redundant set of parentheses surrounding the
9960 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009961 // C++ [over.over]p1:
9962 // [...] The overloaded function name can be preceded by the &
9963 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009964
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009965 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009966 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009967 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009968
9969 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009970 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009971 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009972
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009973 // Look through all of the overloaded functions, searching for one
9974 // whose type matches exactly.
9975 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009976 for (UnresolvedSetIterator I = ovl->decls_begin(),
9977 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009978 // C++0x [temp.arg.explicit]p3:
9979 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009980 // where deduction is not done, if a template argument list is
9981 // specified and it, along with any default template arguments,
9982 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009983 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009984 FunctionTemplateDecl *FunctionTemplate
9985 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009986
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009987 // C++ [over.over]p2:
9988 // If the name is a function template, template argument deduction is
9989 // done (14.8.2.2), and if the argument deduction succeeds, the
9990 // resulting template argument list is used to generate a single
9991 // function template specialization, which is added to the set of
9992 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009993 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009994 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009995 if (TemplateDeductionResult Result
9996 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009997 Specialization, Info,
9998 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009999 // Make a note of the failed deduction for diagnostics.
10000 // TODO: Actually use the failed-deduction info?
10001 FailedCandidates.addCandidate()
10002 .set(FunctionTemplate->getTemplatedDecl(),
10003 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010004 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010005 }
10006
John McCall0009fcc2011-04-26 20:42:42 +000010007 assert(Specialization && "no specialization and no error?");
10008
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010009 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010010 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010011 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010012 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10013 << ovl->getName();
10014 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010015 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010016 return 0;
John McCall0009fcc2011-04-26 20:42:42 +000010017 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010018
John McCall0009fcc2011-04-26 20:42:42 +000010019 Matched = Specialization;
10020 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010021 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010022
Richard Smith2a7d4812013-05-04 07:00:32 +000010023 if (Matched && getLangOpts().CPlusPlus1y &&
Alp Toker314cc812014-01-25 16:55:45 +000010024 Matched->getReturnType()->isUndeducedType() &&
Richard Smith2a7d4812013-05-04 07:00:32 +000010025 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10026 return 0;
10027
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010028 return Matched;
10029}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010030
Douglas Gregor1beec452011-03-12 01:48:56 +000010031
10032
10033
John McCall50a2c2c2011-10-11 23:14:30 +000010034// Resolve and fix an overloaded expression that can be resolved
10035// because it identifies a single function template specialization.
10036//
Douglas Gregor1beec452011-03-12 01:48:56 +000010037// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010038//
10039// Return true if it was logically possible to so resolve the
10040// expression, regardless of whether or not it succeeded. Always
10041// returns true if 'complain' is set.
10042bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10043 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10044 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010045 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010046 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010047 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010048
John McCall50a2c2c2011-10-11 23:14:30 +000010049 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010050
John McCall0009fcc2011-04-26 20:42:42 +000010051 DeclAccessPair found;
10052 ExprResult SingleFunctionExpression;
10053 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10054 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010055 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010056 SrcExpr = ExprError();
10057 return true;
10058 }
John McCall0009fcc2011-04-26 20:42:42 +000010059
10060 // It is only correct to resolve to an instance method if we're
10061 // resolving a form that's permitted to be a pointer to member.
10062 // Otherwise we'll end up making a bound member expression, which
10063 // is illegal in all the contexts we resolve like this.
10064 if (!ovl.HasFormOfMemberPointer &&
10065 isa<CXXMethodDecl>(fn) &&
10066 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010067 if (!complain) return false;
10068
10069 Diag(ovl.Expression->getExprLoc(),
10070 diag::err_bound_member_function)
10071 << 0 << ovl.Expression->getSourceRange();
10072
10073 // TODO: I believe we only end up here if there's a mix of
10074 // static and non-static candidates (otherwise the expression
10075 // would have 'bound member' type, not 'overload' type).
10076 // Ideally we would note which candidate was chosen and why
10077 // the static candidates were rejected.
10078 SrcExpr = ExprError();
10079 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010080 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010081
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010082 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010083 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +000010084 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +000010085
10086 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010087 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010088 SingleFunctionExpression =
10089 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +000010090 if (SingleFunctionExpression.isInvalid()) {
10091 SrcExpr = ExprError();
10092 return true;
10093 }
10094 }
John McCall0009fcc2011-04-26 20:42:42 +000010095 }
10096
10097 if (!SingleFunctionExpression.isUsable()) {
10098 if (complain) {
10099 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10100 << ovl.Expression->getName()
10101 << DestTypeForComplaining
10102 << OpRangeForComplaining
10103 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010104 NoteAllOverloadCandidates(SrcExpr.get());
10105
10106 SrcExpr = ExprError();
10107 return true;
10108 }
10109
10110 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010111 }
10112
John McCall50a2c2c2011-10-11 23:14:30 +000010113 SrcExpr = SingleFunctionExpression;
10114 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010115}
10116
Douglas Gregorcabea402009-09-22 15:41:20 +000010117/// \brief Add a single candidate to the overload set.
10118static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010119 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010120 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010121 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010122 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010123 bool PartialOverloading,
10124 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010125 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010126 if (isa<UsingShadowDecl>(Callee))
10127 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10128
Douglas Gregorcabea402009-09-22 15:41:20 +000010129 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010130 if (ExplicitTemplateArgs) {
10131 assert(!KnownValid && "Explicit template arguments?");
10132 return;
10133 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010134 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10135 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010136 return;
John McCalld14a8642009-11-21 08:51:07 +000010137 }
10138
10139 if (FunctionTemplateDecl *FuncTemplate
10140 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010141 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010142 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010143 return;
10144 }
10145
Richard Smith95ce4f62011-06-26 22:19:54 +000010146 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010147}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010148
Douglas Gregorcabea402009-09-22 15:41:20 +000010149/// \brief Add the overload candidates named by callee and/or found by argument
10150/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010151void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010152 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010153 OverloadCandidateSet &CandidateSet,
10154 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010155
10156#ifndef NDEBUG
10157 // Verify that ArgumentDependentLookup is consistent with the rules
10158 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010159 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010160 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10161 // and let Y be the lookup set produced by argument dependent
10162 // lookup (defined as follows). If X contains
10163 //
10164 // -- a declaration of a class member, or
10165 //
10166 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010167 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010168 //
10169 // -- a declaration that is neither a function or a function
10170 // template
10171 //
10172 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010173
John McCall57500772009-12-16 12:17:52 +000010174 if (ULE->requiresADL()) {
10175 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10176 E = ULE->decls_end(); I != E; ++I) {
10177 assert(!(*I)->getDeclContext()->isRecord());
10178 assert(isa<UsingShadowDecl>(*I) ||
10179 !(*I)->getDeclContext()->isFunctionOrMethod());
10180 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010181 }
10182 }
10183#endif
10184
John McCall57500772009-12-16 12:17:52 +000010185 // It would be nice to avoid this copy.
10186 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +000010187 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010188 if (ULE->hasExplicitTemplateArgs()) {
10189 ULE->copyTemplateArgumentsInto(TABuffer);
10190 ExplicitTemplateArgs = &TABuffer;
10191 }
10192
10193 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10194 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010195 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10196 CandidateSet, PartialOverloading,
10197 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010198
John McCall57500772009-12-16 12:17:52 +000010199 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +000010200 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +000010201 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010202 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010203 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010204}
John McCalld681c392009-12-16 08:11:27 +000010205
Richard Smith0603bbb2013-06-12 22:56:54 +000010206/// Determine whether a declaration with the specified name could be moved into
10207/// a different namespace.
10208static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10209 switch (Name.getCXXOverloadedOperator()) {
10210 case OO_New: case OO_Array_New:
10211 case OO_Delete: case OO_Array_Delete:
10212 return false;
10213
10214 default:
10215 return true;
10216 }
10217}
10218
Richard Smith998a5912011-06-05 22:42:48 +000010219/// Attempt to recover from an ill-formed use of a non-dependent name in a
10220/// template, where the non-dependent name was declared after the template
10221/// was defined. This is common in code written for a compilers which do not
10222/// correctly implement two-stage name lookup.
10223///
10224/// Returns true if a viable candidate was found and a diagnostic was issued.
10225static bool
10226DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10227 const CXXScopeSpec &SS, LookupResult &R,
10228 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010229 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010230 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10231 return false;
10232
10233 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010234 if (DC->isTransparentContext())
10235 continue;
10236
Richard Smith998a5912011-06-05 22:42:48 +000010237 SemaRef.LookupQualifiedName(R, DC);
10238
10239 if (!R.empty()) {
10240 R.suppressDiagnostics();
10241
10242 if (isa<CXXRecordDecl>(DC)) {
10243 // Don't diagnose names we find in classes; we get much better
10244 // diagnostics for these from DiagnoseEmptyLookup.
10245 R.clear();
10246 return false;
10247 }
10248
10249 OverloadCandidateSet Candidates(FnLoc);
10250 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10251 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010252 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010253 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010254
10255 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010256 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010257 // No viable functions. Don't bother the user with notes for functions
10258 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010259 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010260 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010261 }
Richard Smith998a5912011-06-05 22:42:48 +000010262
10263 // Find the namespaces where ADL would have looked, and suggest
10264 // declaring the function there instead.
10265 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10266 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010267 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010268 AssociatedNamespaces,
10269 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010270 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010271 if (canBeDeclaredInNamespace(R.getLookupName())) {
10272 DeclContext *Std = SemaRef.getStdNamespace();
10273 for (Sema::AssociatedNamespaceSet::iterator
10274 it = AssociatedNamespaces.begin(),
10275 end = AssociatedNamespaces.end(); it != end; ++it) {
10276 // Never suggest declaring a function within namespace 'std'.
10277 if (Std && Std->Encloses(*it))
10278 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010279
Richard Smith0603bbb2013-06-12 22:56:54 +000010280 // Never suggest declaring a function within a namespace with a
10281 // reserved name, like __gnu_cxx.
10282 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10283 if (NS &&
10284 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10285 continue;
10286
10287 SuggestedNamespaces.insert(*it);
10288 }
Richard Smith998a5912011-06-05 22:42:48 +000010289 }
10290
10291 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10292 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010293 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010294 SemaRef.Diag(Best->Function->getLocation(),
10295 diag::note_not_found_by_two_phase_lookup)
10296 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010297 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010298 SemaRef.Diag(Best->Function->getLocation(),
10299 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010300 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010301 } else {
10302 // FIXME: It would be useful to list the associated namespaces here,
10303 // but the diagnostics infrastructure doesn't provide a way to produce
10304 // a localized representation of a list of items.
10305 SemaRef.Diag(Best->Function->getLocation(),
10306 diag::note_not_found_by_two_phase_lookup)
10307 << R.getLookupName() << 2;
10308 }
10309
10310 // Try to recover by calling this function.
10311 return true;
10312 }
10313
10314 R.clear();
10315 }
10316
10317 return false;
10318}
10319
10320/// Attempt to recover from ill-formed use of a non-dependent operator in a
10321/// template, where the non-dependent operator was declared after the template
10322/// was defined.
10323///
10324/// Returns true if a viable candidate was found and a diagnostic was issued.
10325static bool
10326DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10327 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010328 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010329 DeclarationName OpName =
10330 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10331 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10332 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010333 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010334}
10335
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010336namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010337class BuildRecoveryCallExprRAII {
10338 Sema &SemaRef;
10339public:
10340 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10341 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10342 SemaRef.IsBuildingRecoveryCallExpr = true;
10343 }
10344
10345 ~BuildRecoveryCallExprRAII() {
10346 SemaRef.IsBuildingRecoveryCallExpr = false;
10347 }
10348};
10349
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010350}
10351
John McCalld681c392009-12-16 08:11:27 +000010352/// Attempts to recover from a call where no functions were found.
10353///
10354/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010355static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010356BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010357 UnresolvedLookupExpr *ULE,
10358 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010359 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010360 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010361 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010362 // Do not try to recover if it is already building a recovery call.
10363 // This stops infinite loops for template instantiations like
10364 //
10365 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10366 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10367 //
10368 if (SemaRef.IsBuildingRecoveryCallExpr)
10369 return ExprError();
10370 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010371
10372 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010373 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010374 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010375
John McCall57500772009-12-16 12:17:52 +000010376 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +000010377 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010378 if (ULE->hasExplicitTemplateArgs()) {
10379 ULE->copyTemplateArgumentsInto(TABuffer);
10380 ExplicitTemplateArgs = &TABuffer;
10381 }
10382
John McCalld681c392009-12-16 08:11:27 +000010383 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10384 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010385 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
Kaelyn Uhrainb4b14752014-02-28 18:12:42 +000010386 ExplicitTemplateArgs != 0, false);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010387 NoTypoCorrectionCCC RejectAll;
10388 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10389 (CorrectionCandidateCallback*)&Validator :
10390 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010391 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010392 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010393 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010394 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010395 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010396 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010397
John McCall57500772009-12-16 12:17:52 +000010398 assert(!R.empty() && "lookup results empty despite recovery");
10399
10400 // Build an implicit member call if appropriate. Just drop the
10401 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010402 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010403 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010404 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10405 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010406 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010407 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010408 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010409 else
10410 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10411
10412 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010413 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010414
10415 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010416 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010417 // end up here.
John McCallb268a282010-08-23 23:25:46 +000010418 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010419 MultiExprArg(Args.data(), Args.size()),
10420 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010421}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010422
Sam Panzer0f384432012-08-21 00:52:01 +000010423/// \brief Constructs and populates an OverloadedCandidateSet from
10424/// the given function.
10425/// \returns true when an the ExprResult output parameter has been set.
10426bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10427 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010428 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010429 SourceLocation RParenLoc,
10430 OverloadCandidateSet *CandidateSet,
10431 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010432#ifndef NDEBUG
10433 if (ULE->requiresADL()) {
10434 // To do ADL, we must have found an unqualified name.
10435 assert(!ULE->getQualifier() && "qualified name with ADL");
10436
10437 // We don't perform ADL for implicit declarations of builtins.
10438 // Verify that this was correctly set up.
10439 FunctionDecl *F;
10440 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10441 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10442 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010443 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010444
John McCall57500772009-12-16 12:17:52 +000010445 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010446 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010447 }
John McCall57500772009-12-16 12:17:52 +000010448#endif
10449
John McCall4124c492011-10-17 18:40:02 +000010450 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010451 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010452 *Result = ExprError();
10453 return true;
10454 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010455
John McCall57500772009-12-16 12:17:52 +000010456 // Add the functions denoted by the callee to the set of candidate
10457 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010458 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010459
10460 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010461 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10462 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010463 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010464 // In Microsoft mode, if we are inside a template class member function then
10465 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010466 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010467 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010468 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010469 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010470 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010471 Context.DependentTy, VK_RValue,
10472 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010473 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +000010474 *Result = Owned(CE);
10475 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010476 }
Sam Panzer0f384432012-08-21 00:52:01 +000010477 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010478 }
John McCalld681c392009-12-16 08:11:27 +000010479
John McCall4124c492011-10-17 18:40:02 +000010480 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010481 return false;
10482}
John McCall4124c492011-10-17 18:40:02 +000010483
Sam Panzer0f384432012-08-21 00:52:01 +000010484/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10485/// the completed call expression. If overload resolution fails, emits
10486/// diagnostics and returns ExprError()
10487static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10488 UnresolvedLookupExpr *ULE,
10489 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010490 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010491 SourceLocation RParenLoc,
10492 Expr *ExecConfig,
10493 OverloadCandidateSet *CandidateSet,
10494 OverloadCandidateSet::iterator *Best,
10495 OverloadingResult OverloadResult,
10496 bool AllowTypoCorrection) {
10497 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010498 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010499 RParenLoc, /*EmptyLookup=*/true,
10500 AllowTypoCorrection);
10501
10502 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010503 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010504 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010505 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010506 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10507 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010508 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010509 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10510 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010511 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010512
Richard Smith998a5912011-06-05 22:42:48 +000010513 case OR_No_Viable_Function: {
10514 // Try to recover by looking for viable functions which the user might
10515 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010516 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010517 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010518 /*EmptyLookup=*/false,
10519 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010520 if (!Recovery.isInvalid())
10521 return Recovery;
10522
Sam Panzer0f384432012-08-21 00:52:01 +000010523 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010524 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010525 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010526 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010527 break;
Richard Smith998a5912011-06-05 22:42:48 +000010528 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010529
10530 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010531 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010532 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010533 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010534 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010535
Sam Panzer0f384432012-08-21 00:52:01 +000010536 case OR_Deleted: {
10537 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10538 << (*Best)->Function->isDeleted()
10539 << ULE->getName()
10540 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10541 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010542 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010543
Sam Panzer0f384432012-08-21 00:52:01 +000010544 // We emitted an error for the unvailable/deleted function call but keep
10545 // the call in the AST.
10546 FunctionDecl *FDecl = (*Best)->Function;
10547 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010548 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10549 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010550 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010551 }
10552
Douglas Gregorb412e172010-07-25 18:17:45 +000010553 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010554 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010555}
10556
Sam Panzer0f384432012-08-21 00:52:01 +000010557/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10558/// (which eventually refers to the declaration Func) and the call
10559/// arguments Args/NumArgs, attempt to resolve the function call down
10560/// to a specific function. If overload resolution succeeds, returns
10561/// the call expression produced by overload resolution.
10562/// Otherwise, emits diagnostics and returns ExprError.
10563ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10564 UnresolvedLookupExpr *ULE,
10565 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010566 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010567 SourceLocation RParenLoc,
10568 Expr *ExecConfig,
10569 bool AllowTypoCorrection) {
10570 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10571 ExprResult result;
10572
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010573 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10574 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010575 return result;
10576
10577 OverloadCandidateSet::iterator Best;
10578 OverloadingResult OverloadResult =
10579 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10580
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010581 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010582 RParenLoc, ExecConfig, &CandidateSet,
10583 &Best, OverloadResult,
10584 AllowTypoCorrection);
10585}
10586
John McCall4c4c1df2010-01-26 03:27:55 +000010587static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010588 return Functions.size() > 1 ||
10589 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10590}
10591
Douglas Gregor084d8552009-03-13 23:49:33 +000010592/// \brief Create a unary operation that may resolve to an overloaded
10593/// operator.
10594///
10595/// \param OpLoc The location of the operator itself (e.g., '*').
10596///
10597/// \param OpcIn The UnaryOperator::Opcode that describes this
10598/// operator.
10599///
James Dennett18348b62012-06-22 08:52:37 +000010600/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010601/// considered by overload resolution. The caller needs to build this
10602/// set based on the context using, e.g.,
10603/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10604/// set should not contain any member functions; those will be added
10605/// by CreateOverloadedUnaryOp().
10606///
James Dennett91738ff2012-06-22 10:32:46 +000010607/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010608ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010609Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10610 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010611 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010612 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010613
10614 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10615 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10616 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010617 // TODO: provide better source location info.
10618 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010619
John McCall4124c492011-10-17 18:40:02 +000010620 if (checkPlaceholderForOverload(*this, Input))
10621 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010622
Douglas Gregor084d8552009-03-13 23:49:33 +000010623 Expr *Args[2] = { Input, 0 };
10624 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010625
Douglas Gregor084d8552009-03-13 23:49:33 +000010626 // For post-increment and post-decrement, add the implicit '0' as
10627 // the second argument, so that we know this is a post-increment or
10628 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010629 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010630 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010631 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10632 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010633 NumArgs = 2;
10634 }
10635
Richard Smithe54c3072013-05-05 15:51:06 +000010636 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10637
Douglas Gregor084d8552009-03-13 23:49:33 +000010638 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010639 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +000010640 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010641 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +000010642 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010643 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +000010644 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010645
John McCall58cc69d2010-01-27 01:50:18 +000010646 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010647 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010648 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010649 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010650 /*ADL*/ true, IsOverloaded(Fns),
10651 Fns.begin(), Fns.end());
Richard Smithe54c3072013-05-05 15:51:06 +000010652 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregor084d8552009-03-13 23:49:33 +000010653 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010654 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010655 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010656 }
10657
10658 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010659 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010660
10661 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010662 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010663
10664 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010665 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010666
John McCall4c4c1df2010-01-26 03:27:55 +000010667 // Add candidates from ADL.
Richard Smithe54c3072013-05-05 15:51:06 +000010668 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10669 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall4c4c1df2010-01-26 03:27:55 +000010670 CandidateSet);
10671
Douglas Gregor084d8552009-03-13 23:49:33 +000010672 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010673 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010674
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010675 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10676
Douglas Gregor084d8552009-03-13 23:49:33 +000010677 // Perform overload resolution.
10678 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010679 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010680 case OR_Success: {
10681 // We found a built-in operator or an overloaded operator.
10682 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010683
Douglas Gregor084d8552009-03-13 23:49:33 +000010684 if (FnDecl) {
10685 // We matched an overloaded operator. Build a call to that
10686 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010687
Douglas Gregor084d8552009-03-13 23:49:33 +000010688 // Convert the arguments.
10689 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010690 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010691
John Wiegley01296292011-04-08 18:41:53 +000010692 ExprResult InputRes =
10693 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10694 Best->FoundDecl, Method);
10695 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010696 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010697 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010698 } else {
10699 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010700 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010701 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010702 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010703 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010704 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010705 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010706 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010707 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010708 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010709 }
10710
Douglas Gregor084d8552009-03-13 23:49:33 +000010711 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010712 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010713 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010714 if (FnExpr.isInvalid())
10715 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010716
Richard Smithc1564702013-11-15 02:58:23 +000010717 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010718 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010719 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10720 ResultTy = ResultTy.getNonLValueExprType(Context);
10721
Eli Friedman030eee42009-11-18 03:58:17 +000010722 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010723 CallExpr *TheCall =
Richard Smithe54c3072013-05-05 15:51:06 +000010724 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010725 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010726
Alp Toker314cc812014-01-25 16:55:45 +000010727 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall, FnDecl))
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010728 return ExprError();
10729
John McCallb268a282010-08-23 23:25:46 +000010730 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010731 } else {
10732 // We matched a built-in operator. Convert the arguments, then
10733 // break out so that we will build the appropriate built-in
10734 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010735 ExprResult InputRes =
10736 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10737 Best->Conversions[0], AA_Passing);
10738 if (InputRes.isInvalid())
10739 return ExprError();
10740 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010741 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010742 }
John Wiegley01296292011-04-08 18:41:53 +000010743 }
10744
10745 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010746 // This is an erroneous use of an operator which can be overloaded by
10747 // a non-member function. Check for non-member operators which were
10748 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010749 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010750 // FIXME: Recover by calling the found function.
10751 return ExprError();
10752
John Wiegley01296292011-04-08 18:41:53 +000010753 // No viable function; fall through to handling this as a
10754 // built-in operator, which will produce an error message for us.
10755 break;
10756
10757 case OR_Ambiguous:
10758 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10759 << UnaryOperator::getOpcodeStr(Opc)
10760 << Input->getType()
10761 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010762 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010763 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10764 return ExprError();
10765
10766 case OR_Deleted:
10767 Diag(OpLoc, diag::err_ovl_deleted_oper)
10768 << Best->Function->isDeleted()
10769 << UnaryOperator::getOpcodeStr(Opc)
10770 << getDeletedOrUnavailableSuffix(Best->Function)
10771 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010772 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010773 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010774 return ExprError();
10775 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010776
10777 // Either we found no viable overloaded operator or we matched a
10778 // built-in operator. In either case, fall through to trying to
10779 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010780 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010781}
10782
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010783/// \brief Create a binary operation that may resolve to an overloaded
10784/// operator.
10785///
10786/// \param OpLoc The location of the operator itself (e.g., '+').
10787///
10788/// \param OpcIn The BinaryOperator::Opcode that describes this
10789/// operator.
10790///
James Dennett18348b62012-06-22 08:52:37 +000010791/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010792/// considered by overload resolution. The caller needs to build this
10793/// set based on the context using, e.g.,
10794/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10795/// set should not contain any member functions; those will be added
10796/// by CreateOverloadedBinOp().
10797///
10798/// \param LHS Left-hand argument.
10799/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010800ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010801Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010802 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010803 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010804 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010805 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010806 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010807
10808 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10809 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10810 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10811
10812 // If either side is type-dependent, create an appropriate dependent
10813 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010814 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010815 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010816 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010817 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010818 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010819 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010820 Context.DependentTy,
10821 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010822 OpLoc,
10823 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010824
Douglas Gregor5287f092009-11-05 00:51:44 +000010825 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10826 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010827 VK_LValue,
10828 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010829 Context.DependentTy,
10830 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010831 OpLoc,
10832 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010833 }
John McCall4c4c1df2010-01-26 03:27:55 +000010834
10835 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010836 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010837 // TODO: provide better source location info in DNLoc component.
10838 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010839 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010840 = UnresolvedLookupExpr::Create(Context, NamingClass,
10841 NestedNameSpecifierLoc(), OpNameInfo,
10842 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010843 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010844 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10845 Context.DependentTy, VK_RValue,
10846 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010847 }
10848
John McCall4124c492011-10-17 18:40:02 +000010849 // Always do placeholder-like conversions on the RHS.
10850 if (checkPlaceholderForOverload(*this, Args[1]))
10851 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010852
John McCall526ab472011-10-25 17:37:35 +000010853 // Do placeholder-like conversion on the LHS; note that we should
10854 // not get here with a PseudoObject LHS.
10855 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010856 if (checkPlaceholderForOverload(*this, Args[0]))
10857 return ExprError();
10858
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010859 // If this is the assignment operator, we only perform overload resolution
10860 // if the left-hand side is a class or enumeration type. This is actually
10861 // a hack. The standard requires that we do overload resolution between the
10862 // various built-in candidates, but as DR507 points out, this can lead to
10863 // problems. So we do it this way, which pretty much follows what GCC does.
10864 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010865 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010866 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010867
John McCalle26a8722010-12-04 08:14:53 +000010868 // If this is the .* operator, which is not overloadable, just
10869 // create a built-in binary operator.
10870 if (Opc == BO_PtrMemD)
10871 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10872
Douglas Gregor084d8552009-03-13 23:49:33 +000010873 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010874 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010875
10876 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010877 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010878
10879 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010880 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010881
John McCall4c4c1df2010-01-26 03:27:55 +000010882 // Add candidates from ADL.
10883 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010884 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010885 /*ExplicitTemplateArgs*/ 0,
10886 CandidateSet);
10887
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010888 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010889 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010890
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010891 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10892
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010893 // Perform overload resolution.
10894 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010895 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010896 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010897 // We found a built-in operator or an overloaded operator.
10898 FunctionDecl *FnDecl = Best->Function;
10899
10900 if (FnDecl) {
10901 // We matched an overloaded operator. Build a call to that
10902 // operator.
10903
10904 // Convert the arguments.
10905 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010906 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010907 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010908
Chandler Carruth8e543b32010-12-12 08:17:55 +000010909 ExprResult Arg1 =
10910 PerformCopyInitialization(
10911 InitializedEntity::InitializeParameter(Context,
10912 FnDecl->getParamDecl(0)),
10913 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010914 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010915 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010916
John Wiegley01296292011-04-08 18:41:53 +000010917 ExprResult Arg0 =
10918 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10919 Best->FoundDecl, Method);
10920 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010921 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010922 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010923 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010924 } else {
10925 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010926 ExprResult Arg0 = PerformCopyInitialization(
10927 InitializedEntity::InitializeParameter(Context,
10928 FnDecl->getParamDecl(0)),
10929 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010930 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010931 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010932
Chandler Carruth8e543b32010-12-12 08:17:55 +000010933 ExprResult Arg1 =
10934 PerformCopyInitialization(
10935 InitializedEntity::InitializeParameter(Context,
10936 FnDecl->getParamDecl(1)),
10937 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010938 if (Arg1.isInvalid())
10939 return ExprError();
10940 Args[0] = LHS = Arg0.takeAs<Expr>();
10941 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010942 }
10943
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010944 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010945 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000010946 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010947 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010948 if (FnExpr.isInvalid())
10949 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010950
Richard Smithc1564702013-11-15 02:58:23 +000010951 // Determine the result type.
Alp Toker314cc812014-01-25 16:55:45 +000010952 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000010953 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10954 ResultTy = ResultTy.getNonLValueExprType(Context);
10955
John McCallb268a282010-08-23 23:25:46 +000010956 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010957 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010958 Args, ResultTy, VK, OpLoc,
10959 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010960
Alp Toker314cc812014-01-25 16:55:45 +000010961 if (CheckCallReturnType(FnDecl->getReturnType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010962 FnDecl))
10963 return ExprError();
10964
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000010965 ArrayRef<const Expr *> ArgsArray(Args, 2);
10966 // Cut off the implicit 'this'.
10967 if (isa<CXXMethodDecl>(FnDecl))
10968 ArgsArray = ArgsArray.slice(1);
10969 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10970 TheCall->getSourceRange(), VariadicDoesNotApply);
10971
John McCallb268a282010-08-23 23:25:46 +000010972 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010973 } else {
10974 // We matched a built-in operator. Convert the arguments, then
10975 // break out so that we will build the appropriate built-in
10976 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010977 ExprResult ArgsRes0 =
10978 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10979 Best->Conversions[0], AA_Passing);
10980 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010981 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010982 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010983
John Wiegley01296292011-04-08 18:41:53 +000010984 ExprResult ArgsRes1 =
10985 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10986 Best->Conversions[1], AA_Passing);
10987 if (ArgsRes1.isInvalid())
10988 return ExprError();
10989 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010990 break;
10991 }
10992 }
10993
Douglas Gregor66950a32009-09-30 21:46:01 +000010994 case OR_No_Viable_Function: {
10995 // C++ [over.match.oper]p9:
10996 // If the operator is the operator , [...] and there are no
10997 // viable functions, then the operator is assumed to be the
10998 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010999 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011000 break;
11001
Chandler Carruth8e543b32010-12-12 08:17:55 +000011002 // For class as left operand for assignment or compound assigment
11003 // operator do not fall through to handling in built-in, but report that
11004 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011005 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011006 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011007 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011008 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11009 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011010 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011011 if (Args[0]->getType()->isIncompleteType()) {
11012 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11013 << Args[0]->getType()
11014 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11015 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011016 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011017 // This is an erroneous use of an operator which can be overloaded by
11018 // a non-member function. Check for non-member operators which were
11019 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011020 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011021 // FIXME: Recover by calling the found function.
11022 return ExprError();
11023
Douglas Gregor66950a32009-09-30 21:46:01 +000011024 // No viable function; try to create a built-in operation, which will
11025 // produce an error. Then, show the non-viable candidates.
11026 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011027 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011028 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011029 "C++ binary operator overloading is missing candidates!");
11030 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011031 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011032 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011033 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011034 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011035
11036 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011037 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011038 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011039 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011040 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011041 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011042 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011043 return ExprError();
11044
11045 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011046 if (isImplicitlyDeleted(Best->Function)) {
11047 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11048 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011049 << Context.getRecordType(Method->getParent())
11050 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011051
Richard Smithde1a4872012-12-28 12:23:24 +000011052 // The user probably meant to call this special member. Just
11053 // explain why it's deleted.
11054 NoteDeletedFunction(Method);
11055 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011056 } else {
11057 Diag(OpLoc, diag::err_ovl_deleted_oper)
11058 << Best->Function->isDeleted()
11059 << BinaryOperator::getOpcodeStr(Opc)
11060 << getDeletedOrUnavailableSuffix(Best->Function)
11061 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11062 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011063 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011064 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011065 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011066 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011067
Douglas Gregor66950a32009-09-30 21:46:01 +000011068 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011069 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011070}
11071
John McCalldadc5752010-08-24 06:29:42 +000011072ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011073Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11074 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011075 Expr *Base, Expr *Idx) {
11076 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011077 DeclarationName OpName =
11078 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11079
11080 // If either side is type-dependent, create an appropriate dependent
11081 // expression.
11082 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11083
John McCall58cc69d2010-01-27 01:50:18 +000011084 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011085 // CHECKME: no 'operator' keyword?
11086 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11087 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011088 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011089 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011090 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011091 /*ADL*/ true, /*Overloaded*/ false,
11092 UnresolvedSetIterator(),
11093 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011094 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011095
Sebastian Redladba46e2009-10-29 20:17:01 +000011096 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011097 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000011098 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000011099 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000011100 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000011101 }
11102
John McCall4124c492011-10-17 18:40:02 +000011103 // Handle placeholders on both operands.
11104 if (checkPlaceholderForOverload(*this, Args[0]))
11105 return ExprError();
11106 if (checkPlaceholderForOverload(*this, Args[1]))
11107 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011108
Sebastian Redladba46e2009-10-29 20:17:01 +000011109 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000011110 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011111
11112 // Subscript can only be overloaded as a member function.
11113
11114 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011115 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011116
11117 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011118 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011119
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011120 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11121
Sebastian Redladba46e2009-10-29 20:17:01 +000011122 // Perform overload resolution.
11123 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011124 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011125 case OR_Success: {
11126 // We found a built-in operator or an overloaded operator.
11127 FunctionDecl *FnDecl = Best->Function;
11128
11129 if (FnDecl) {
11130 // We matched an overloaded operator. Build a call to that
11131 // operator.
11132
John McCalla0296f72010-03-19 07:35:19 +000011133 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011134
Sebastian Redladba46e2009-10-29 20:17:01 +000011135 // Convert the arguments.
11136 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011137 ExprResult Arg0 =
11138 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
11139 Best->FoundDecl, Method);
11140 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011141 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011142 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011143
Anders Carlssona68e51e2010-01-29 18:37:50 +000011144 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011145 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011146 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011147 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011148 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011149 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000011150 Owned(Args[1]));
11151 if (InputInit.isInvalid())
11152 return ExprError();
11153
11154 Args[1] = InputInit.takeAs<Expr>();
11155
Sebastian Redladba46e2009-10-29 20:17:01 +000011156 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011157 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11158 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011159 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011160 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011161 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011162 OpLocInfo.getLoc(),
11163 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011164 if (FnExpr.isInvalid())
11165 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011166
Richard Smithc1564702013-11-15 02:58:23 +000011167 // Determine the result type
Alp Toker314cc812014-01-25 16:55:45 +000011168 QualType ResultTy = FnDecl->getReturnType();
Richard Smithc1564702013-11-15 02:58:23 +000011169 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11170 ResultTy = ResultTy.getNonLValueExprType(Context);
11171
John McCallb268a282010-08-23 23:25:46 +000011172 CXXOperatorCallExpr *TheCall =
11173 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011174 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011175 ResultTy, VK, RLoc,
11176 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011177
Alp Toker314cc812014-01-25 16:55:45 +000011178 if (CheckCallReturnType(FnDecl->getReturnType(), LLoc, TheCall, FnDecl))
Sebastian Redladba46e2009-10-29 20:17:01 +000011179 return ExprError();
11180
John McCallb268a282010-08-23 23:25:46 +000011181 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011182 } else {
11183 // We matched a built-in operator. Convert the arguments, then
11184 // break out so that we will build the appropriate built-in
11185 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011186 ExprResult ArgsRes0 =
11187 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11188 Best->Conversions[0], AA_Passing);
11189 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011190 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011191 Args[0] = ArgsRes0.take();
11192
11193 ExprResult ArgsRes1 =
11194 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11195 Best->Conversions[1], AA_Passing);
11196 if (ArgsRes1.isInvalid())
11197 return ExprError();
11198 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011199
11200 break;
11201 }
11202 }
11203
11204 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011205 if (CandidateSet.empty())
11206 Diag(LLoc, diag::err_ovl_no_oper)
11207 << Args[0]->getType() << /*subscript*/ 0
11208 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11209 else
11210 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11211 << Args[0]->getType()
11212 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011213 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011214 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011215 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011216 }
11217
11218 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011219 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011220 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011221 << Args[0]->getType() << Args[1]->getType()
11222 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011223 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011224 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011225 return ExprError();
11226
11227 case OR_Deleted:
11228 Diag(LLoc, diag::err_ovl_deleted_oper)
11229 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011230 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011231 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011232 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011233 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011234 return ExprError();
11235 }
11236
11237 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011238 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011239}
11240
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011241/// BuildCallToMemberFunction - Build a call to a member
11242/// function. MemExpr is the expression that refers to the member
11243/// function (and includes the object parameter), Args/NumArgs are the
11244/// arguments to the function call (not including the object
11245/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011246/// expression refers to a non-static member function or an overloaded
11247/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011248ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011249Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011250 SourceLocation LParenLoc,
11251 MultiExprArg Args,
11252 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011253 assert(MemExprE->getType() == Context.BoundMemberTy ||
11254 MemExprE->getType() == Context.OverloadTy);
11255
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011256 // Dig out the member expression. This holds both the object
11257 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011258 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011259
John McCall0009fcc2011-04-26 20:42:42 +000011260 // Determine whether this is a call to a pointer-to-member function.
11261 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11262 assert(op->getType() == Context.BoundMemberTy);
11263 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11264
11265 QualType fnType =
11266 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11267
11268 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11269 QualType resultType = proto->getCallResultType(Context);
Alp Toker314cc812014-01-25 16:55:45 +000011270 ExprValueKind valueKind = Expr::getValueKindForType(proto->getReturnType());
John McCall0009fcc2011-04-26 20:42:42 +000011271
11272 // Check that the object type isn't more qualified than the
11273 // member function we're calling.
11274 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11275
11276 QualType objectType = op->getLHS()->getType();
11277 if (op->getOpcode() == BO_PtrMemI)
11278 objectType = objectType->castAs<PointerType>()->getPointeeType();
11279 Qualifiers objectQuals = objectType.getQualifiers();
11280
11281 Qualifiers difference = objectQuals - funcQuals;
11282 difference.removeObjCGCAttr();
11283 difference.removeAddressSpace();
11284 if (difference) {
11285 std::string qualsString = difference.getAsString();
11286 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11287 << fnType.getUnqualifiedType()
11288 << qualsString
11289 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11290 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011291
John McCall0009fcc2011-04-26 20:42:42 +000011292 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011293 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011294 resultType, valueKind, RParenLoc);
11295
Alp Toker314cc812014-01-25 16:55:45 +000011296 if (CheckCallReturnType(proto->getReturnType(), op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000011297 call, 0))
11298 return ExprError();
11299
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011300 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011301 return ExprError();
11302
Richard Trieu9be9c682013-06-22 02:30:38 +000011303 if (CheckOtherCall(call, proto))
11304 return ExprError();
11305
John McCall0009fcc2011-04-26 20:42:42 +000011306 return MaybeBindToTemporary(call);
11307 }
11308
John McCall4124c492011-10-17 18:40:02 +000011309 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011310 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011311 return ExprError();
11312
John McCall10eae182009-11-30 22:42:35 +000011313 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011314 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000011315 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011316 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000011317 if (isa<MemberExpr>(NakedMemExpr)) {
11318 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011319 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011320 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011321 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011322 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011323 } else {
11324 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011325 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011326
John McCall6e9f8f62009-12-03 04:06:58 +000011327 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011328 Expr::Classification ObjectClassification
11329 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11330 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011331
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011332 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000011333 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000011334
John McCall2d74de92009-12-01 22:10:20 +000011335 // FIXME: avoid copy.
11336 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11337 if (UnresExpr->hasExplicitTemplateArgs()) {
11338 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11339 TemplateArgs = &TemplateArgsBuffer;
11340 }
11341
John McCall10eae182009-11-30 22:42:35 +000011342 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11343 E = UnresExpr->decls_end(); I != E; ++I) {
11344
John McCall6e9f8f62009-12-03 04:06:58 +000011345 NamedDecl *Func = *I;
11346 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11347 if (isa<UsingShadowDecl>(Func))
11348 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11349
Douglas Gregor02824322011-01-26 19:30:28 +000011350
Francois Pichet64225792011-01-18 05:04:39 +000011351 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011352 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011353 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011354 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011355 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011356 // If explicit template arguments were provided, we can't call a
11357 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011358 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011359 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011360
John McCalla0296f72010-03-19 07:35:19 +000011361 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011362 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011363 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011364 } else {
John McCall10eae182009-11-30 22:42:35 +000011365 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011366 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011367 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011368 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011369 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011370 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011371 }
Mike Stump11289f42009-09-09 15:08:12 +000011372
John McCall10eae182009-11-30 22:42:35 +000011373 DeclarationName DeclName = UnresExpr->getMemberName();
11374
John McCall4124c492011-10-17 18:40:02 +000011375 UnbridgedCasts.restore();
11376
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011377 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011378 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011379 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011380 case OR_Success:
11381 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011382 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011383 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011384 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11385 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011386 // If FoundDecl is different from Method (such as if one is a template
11387 // and the other a specialization), make sure DiagnoseUseOfDecl is
11388 // called on both.
11389 // FIXME: This would be more comprehensively addressed by modifying
11390 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11391 // being used.
11392 if (Method != FoundDecl.getDecl() &&
11393 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11394 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011395 break;
11396
11397 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011398 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011399 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011400 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011401 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011402 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011403 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011404
11405 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011406 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011407 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011408 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011409 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011410 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011411
11412 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011413 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011414 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011415 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011416 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011417 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011418 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011419 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011420 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011421 }
11422
John McCall16df1e52010-03-30 21:47:33 +000011423 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011424
John McCall2d74de92009-12-01 22:10:20 +000011425 // If overload resolution picked a static member, build a
11426 // non-member call based on that function.
11427 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011428 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11429 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011430 }
11431
John McCall10eae182009-11-30 22:42:35 +000011432 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011433 }
11434
Alp Toker314cc812014-01-25 16:55:45 +000011435 QualType ResultType = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011436 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11437 ResultType = ResultType.getNonLValueExprType(Context);
11438
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011439 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011440 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011441 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011442 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011443
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011444 // Check for a valid return type.
Alp Toker314cc812014-01-25 16:55:45 +000011445 if (CheckCallReturnType(Method->getReturnType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011446 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011447 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011448
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011449 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011450 // We only need to do this if there was actually an overload; otherwise
11451 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011452 if (!Method->isStatic()) {
11453 ExprResult ObjectArg =
11454 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11455 FoundDecl, Method);
11456 if (ObjectArg.isInvalid())
11457 return ExprError();
11458 MemExpr->setBase(ObjectArg.take());
11459 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011460
11461 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011462 const FunctionProtoType *Proto =
11463 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011464 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011465 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011466 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011467
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011468 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011469
Richard Smith55ce3522012-06-25 20:30:08 +000011470 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011471 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011472
Anders Carlsson47061ee2011-05-06 14:25:31 +000011473 if ((isa<CXXConstructorDecl>(CurContext) ||
11474 isa<CXXDestructorDecl>(CurContext)) &&
11475 TheCall->getMethodDecl()->isPure()) {
11476 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11477
Chandler Carruth59259262011-06-27 08:31:58 +000011478 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011479 Diag(MemExpr->getLocStart(),
11480 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11481 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11482 << MD->getParent()->getDeclName();
11483
11484 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011485 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011486 }
John McCallb268a282010-08-23 23:25:46 +000011487 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011488}
11489
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011490/// BuildCallToObjectOfClassType - Build a call to an object of class
11491/// type (C++ [over.call.object]), which can end up invoking an
11492/// overloaded function call operator (@c operator()) or performing a
11493/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011494ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011495Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011496 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011497 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011498 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011499 if (checkPlaceholderForOverload(*this, Obj))
11500 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011501 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000011502
11503 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011504 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011505 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011506
John Wiegley01296292011-04-08 18:41:53 +000011507 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11508 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011509
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011510 // C++ [over.call.object]p1:
11511 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011512 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011513 // candidate functions includes at least the function call
11514 // operators of T. The function call operators of T are obtained by
11515 // ordinary lookup of the name operator() in the context of
11516 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000011517 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000011518 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011519
John Wiegley01296292011-04-08 18:41:53 +000011520 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011521 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011522 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011523
John McCall27b18f82009-11-17 02:14:36 +000011524 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11525 LookupQualifiedName(R, Record->getDecl());
11526 R.suppressDiagnostics();
11527
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011528 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011529 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011530 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011531 Object.get()->Classify(Context),
11532 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011533 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011534 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011535
Douglas Gregorab7897a2008-11-19 22:57:39 +000011536 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011537 // In addition, for each (non-explicit in C++0x) conversion function
11538 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011539 //
11540 // operator conversion-type-id () cv-qualifier;
11541 //
11542 // where cv-qualifier is the same cv-qualification as, or a
11543 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011544 // denotes the type "pointer to function of (P1,...,Pn) returning
11545 // R", or the type "reference to pointer to function of
11546 // (P1,...,Pn) returning R", or the type "reference to function
11547 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011548 // is also considered as a candidate function. Similarly,
11549 // surrogate call functions are added to the set of candidate
11550 // functions for each conversion function declared in an
11551 // accessible base class provided the function is not hidden
11552 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011553 std::pair<CXXRecordDecl::conversion_iterator,
11554 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011555 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011556 for (CXXRecordDecl::conversion_iterator
11557 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011558 NamedDecl *D = *I;
11559 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11560 if (isa<UsingShadowDecl>(D))
11561 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011562
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011563 // Skip over templated conversion functions; they aren't
11564 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011565 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011566 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011567
John McCall6e9f8f62009-12-03 04:06:58 +000011568 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011569 if (!Conv->isExplicit()) {
11570 // Strip the reference type (if any) and then the pointer type (if
11571 // any) to get down to what might be a function type.
11572 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11573 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11574 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011575
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011576 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11577 {
11578 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011579 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011580 }
11581 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011582 }
Mike Stump11289f42009-09-09 15:08:12 +000011583
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011584 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11585
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011586 // Perform overload resolution.
11587 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011588 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011589 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011590 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011591 // Overload resolution succeeded; we'll build the appropriate call
11592 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011593 break;
11594
11595 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011596 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011597 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011598 << Object.get()->getType() << /*call*/ 1
11599 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011600 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011601 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011602 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011603 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011604 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011605 break;
11606
11607 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011608 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011609 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011610 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011611 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011612 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011613
11614 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011615 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011616 diag::err_ovl_deleted_object_call)
11617 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011618 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011619 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011620 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011621 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011622 break;
Mike Stump11289f42009-09-09 15:08:12 +000011623 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011624
Douglas Gregorb412e172010-07-25 18:17:45 +000011625 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011626 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011627
John McCall4124c492011-10-17 18:40:02 +000011628 UnbridgedCasts.restore();
11629
Douglas Gregorab7897a2008-11-19 22:57:39 +000011630 if (Best->Function == 0) {
11631 // Since there is no function declaration, this is one of the
11632 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011633 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011634 = cast<CXXConversionDecl>(
11635 Best->Conversions[0].UserDefined.ConversionFunction);
11636
John Wiegley01296292011-04-08 18:41:53 +000011637 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011638 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11639 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011640 assert(Conv == Best->FoundDecl.getDecl() &&
11641 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011642 // We selected one of the surrogate functions that converts the
11643 // object parameter to a function pointer. Perform the conversion
11644 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011645
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011646 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011647 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011648 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11649 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011650 if (Call.isInvalid())
11651 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011652 // Record usage of conversion in an implicit cast.
11653 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11654 CK_UserDefinedConversion,
11655 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011656
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011657 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011658 }
11659
John Wiegley01296292011-04-08 18:41:53 +000011660 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011661
Douglas Gregorab7897a2008-11-19 22:57:39 +000011662 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11663 // that calls this method, using Object for the implicit object
11664 // parameter and passing along the remaining arguments.
11665 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011666
11667 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011668 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011669 return ExprError();
11670
Chandler Carruth8e543b32010-12-12 08:17:55 +000011671 const FunctionProtoType *Proto =
11672 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011673
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011674 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011675
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011676 DeclarationNameInfo OpLocInfo(
11677 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11678 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011679 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011680 HadMultipleCandidates,
11681 OpLocInfo.getLoc(),
11682 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011683 if (NewFn.isInvalid())
11684 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011685
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011686 // Build the full argument list for the method call (the implicit object
11687 // parameter is placed at the beginning of the list).
Ahmed Charlesaf94d562014-03-09 11:34:25 +000011688 std::unique_ptr<Expr * []> MethodArgs(new Expr *[Args.size() + 1]);
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011689 MethodArgs[0] = Object.get();
11690 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11691
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011692 // Once we've built TheCall, all of the expressions are properly
11693 // owned.
Alp Toker314cc812014-01-25 16:55:45 +000011694 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011695 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11696 ResultTy = ResultTy.getNonLValueExprType(Context);
11697
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011698 CXXOperatorCallExpr *TheCall = new (Context)
11699 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11700 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11701 ResultTy, VK, RParenLoc, false);
11702 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011703
Alp Toker314cc812014-01-25 16:55:45 +000011704 if (CheckCallReturnType(Method->getReturnType(), LParenLoc, TheCall, Method))
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011705 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011706
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011707 // We may have default arguments. If so, we need to allocate more
11708 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011709 if (Args.size() < NumParams)
11710 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011711
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011712 bool IsError = false;
11713
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011714 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011715 ExprResult ObjRes =
11716 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11717 Best->FoundDecl, Method);
11718 if (ObjRes.isInvalid())
11719 IsError = true;
11720 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011721 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011722 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011723
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011724 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011725 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011726 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011727 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011728 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011729
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011730 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011731
John McCalldadc5752010-08-24 06:29:42 +000011732 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011733 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011734 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011735 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011736 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011737
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011738 IsError |= InputInit.isInvalid();
11739 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011740 } else {
John McCalldadc5752010-08-24 06:29:42 +000011741 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011742 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11743 if (DefArg.isInvalid()) {
11744 IsError = true;
11745 break;
11746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011747
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011748 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011749 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011750
11751 TheCall->setArg(i + 1, Arg);
11752 }
11753
11754 // If this is a variadic call, handle args passed through "...".
11755 if (Proto->isVariadic()) {
11756 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011757 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011758 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11759 IsError |= Arg.isInvalid();
11760 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011761 }
11762 }
11763
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011764 if (IsError) return true;
11765
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011766 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011767
Richard Smith55ce3522012-06-25 20:30:08 +000011768 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011769 return true;
11770
John McCalle172be52010-08-24 06:09:16 +000011771 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011772}
11773
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011774/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011775/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011776/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011777ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011778Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11779 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011780 assert(Base->getType()->isRecordType() &&
11781 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011782
John McCall4124c492011-10-17 18:40:02 +000011783 if (checkPlaceholderForOverload(*this, Base))
11784 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011785
John McCallbc077cf2010-02-08 23:07:23 +000011786 SourceLocation Loc = Base->getExprLoc();
11787
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011788 // C++ [over.ref]p1:
11789 //
11790 // [...] An expression x->m is interpreted as (x.operator->())->m
11791 // for a class object x of type T if T::operator->() exists and if
11792 // the operator is selected as the best match function by the
11793 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011794 DeclarationName OpName =
11795 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011796 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011797 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011798
John McCallbc077cf2010-02-08 23:07:23 +000011799 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011800 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011801 return ExprError();
11802
John McCall27b18f82009-11-17 02:14:36 +000011803 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11804 LookupQualifiedName(R, BaseRecord->getDecl());
11805 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011806
11807 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011808 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011809 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011810 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011811 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011812
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011813 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11814
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011815 // Perform overload resolution.
11816 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011817 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011818 case OR_Success:
11819 // Overload resolution succeeded; we'll build the call below.
11820 break;
11821
11822 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011823 if (CandidateSet.empty()) {
11824 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011825 if (NoArrowOperatorFound) {
11826 // Report this specific error to the caller instead of emitting a
11827 // diagnostic, as requested.
11828 *NoArrowOperatorFound = true;
11829 return ExprError();
11830 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011831 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11832 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011833 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011834 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011835 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011836 }
11837 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011838 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011839 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011840 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011841 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011842
11843 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011844 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11845 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011846 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011847 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011848
11849 case OR_Deleted:
11850 Diag(OpLoc, diag::err_ovl_deleted_oper)
11851 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011852 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011853 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011854 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011855 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011856 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011857 }
11858
John McCalla0296f72010-03-19 07:35:19 +000011859 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11860
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011861 // Convert the object parameter.
11862 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011863 ExprResult BaseResult =
11864 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11865 Best->FoundDecl, Method);
11866 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011867 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011868 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011869
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011870 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000011871 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011872 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011873 if (FnExpr.isInvalid())
11874 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011875
Alp Toker314cc812014-01-25 16:55:45 +000011876 QualType ResultTy = Method->getReturnType();
John McCall7decc9e2010-11-18 06:31:45 +000011877 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11878 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011879 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011880 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011881 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011882
Alp Toker314cc812014-01-25 16:55:45 +000011883 if (CheckCallReturnType(Method->getReturnType(), OpLoc, TheCall, Method))
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011884 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011885
11886 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011887}
11888
Richard Smithbcc22fc2012-03-09 08:00:36 +000011889/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11890/// a literal operator described by the provided lookup results.
11891ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11892 DeclarationNameInfo &SuffixInfo,
11893 ArrayRef<Expr*> Args,
11894 SourceLocation LitEndLoc,
11895 TemplateArgumentListInfo *TemplateArgs) {
11896 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011897
Richard Smithbcc22fc2012-03-09 08:00:36 +000011898 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11899 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11900 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011901
Richard Smithbcc22fc2012-03-09 08:00:36 +000011902 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11903
Richard Smithbcc22fc2012-03-09 08:00:36 +000011904 // Perform overload resolution. This will usually be trivial, but might need
11905 // to perform substitutions for a literal operator template.
11906 OverloadCandidateSet::iterator Best;
11907 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11908 case OR_Success:
11909 case OR_Deleted:
11910 break;
11911
11912 case OR_No_Viable_Function:
11913 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11914 << R.getLookupName();
11915 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11916 return ExprError();
11917
11918 case OR_Ambiguous:
11919 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11920 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11921 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011922 }
11923
Richard Smithbcc22fc2012-03-09 08:00:36 +000011924 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000011925 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11926 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000011927 SuffixInfo.getLoc(),
11928 SuffixInfo.getInfo());
11929 if (Fn.isInvalid())
11930 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011931
11932 // Check the argument types. This should almost always be a no-op, except
11933 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011934 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000011935 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000011936 ExprResult InputInit = PerformCopyInitialization(
11937 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11938 SourceLocation(), Args[ArgIdx]);
11939 if (InputInit.isInvalid())
11940 return true;
11941 ConvArgs[ArgIdx] = InputInit.take();
11942 }
11943
Alp Toker314cc812014-01-25 16:55:45 +000011944 QualType ResultTy = FD->getReturnType();
Richard Smithc67fdd42012-03-07 08:35:16 +000011945 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11946 ResultTy = ResultTy.getNonLValueExprType(Context);
11947
Richard Smithc67fdd42012-03-07 08:35:16 +000011948 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011949 new (Context) UserDefinedLiteral(Context, Fn.take(),
11950 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011951 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11952
Alp Toker314cc812014-01-25 16:55:45 +000011953 if (CheckCallReturnType(FD->getReturnType(), UDSuffixLoc, UDL, FD))
Richard Smithc67fdd42012-03-07 08:35:16 +000011954 return ExprError();
11955
Richard Smith55ce3522012-06-25 20:30:08 +000011956 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011957 return ExprError();
11958
11959 return MaybeBindToTemporary(UDL);
11960}
11961
Sam Panzer0f384432012-08-21 00:52:01 +000011962/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11963/// given LookupResult is non-empty, it is assumed to describe a member which
11964/// will be invoked. Otherwise, the function will be found via argument
11965/// dependent lookup.
11966/// CallExpr is set to a valid expression and FRS_Success returned on success,
11967/// otherwise CallExpr is set to ExprError() and some non-success value
11968/// is returned.
11969Sema::ForRangeStatus
11970Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11971 SourceLocation RangeLoc, VarDecl *Decl,
11972 BeginEndFunction BEF,
11973 const DeclarationNameInfo &NameInfo,
11974 LookupResult &MemberLookup,
11975 OverloadCandidateSet *CandidateSet,
11976 Expr *Range, ExprResult *CallExpr) {
11977 CandidateSet->clear();
11978 if (!MemberLookup.empty()) {
11979 ExprResult MemberRef =
11980 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11981 /*IsPtr=*/false, CXXScopeSpec(),
11982 /*TemplateKWLoc=*/SourceLocation(),
11983 /*FirstQualifierInScope=*/0,
11984 MemberLookup,
11985 /*TemplateArgs=*/0);
11986 if (MemberRef.isInvalid()) {
11987 *CallExpr = ExprError();
11988 Diag(Range->getLocStart(), diag::note_in_for_range)
11989 << RangeLoc << BEF << Range->getType();
11990 return FRS_DiagnosticIssued;
11991 }
Dmitri Gribenko78852e92013-05-05 20:40:26 +000011992 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzer0f384432012-08-21 00:52:01 +000011993 if (CallExpr->isInvalid()) {
11994 *CallExpr = ExprError();
11995 Diag(Range->getLocStart(), diag::note_in_for_range)
11996 << RangeLoc << BEF << Range->getType();
11997 return FRS_DiagnosticIssued;
11998 }
11999 } else {
12000 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012001 UnresolvedLookupExpr *Fn =
12002 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
12003 NestedNameSpecifierLoc(), NameInfo,
12004 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012005 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012006
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012007 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012008 CandidateSet, CallExpr);
12009 if (CandidateSet->empty() || CandidateSetError) {
12010 *CallExpr = ExprError();
12011 return FRS_NoViableFunction;
12012 }
12013 OverloadCandidateSet::iterator Best;
12014 OverloadingResult OverloadResult =
12015 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12016
12017 if (OverloadResult == OR_No_Viable_Function) {
12018 *CallExpr = ExprError();
12019 return FRS_NoViableFunction;
12020 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012021 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzer0f384432012-08-21 00:52:01 +000012022 Loc, 0, CandidateSet, &Best,
12023 OverloadResult,
12024 /*AllowTypoCorrection=*/false);
12025 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12026 *CallExpr = ExprError();
12027 Diag(Range->getLocStart(), diag::note_in_for_range)
12028 << RangeLoc << BEF << Range->getType();
12029 return FRS_DiagnosticIssued;
12030 }
12031 }
12032 return FRS_Success;
12033}
12034
12035
Douglas Gregorcd695e52008-11-10 20:40:00 +000012036/// FixOverloadedFunctionReference - E is an expression that refers to
12037/// a C++ overloaded function (possibly with some parentheses and
12038/// perhaps a '&' around it). We have resolved the overloaded function
12039/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012040/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012041Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012042 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012043 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012044 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12045 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012046 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012047 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012048
Douglas Gregor51c538b2009-11-20 19:42:02 +000012049 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012050 }
12051
Douglas Gregor51c538b2009-11-20 19:42:02 +000012052 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012053 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12054 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012055 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012056 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012057 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012058 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012059 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012060 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012061
12062 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012063 ICE->getCastKind(),
12064 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000012065 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012066 }
12067
Douglas Gregor51c538b2009-11-20 19:42:02 +000012068 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012069 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012070 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012071 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12072 if (Method->isStatic()) {
12073 // Do nothing: static member functions aren't any different
12074 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012075 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012076 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012077 // UnresolvedLookupExpr holding an overloaded member function
12078 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012079 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12080 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012081 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012082 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012083
John McCalld14a8642009-11-21 08:51:07 +000012084 assert(isa<DeclRefExpr>(SubExpr)
12085 && "fixed to something other than a decl ref");
12086 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12087 && "fixed to a member ref with no nested name qualifier");
12088
12089 // We have taken the address of a pointer to member
12090 // function. Perform the computation here so that we get the
12091 // appropriate pointer to member type.
12092 QualType ClassType
12093 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12094 QualType MemPtrType
12095 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12096
John McCall7decc9e2010-11-18 06:31:45 +000012097 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12098 VK_RValue, OK_Ordinary,
12099 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012100 }
12101 }
John McCall16df1e52010-03-30 21:47:33 +000012102 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12103 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012104 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012105 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012106
John McCalle3027922010-08-25 11:45:40 +000012107 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012108 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012109 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012110 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012111 }
John McCalld14a8642009-11-21 08:51:07 +000012112
12113 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012114 // FIXME: avoid copy.
12115 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000012116 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012117 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12118 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012119 }
12120
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012121 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12122 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012123 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012124 Fn,
John McCall113bee02012-03-10 09:33:50 +000012125 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012126 ULE->getNameLoc(),
12127 Fn->getType(),
12128 VK_LValue,
12129 Found.getDecl(),
12130 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012131 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012132 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12133 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012134 }
12135
John McCall10eae182009-11-30 22:42:35 +000012136 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012137 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000012138 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
12139 if (MemExpr->hasExplicitTemplateArgs()) {
12140 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12141 TemplateArgs = &TemplateArgsBuffer;
12142 }
John McCall6b51f282009-11-23 01:53:49 +000012143
John McCall2d74de92009-12-01 22:10:20 +000012144 Expr *Base;
12145
John McCall7decc9e2010-11-18 06:31:45 +000012146 // If we're filling in a static method where we used to have an
12147 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012148 if (MemExpr->isImplicitAccess()) {
12149 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012150 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12151 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012152 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012153 Fn,
John McCall113bee02012-03-10 09:33:50 +000012154 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012155 MemExpr->getMemberLoc(),
12156 Fn->getType(),
12157 VK_LValue,
12158 Found.getDecl(),
12159 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012160 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012161 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12162 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012163 } else {
12164 SourceLocation Loc = MemExpr->getMemberLoc();
12165 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012166 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012167 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012168 Base = new (Context) CXXThisExpr(Loc,
12169 MemExpr->getBaseType(),
12170 /*isImplicit=*/true);
12171 }
John McCall2d74de92009-12-01 22:10:20 +000012172 } else
John McCallc3007a22010-10-26 07:05:15 +000012173 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012174
John McCall4adb38c2011-04-27 00:36:17 +000012175 ExprValueKind valueKind;
12176 QualType type;
12177 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12178 valueKind = VK_LValue;
12179 type = Fn->getType();
12180 } else {
12181 valueKind = VK_RValue;
12182 type = Context.BoundMemberTy;
12183 }
12184
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012185 MemberExpr *ME = MemberExpr::Create(Context, Base,
12186 MemExpr->isArrow(),
12187 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012188 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012189 Fn,
12190 Found,
12191 MemExpr->getMemberNameInfo(),
12192 TemplateArgs,
12193 type, valueKind, OK_Ordinary);
12194 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012195 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012196 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012197 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012198
John McCallc3007a22010-10-26 07:05:15 +000012199 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012200}
12201
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012202ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012203 DeclAccessPair Found,
12204 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000012205 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012206}
12207
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012208} // end namespace clang