blob: 7d35bcabfe2406c5805b896c6d1c538ec3f996cb [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
John McCall3d988d92009-12-02 08:47:38 +0000933 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000934 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
935 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
937 continue;
938 }
939
John McCalldaa3d6b2009-12-09 03:35:25 +0000940 Match = *I;
941 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942 }
John McCall3d988d92009-12-02 08:47:38 +0000943 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000944 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
945 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
946 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
947 continue;
948 }
949
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000950 if (!shouldLinkPossiblyHiddenDecl(*I, New))
951 continue;
952
John McCalldaa3d6b2009-12-09 03:35:25 +0000953 Match = *I;
954 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000955 }
John McCalla8987a2942010-11-10 03:01:53 +0000956 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000957 // We can overload with these, which can show up when doing
958 // redeclaration checks for UsingDecls.
959 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000960 } else if (isa<TagDecl>(OldD)) {
961 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000962 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
963 // Optimistically assume that an unresolved using decl will
964 // overload; if it doesn't, we'll have to diagnose during
965 // template instantiation.
966 } else {
John McCall1f82f242009-11-18 22:49:29 +0000967 // (C++ 13p1):
968 // Only function declarations can be overloaded; object and type
969 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000970 Match = *I;
971 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000972 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000973 }
John McCall1f82f242009-11-18 22:49:29 +0000974
John McCalldaa3d6b2009-12-09 03:35:25 +0000975 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000976}
977
Richard Smithac974a32013-06-30 09:48:50 +0000978bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
979 bool UseUsingDeclRules) {
980 // C++ [basic.start.main]p2: This function shall not be overloaded.
981 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000982 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000983
David Majnemerc729b0b2013-09-16 22:44:20 +0000984 // MSVCRT user defined entry points cannot be overloaded.
985 if (New->isMSVCRTEntryPoint())
986 return false;
987
John McCall1f82f242009-11-18 22:49:29 +0000988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
990
991 // C++ [temp.fct]p2:
992 // A function template can be overloaded with other function templates
993 // and with normal (non-template) functions.
994 if ((OldTemplate == 0) != (NewTemplate == 0))
995 return true;
996
997 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000998 QualType OldQType = Context.getCanonicalType(Old->getType());
999 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001000
1001 // Compare the signatures (C++ 1.3.10) of the two functions to
1002 // determine whether they are overloads. If we find any mismatch
1003 // in the signature, they are overloads.
1004
1005 // If either of these functions is a K&R-style function (no
1006 // prototype), then we consider them to have matching signatures.
1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1009 return false;
1010
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001011 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1012 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001013
1014 // The signature of a function includes the types of its
1015 // parameters (C++ 1.3.10), which includes the presence or absence
1016 // of the ellipsis; see C++ DR 357).
1017 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001018 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001019 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001020 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001021 return true;
1022
1023 // C++ [temp.over.link]p4:
1024 // The signature of a function template consists of its function
1025 // signature, its return type and its template parameter list. The names
1026 // of the template parameters are significant only for establishing the
1027 // relationship between the template parameters and the rest of the
1028 // signature.
1029 //
1030 // We check the return type and template parameter lists for function
1031 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001032 //
1033 // However, we don't consider either of these when deciding whether
1034 // a member introduced by a shadow declaration is hidden.
1035 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001036 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037 OldTemplate->getTemplateParameters(),
1038 false, TPL_TemplateMatch) ||
John McCall1f82f242009-11-18 22:49:29 +00001039 OldType->getResultType() != NewType->getResultType()))
1040 return true;
1041
1042 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001044 //
1045 // As part of this, also check whether one of the member functions
1046 // is static, in which case they are not overloads (C++
1047 // 13.1p2). While not part of the definition of the signature,
1048 // this check is important to determine whether these functions
1049 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001052 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001053 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055 if (!UseUsingDeclRules &&
1056 (OldMethod->getRefQualifier() == RQ_None ||
1057 NewMethod->getRefQualifier() == RQ_None)) {
1058 // C++0x [over.load]p2:
1059 // - Member function declarations with the same name and the same
1060 // parameter-type-list as well as member function template
1061 // declarations with the same name, the same parameter-type-list, and
1062 // the same template parameter lists cannot be overloaded if any of
1063 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001064 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001066 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001067 }
1068 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070
Richard Smith574f4f62013-01-14 05:37:29 +00001071 // We may not have applied the implicit const for a constexpr member
1072 // function yet (because we haven't yet resolved whether this is a static
1073 // or non-static member function). Add it now, on the assumption that this
1074 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001075 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001076 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithac974a32013-06-30 09:48:50 +00001077 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001078 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001079 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001080
1081 // We do not allow overloading based off of '__restrict'.
1082 OldQuals &= ~Qualifiers::Restrict;
1083 NewQuals &= ~Qualifiers::Restrict;
1084 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001085 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001088 // enable_if attributes are an order-sensitive part of the signature.
1089 for (specific_attr_iterator<EnableIfAttr>
1090 NewI = New->specific_attr_begin<EnableIfAttr>(),
1091 NewE = New->specific_attr_end<EnableIfAttr>(),
1092 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1093 OldE = Old->specific_attr_end<EnableIfAttr>();
1094 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1095 if (NewI == NewE || OldI == OldE)
1096 return true;
1097 llvm::FoldingSetNodeID NewID, OldID;
1098 NewI->getCond()->Profile(NewID, Context, true);
1099 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001100 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001101 return true;
1102 }
1103
John McCall1f82f242009-11-18 22:49:29 +00001104 // The signatures match; this is not an overload.
1105 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001106}
1107
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001108/// \brief Checks availability of the function depending on the current
1109/// function context. Inside an unavailable function, unavailability is ignored.
1110///
1111/// \returns true if \arg FD is unavailable and current context is inside
1112/// an available function, false otherwise.
1113bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1114 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1115}
1116
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001117/// \brief Tries a user-defined conversion from From to ToType.
1118///
1119/// Produces an implicit conversion sequence for when a standard conversion
1120/// is not an option. See TryImplicitConversion for more information.
1121static ImplicitConversionSequence
1122TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1123 bool SuppressUserConversions,
1124 bool AllowExplicit,
1125 bool InOverloadResolution,
1126 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001127 bool AllowObjCWritebackConversion,
1128 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001129 ImplicitConversionSequence ICS;
1130
1131 if (SuppressUserConversions) {
1132 // We're not in the case above, so there is no conversion that
1133 // we can perform.
1134 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1135 return ICS;
1136 }
1137
1138 // Attempt user-defined conversion.
1139 OverloadCandidateSet Conversions(From->getExprLoc());
1140 OverloadingResult UserDefResult
1141 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001142 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001143
1144 if (UserDefResult == OR_Success) {
1145 ICS.setUserDefined();
1146 // C++ [over.ics.user]p4:
1147 // A conversion of an expression of class type to the same class
1148 // type is given Exact Match rank, and a conversion of an
1149 // expression of class type to a base class of that type is
1150 // given Conversion rank, in spite of the fact that a copy
1151 // constructor (i.e., a user-defined conversion function) is
1152 // called for those cases.
1153 if (CXXConstructorDecl *Constructor
1154 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1155 QualType FromCanon
1156 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1157 QualType ToCanon
1158 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1159 if (Constructor->isCopyConstructor() &&
1160 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1161 // Turn this into a "standard" conversion sequence, so that it
1162 // gets ranked with standard conversion sequences.
1163 ICS.setStandard();
1164 ICS.Standard.setAsIdentityConversion();
1165 ICS.Standard.setFromType(From->getType());
1166 ICS.Standard.setAllToTypes(ToType);
1167 ICS.Standard.CopyConstructor = Constructor;
1168 if (ToCanon != FromCanon)
1169 ICS.Standard.Second = ICK_Derived_To_Base;
1170 }
1171 }
1172
1173 // C++ [over.best.ics]p4:
1174 // However, when considering the argument of a user-defined
1175 // conversion function that is a candidate by 13.3.1.3 when
1176 // invoked for the copying of the temporary in the second step
1177 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1178 // 13.3.1.6 in all cases, only standard conversion sequences and
1179 // ellipsis conversion sequences are allowed.
1180 if (SuppressUserConversions && ICS.isUserDefined()) {
1181 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1182 }
1183 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1184 ICS.setAmbiguous();
1185 ICS.Ambiguous.setFromType(From->getType());
1186 ICS.Ambiguous.setToType(ToType);
1187 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1188 Cand != Conversions.end(); ++Cand)
1189 if (Cand->Viable)
1190 ICS.Ambiguous.addConversion(Cand->Function);
1191 } else {
1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1193 }
1194
1195 return ICS;
1196}
1197
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001198/// TryImplicitConversion - Attempt to perform an implicit conversion
1199/// from the given expression (Expr) to the given type (ToType). This
1200/// function returns an implicit conversion sequence that can be used
1201/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001202///
1203/// void f(float f);
1204/// void g(int i) { f(i); }
1205///
1206/// this routine would produce an implicit conversion sequence to
1207/// describe the initialization of f from i, which will be a standard
1208/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1209/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1210//
1211/// Note that this routine only determines how the conversion can be
1212/// performed; it does not actually perform the conversion. As such,
1213/// it will not produce any diagnostics if no conversion is available,
1214/// but will instead return an implicit conversion sequence of kind
1215/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001216///
1217/// If @p SuppressUserConversions, then user-defined conversions are
1218/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001219/// If @p AllowExplicit, then explicit user-defined conversions are
1220/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001221///
1222/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1223/// writeback conversion, which allows __autoreleasing id* parameters to
1224/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001225static ImplicitConversionSequence
1226TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1227 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001229 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001230 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001231 bool AllowObjCWritebackConversion,
1232 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001233 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001234 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001235 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001236 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001237 return ICS;
1238 }
1239
David Blaikiebbafb8a2012-03-11 07:00:24 +00001240 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001241 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001242 return ICS;
1243 }
1244
Douglas Gregor836a7e82010-08-11 02:15:33 +00001245 // C++ [over.ics.user]p4:
1246 // A conversion of an expression of class type to the same class
1247 // type is given Exact Match rank, and a conversion of an
1248 // expression of class type to a base class of that type is
1249 // given Conversion rank, in spite of the fact that a copy/move
1250 // constructor (i.e., a user-defined conversion function) is
1251 // called for those cases.
1252 QualType FromType = From->getType();
1253 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001254 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1255 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001256 ICS.setStandard();
1257 ICS.Standard.setAsIdentityConversion();
1258 ICS.Standard.setFromType(FromType);
1259 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260
Douglas Gregor5ab11652010-04-17 22:01:05 +00001261 // We don't actually check at this point whether there is a valid
1262 // copy/move constructor, since overloading just assumes that it
1263 // exists. When we actually perform initialization, we'll find the
1264 // appropriate constructor to copy the returned object, if needed.
1265 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
Douglas Gregor5ab11652010-04-17 22:01:05 +00001267 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001268 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001269 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270
Douglas Gregor836a7e82010-08-11 02:15:33 +00001271 return ICS;
1272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001273
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001274 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1275 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001276 AllowObjCWritebackConversion,
1277 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001278}
1279
John McCall31168b02011-06-15 23:02:42 +00001280ImplicitConversionSequence
1281Sema::TryImplicitConversion(Expr *From, QualType ToType,
1282 bool SuppressUserConversions,
1283 bool AllowExplicit,
1284 bool InOverloadResolution,
1285 bool CStyle,
1286 bool AllowObjCWritebackConversion) {
1287 return clang::TryImplicitConversion(*this, From, ToType,
1288 SuppressUserConversions, AllowExplicit,
1289 InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001290 AllowObjCWritebackConversion,
1291 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001292}
1293
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001294/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001295/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001296/// converted expression. Flavor is the kind of conversion we're
1297/// performing, used in the error message. If @p AllowExplicit,
1298/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001299ExprResult
1300Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001301 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001302 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001303 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001304}
1305
John Wiegley01296292011-04-08 18:41:53 +00001306ExprResult
1307Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001308 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001309 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001310 if (checkPlaceholderForOverload(*this, From))
1311 return ExprError();
1312
John McCall31168b02011-06-15 23:02:42 +00001313 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1314 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001315 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001316 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001317 if (getLangOpts().ObjC1)
1318 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1319 ToType, From->getType(), From);
John McCall5c32be02010-08-24 20:38:10 +00001320 ICS = clang::TryImplicitConversion(*this, From, ToType,
1321 /*SuppressUserConversions=*/false,
1322 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001323 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001324 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001325 AllowObjCWritebackConversion,
1326 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001327 return PerformImplicitConversion(From, ToType, ICS, Action);
1328}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001329
1330/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001331/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001332bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1333 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001334 if (Context.hasSameUnqualifiedType(FromType, ToType))
1335 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
John McCall991eb4b2010-12-21 00:44:39 +00001337 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1338 // where F adds one of the following at most once:
1339 // - a pointer
1340 // - a member pointer
1341 // - a block pointer
1342 CanQualType CanTo = Context.getCanonicalType(ToType);
1343 CanQualType CanFrom = Context.getCanonicalType(FromType);
1344 Type::TypeClass TyClass = CanTo->getTypeClass();
1345 if (TyClass != CanFrom->getTypeClass()) return false;
1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1347 if (TyClass == Type::Pointer) {
1348 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1349 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1350 } else if (TyClass == Type::BlockPointer) {
1351 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1352 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1353 } else if (TyClass == Type::MemberPointer) {
1354 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1355 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1356 } else {
1357 return false;
1358 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001359
John McCall991eb4b2010-12-21 00:44:39 +00001360 TyClass = CanTo->getTypeClass();
1361 if (TyClass != CanFrom->getTypeClass()) return false;
1362 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1363 return false;
1364 }
1365
1366 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1367 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1368 if (!EInfo.getNoReturn()) return false;
1369
1370 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1371 assert(QualType(FromFn, 0).isCanonical());
1372 if (QualType(FromFn, 0) != CanTo) return false;
1373
1374 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001375 return true;
1376}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377
Douglas Gregor46188682010-05-18 22:42:18 +00001378/// \brief Determine whether the conversion from FromType to ToType is a valid
1379/// vector conversion.
1380///
1381/// \param ICK Will be set to the vector conversion kind, if this is a vector
1382/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1384 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001385 // We need at least one of these types to be a vector type to have a vector
1386 // conversion.
1387 if (!ToType->isVectorType() && !FromType->isVectorType())
1388 return false;
1389
1390 // Identical types require no conversions.
1391 if (Context.hasSameUnqualifiedType(FromType, ToType))
1392 return false;
1393
1394 // There are no conversions between extended vector types, only identity.
1395 if (ToType->isExtVectorType()) {
1396 // There are no conversions between extended vector types other than the
1397 // identity conversion.
1398 if (FromType->isExtVectorType())
1399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001400
Douglas Gregor46188682010-05-18 22:42:18 +00001401 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001402 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001403 ICK = ICK_Vector_Splat;
1404 return true;
1405 }
1406 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001407
1408 // We can perform the conversion between vector types in the following cases:
1409 // 1)vector types are equivalent AltiVec and GCC vector types
1410 // 2)lax vector conversions are permitted and the vector types are of the
1411 // same size
1412 if (ToType->isVectorType() && FromType->isVectorType()) {
1413 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001414 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001415 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001416 ICK = ICK_Vector_Conversion;
1417 return true;
1418 }
Douglas Gregor46188682010-05-18 22:42:18 +00001419 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001420
Douglas Gregor46188682010-05-18 22:42:18 +00001421 return false;
1422}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001424static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1425 bool InOverloadResolution,
1426 StandardConversionSequence &SCS,
1427 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001428
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001429/// IsStandardConversion - Determines whether there is a standard
1430/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1431/// expression From to the type ToType. Standard conversion sequences
1432/// only consider non-class types; for conversions that involve class
1433/// types, use TryImplicitConversion. If a conversion exists, SCS will
1434/// contain the standard conversion sequence required to perform this
1435/// conversion and this routine will return true. Otherwise, this
1436/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001437static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1438 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001439 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001440 bool CStyle,
1441 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001443
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001445 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001446 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001447 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001448 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001449
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001450 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001451 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001452 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001453 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001454 return false;
1455
Mike Stump11289f42009-09-09 15:08:12 +00001456 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001457 }
1458
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459 // The first conversion can be an lvalue-to-rvalue conversion,
1460 // array-to-pointer conversion, or function-to-pointer conversion
1461 // (C++ 4p1).
1462
John McCall5c32be02010-08-24 20:38:10 +00001463 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001464 DeclAccessPair AccessPair;
1465 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001467 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001468 // We were able to resolve the address of the overloaded function,
1469 // so we can convert to the type of that function.
1470 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001471
1472 // we can sometimes resolve &foo<int> regardless of ToType, so check
1473 // if the type matches (identity) or we are converting to bool
1474 if (!S.Context.hasSameUnqualifiedType(
1475 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1476 QualType resultTy;
1477 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001478 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001479 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1480 // otherwise, only a boolean conversion is standard
1481 if (!ToType->isBooleanType())
1482 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
Chandler Carruthffce2452011-03-29 08:08:18 +00001485 // Check if the "from" expression is taking the address of an overloaded
1486 // function and recompute the FromType accordingly. Take advantage of the
1487 // fact that non-static member functions *must* have such an address-of
1488 // expression.
1489 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1490 if (Method && !Method->isStatic()) {
1491 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1492 "Non-unary operator on non-static member address");
1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1494 == UO_AddrOf &&
1495 "Non-address-of operator on non-static member address");
1496 const Type *ClassType
1497 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1498 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001499 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1500 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1501 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001502 "Non-address-of operator for overloaded function expression");
1503 FromType = S.Context.getPointerType(FromType);
1504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001505
Douglas Gregor980fb162010-04-29 18:24:40 +00001506 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001507 assert(S.Context.hasSameType(
1508 FromType,
1509 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001510 } else {
1511 return false;
1512 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001513 }
John McCall154a2fd2011-08-30 00:57:29 +00001514 // Lvalue-to-rvalue conversion (C++11 4.1):
1515 // A glvalue (3.10) of a non-function, non-array type T can
1516 // be converted to a prvalue.
1517 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001518 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001519 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001520 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001522
Douglas Gregorc79862f2012-04-12 17:51:55 +00001523 // C11 6.3.2.1p2:
1524 // ... if the lvalue has atomic type, the value has the non-atomic version
1525 // of the type of the lvalue ...
1526 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1527 FromType = Atomic->getValueType();
1528
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529 // If T is a non-class type, the type of the rvalue is the
1530 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001531 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1532 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001534 } else if (FromType->isArrayType()) {
1535 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537
1538 // An lvalue or rvalue of type "array of N T" or "array of unknown
1539 // bound of T" can be converted to an rvalue of type "pointer to
1540 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001541 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001542
John McCall5c32be02010-08-24 20:38:10 +00001543 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001544 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001545 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001546
1547 // For the purpose of ranking in overload resolution
1548 // (13.3.3.1.1), this conversion is considered an
1549 // array-to-pointer conversion followed by a qualification
1550 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001551 SCS.Second = ICK_Identity;
1552 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001553 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001554 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 }
John McCall086a4642010-11-24 05:12:34 +00001557 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001558 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001559 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560
1561 // An lvalue of function type T can be converted to an rvalue of
1562 // type "pointer to T." The result is a pointer to the
1563 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001564 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001565 } else {
1566 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001567 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001569 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570
1571 // The second conversion can be an integral promotion, floating
1572 // point promotion, integral conversion, floating point conversion,
1573 // floating-integral conversion, pointer conversion,
1574 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001575 // For overloading in C, this can also be a "compatible-type"
1576 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001577 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001578 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001579 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580 // The unqualified versions of the types are the same: there's no
1581 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001582 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001583 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001584 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001587 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001588 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001591 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001592 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001593 SCS.Second = ICK_Complex_Promotion;
1594 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001595 } else if (ToType->isBooleanType() &&
1596 (FromType->isArithmeticType() ||
1597 FromType->isAnyPointerType() ||
1598 FromType->isBlockPointerType() ||
1599 FromType->isMemberPointerType() ||
1600 FromType->isNullPtrType())) {
1601 // Boolean conversions (C++ 4.12).
1602 SCS.Second = ICK_Boolean_Conversion;
1603 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001604 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001605 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001606 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001607 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001608 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001609 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001610 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001611 SCS.Second = ICK_Complex_Conversion;
1612 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001613 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1614 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001615 // Complex-real conversions (C99 6.3.1.7)
1616 SCS.Second = ICK_Complex_Real;
1617 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001618 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001619 // Floating point conversions (C++ 4.8).
1620 SCS.Second = ICK_Floating_Conversion;
1621 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001623 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001624 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001625 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001626 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001627 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001629 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001630 SCS.Second = ICK_Block_Pointer_Conversion;
1631 } else if (AllowObjCWritebackConversion &&
1632 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1633 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001634 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1635 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001636 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001638 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001639 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001641 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001642 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001643 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001644 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001645 SCS.Second = SecondICK;
1646 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001647 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001648 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001649 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001650 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001651 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001652 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001653 // Treat a conversion that strips "noreturn" as an identity conversion.
1654 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001655 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1656 InOverloadResolution,
1657 SCS, CStyle)) {
1658 SCS.Second = ICK_TransparentUnionConversion;
1659 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001660 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1661 CStyle)) {
1662 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001663 // appropriately.
1664 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001665 } else if (ToType->isEventT() &&
1666 From->isIntegerConstantExpr(S.getASTContext()) &&
1667 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1668 SCS.Second = ICK_Zero_Event_Conversion;
1669 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670 } else {
1671 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001674 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001676 QualType CanonFrom;
1677 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001679 bool ObjCLifetimeConversion;
1680 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1681 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001682 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001683 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001684 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001685 CanonFrom = S.Context.getCanonicalType(FromType);
1686 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687 } else {
1688 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689 SCS.Third = ICK_Identity;
1690
Mike Stump11289f42009-09-09 15:08:12 +00001691 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001692 // [...] Any difference in top-level cv-qualification is
1693 // subsumed by the initialization itself and does not constitute
1694 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001695 CanonFrom = S.Context.getCanonicalType(FromType);
1696 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001698 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001699 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001700 FromType = ToType;
1701 CanonFrom = CanonTo;
1702 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001703 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001704 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001705
1706 // If we have not converted the argument type to the parameter type,
1707 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001708 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001709 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001713
1714static bool
1715IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1716 QualType &ToType,
1717 bool InOverloadResolution,
1718 StandardConversionSequence &SCS,
1719 bool CStyle) {
1720
1721 const RecordType *UT = ToType->getAsUnionType();
1722 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1723 return false;
1724 // The field to initialize within the transparent union.
1725 RecordDecl *UD = UT->getDecl();
1726 // It's compatible if the expression matches any of the fields.
1727 for (RecordDecl::field_iterator it = UD->field_begin(),
1728 itend = UD->field_end();
1729 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001730 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1731 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001732 ToType = it->getType();
1733 return true;
1734 }
1735 }
1736 return false;
1737}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001738
1739/// IsIntegralPromotion - Determines whether the conversion from the
1740/// expression From (whose potentially-adjusted type is FromType) to
1741/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1742/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001743bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001744 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001745 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001746 if (!To) {
1747 return false;
1748 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001749
1750 // An rvalue of type char, signed char, unsigned char, short int, or
1751 // unsigned short int can be converted to an rvalue of type int if
1752 // int can represent all the values of the source type; otherwise,
1753 // the source rvalue can be converted to an rvalue of type unsigned
1754 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001755 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1756 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 if (// We can promote any signed, promotable integer type to an int
1758 (FromType->isSignedIntegerType() ||
1759 // We can promote any unsigned integer type whose size is
1760 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001761 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001762 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001763 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001764 }
1765
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001766 return To->getKind() == BuiltinType::UInt;
1767 }
1768
Richard Smithb9c5a602012-09-13 21:18:54 +00001769 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 // A prvalue of an unscoped enumeration type whose underlying type is not
1771 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1772 // following types that can represent all the values of the enumeration
1773 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1774 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001775 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001777 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778 // with lowest integer conversion rank (4.13) greater than the rank of long
1779 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001780 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001781 // C++11 [conv.prom]p4:
1782 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1783 // can be converted to a prvalue of its underlying type. Moreover, if
1784 // integral promotion can be applied to its underlying type, a prvalue of an
1785 // unscoped enumeration type whose underlying type is fixed can also be
1786 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001787 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1788 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1789 // provided for a scoped enumeration.
1790 if (FromEnumType->getDecl()->isScoped())
1791 return false;
1792
Richard Smithb9c5a602012-09-13 21:18:54 +00001793 // We can perform an integral promotion to the underlying type of the enum,
1794 // even if that's not the promoted type.
1795 if (FromEnumType->getDecl()->isFixed()) {
1796 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1797 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1798 IsIntegralPromotion(From, Underlying, ToType);
1799 }
1800
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001801 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001802 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001803 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001804 return Context.hasSameUnqualifiedType(ToType,
1805 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001806 }
John McCall56774992009-12-09 09:09:27 +00001807
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001808 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1810 // to an rvalue a prvalue of the first of the following types that can
1811 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001812 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001813 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001814 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001815 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001816 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001817 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001818 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001819 // Determine whether the type we're converting from is signed or
1820 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001821 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824 // The types we'll try to promote to, in the appropriate
1825 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001826 QualType PromoteTypes[6] = {
1827 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001828 Context.LongTy, Context.UnsignedLongTy ,
1829 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001830 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001831 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001832 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1833 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001834 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001835 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1836 // We found the type that we can promote to. If this is the
1837 // type we wanted, we have a promotion. Otherwise, no
1838 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001839 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001840 }
1841 }
1842 }
1843
1844 // An rvalue for an integral bit-field (9.6) can be converted to an
1845 // rvalue of type int if int can represent all the values of the
1846 // bit-field; otherwise, it can be converted to unsigned int if
1847 // unsigned int can represent all the values of the bit-field. If
1848 // the bit-field is larger yet, no integral promotion applies to
1849 // it. If the bit-field has an enumerated type, it is treated as any
1850 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001851 // FIXME: We should delay checking of bit-fields until we actually perform the
1852 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001853 using llvm::APSInt;
1854 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001855 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001856 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001857 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001858 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1859 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1860 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001862 // Are we promoting to an int from a bitfield that fits in an int?
1863 if (BitWidth < ToSize ||
1864 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1865 return To->getKind() == BuiltinType::Int;
1866 }
Mike Stump11289f42009-09-09 15:08:12 +00001867
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001868 // Are we promoting to an unsigned int from an unsigned bitfield
1869 // that fits into an unsigned int?
1870 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1871 return To->getKind() == BuiltinType::UInt;
1872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001874 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001875 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001876 }
Mike Stump11289f42009-09-09 15:08:12 +00001877
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001878 // An rvalue of type bool can be converted to an rvalue of type int,
1879 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001880 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001881 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001882 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001883
1884 return false;
1885}
1886
1887/// IsFloatingPointPromotion - Determines whether the conversion from
1888/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1889/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001890bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001891 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1892 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001893 /// An rvalue of type float can be converted to an rvalue of type
1894 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001895 if (FromBuiltin->getKind() == BuiltinType::Float &&
1896 ToBuiltin->getKind() == BuiltinType::Double)
1897 return true;
1898
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001899 // C99 6.3.1.5p1:
1900 // When a float is promoted to double or long double, or a
1901 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001902 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001903 (FromBuiltin->getKind() == BuiltinType::Float ||
1904 FromBuiltin->getKind() == BuiltinType::Double) &&
1905 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1906 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001907
1908 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001909 if (!getLangOpts().NativeHalfType &&
1910 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001911 ToBuiltin->getKind() == BuiltinType::Float)
1912 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001913 }
1914
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001915 return false;
1916}
1917
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001918/// \brief Determine if a conversion is a complex promotion.
1919///
1920/// A complex promotion is defined as a complex -> complex conversion
1921/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001922/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001923bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001924 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001925 if (!FromComplex)
1926 return false;
1927
John McCall9dd450b2009-09-21 23:43:11 +00001928 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001929 if (!ToComplex)
1930 return false;
1931
1932 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001933 ToComplex->getElementType()) ||
1934 IsIntegralPromotion(0, FromComplex->getElementType(),
1935 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001936}
1937
Douglas Gregor237f96c2008-11-26 23:31:11 +00001938/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1939/// the pointer type FromPtr to a pointer to type ToPointee, with the
1940/// same type qualifiers as FromPtr has on its pointee type. ToType,
1941/// if non-empty, will be a pointer to ToType that may or may not have
1942/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001943///
Mike Stump11289f42009-09-09 15:08:12 +00001944static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001945BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001946 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001947 ASTContext &Context,
1948 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001949 assert((FromPtr->getTypeClass() == Type::Pointer ||
1950 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1951 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952
John McCall31168b02011-06-15 23:02:42 +00001953 /// Conversions to 'id' subsume cv-qualifier conversions.
1954 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001955 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
1957 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001958 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001959 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001960 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001961
John McCall31168b02011-06-15 23:02:42 +00001962 if (StripObjCLifetime)
1963 Quals.removeObjCLifetime();
1964
Mike Stump11289f42009-09-09 15:08:12 +00001965 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001966 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001967 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001968 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001969 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001970
1971 // Build a pointer to ToPointee. It has the right qualifiers
1972 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001973 if (isa<ObjCObjectPointerType>(ToType))
1974 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001975 return Context.getPointerType(ToPointee);
1976 }
1977
1978 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001979 QualType QualifiedCanonToPointee
1980 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001982 if (isa<ObjCObjectPointerType>(ToType))
1983 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1984 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001985}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Mike Stump11289f42009-09-09 15:08:12 +00001987static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001988 bool InOverloadResolution,
1989 ASTContext &Context) {
1990 // Handle value-dependent integral null pointer constants correctly.
1991 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1992 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001993 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001994 return !InOverloadResolution;
1995
Douglas Gregor56751b52009-09-25 04:25:58 +00001996 return Expr->isNullPointerConstant(Context,
1997 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1998 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001999}
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002001/// IsPointerConversion - Determines whether the conversion of the
2002/// expression From, which has the (possibly adjusted) type FromType,
2003/// can be converted to the type ToType via a pointer conversion (C++
2004/// 4.10). If so, returns true and places the converted type (that
2005/// might differ from ToType in its cv-qualifiers at some level) into
2006/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002007///
Douglas Gregora29dc052008-11-27 01:19:21 +00002008/// This routine also supports conversions to and from block pointers
2009/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2010/// pointers to interfaces. FIXME: Once we've determined the
2011/// appropriate overloading rules for Objective-C, we may want to
2012/// split the Objective-C checks into a different routine; however,
2013/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002014/// conversions, so for now they live here. IncompatibleObjC will be
2015/// set if the conversion is an allowed Objective-C conversion that
2016/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002018 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002019 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002020 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002021 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002022 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2023 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002024 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002025
Mike Stump11289f42009-09-09 15:08:12 +00002026 // Conversion from a null pointer constant to any Objective-C pointer type.
2027 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002028 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002029 ConvertedType = ToType;
2030 return true;
2031 }
2032
Douglas Gregor231d1c62008-11-27 00:15:41 +00002033 // Blocks: Block pointers can be converted to void*.
2034 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002035 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002036 ConvertedType = ToType;
2037 return true;
2038 }
2039 // Blocks: A null pointer constant can be converted to a block
2040 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002041 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002042 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002043 ConvertedType = ToType;
2044 return true;
2045 }
2046
Sebastian Redl576fd422009-05-10 18:38:11 +00002047 // If the left-hand-side is nullptr_t, the right side can be a null
2048 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002049 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002050 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002051 ConvertedType = ToType;
2052 return true;
2053 }
2054
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002055 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002056 if (!ToTypePtr)
2057 return false;
2058
2059 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002060 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002061 ConvertedType = ToType;
2062 return true;
2063 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002064
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002066 // , including objective-c pointers.
2067 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002068 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002069 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002070 ConvertedType = BuildSimilarlyQualifiedPointerType(
2071 FromType->getAs<ObjCObjectPointerType>(),
2072 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002073 ToType, Context);
2074 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002075 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002077 if (!FromTypePtr)
2078 return false;
2079
2080 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002081
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002083 // pointer conversion, so don't do all of the work below.
2084 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2085 return false;
2086
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002087 // An rvalue of type "pointer to cv T," where T is an object type,
2088 // can be converted to an rvalue of type "pointer to cv void" (C++
2089 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002090 if (FromPointeeType->isIncompleteOrObjectType() &&
2091 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002092 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002093 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002094 ToType, Context,
2095 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002096 return true;
2097 }
2098
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002099 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002100 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002101 ToPointeeType->isVoidType()) {
2102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2103 ToPointeeType,
2104 ToType, Context);
2105 return true;
2106 }
2107
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002108 // When we're overloading in C, we allow a special kind of pointer
2109 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002110 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002111 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002113 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002114 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002115 return true;
2116 }
2117
Douglas Gregor5c407d92008-10-23 00:40:37 +00002118 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002119 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002120 // An rvalue of type "pointer to cv D," where D is a class type,
2121 // can be converted to an rvalue of type "pointer to cv B," where
2122 // B is a base class (clause 10) of D. If B is an inaccessible
2123 // (clause 11) or ambiguous (10.2) base class of D, a program that
2124 // necessitates this conversion is ill-formed. The result of the
2125 // conversion is a pointer to the base class sub-object of the
2126 // derived class object. The null pointer value is converted to
2127 // the null pointer value of the destination type.
2128 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002129 // Note that we do not check for ambiguity or inaccessibility
2130 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002131 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002132 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002133 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002134 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002135 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002137 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002138 ToType, Context);
2139 return true;
2140 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002141
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002142 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2143 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2144 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2145 ToPointeeType,
2146 ToType, Context);
2147 return true;
2148 }
2149
Douglas Gregora119f102008-12-19 19:13:09 +00002150 return false;
2151}
Douglas Gregoraec25842011-04-26 23:16:46 +00002152
2153/// \brief Adopt the given qualifiers for the given type.
2154static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2155 Qualifiers TQs = T.getQualifiers();
2156
2157 // Check whether qualifiers already match.
2158 if (TQs == Qs)
2159 return T;
2160
2161 if (Qs.compatiblyIncludes(TQs))
2162 return Context.getQualifiedType(T, Qs);
2163
2164 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2165}
Douglas Gregora119f102008-12-19 19:13:09 +00002166
2167/// isObjCPointerConversion - Determines whether this is an
2168/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2169/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002170bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002171 QualType& ConvertedType,
2172 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002173 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002174 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
Douglas Gregoraec25842011-04-26 23:16:46 +00002176 // The set of qualifiers on the type we're converting from.
2177 Qualifiers FromQualifiers = FromType.getQualifiers();
2178
Steve Naroff7cae42b2009-07-10 23:34:53 +00002179 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002180 const ObjCObjectPointerType* ToObjCPtr =
2181 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002182 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002183 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002184
Steve Naroff7cae42b2009-07-10 23:34:53 +00002185 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002186 // If the pointee types are the same (ignoring qualifications),
2187 // then this is not a pointer conversion.
2188 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2189 FromObjCPtr->getPointeeType()))
2190 return false;
2191
Douglas Gregoraec25842011-04-26 23:16:46 +00002192 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002193 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002194 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002195 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002196 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002197 return true;
2198 }
2199 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002200 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002201 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002202 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002203 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002204 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002205 return true;
2206 }
2207 // Objective C++: We're able to convert from a pointer to an
2208 // interface to a pointer to a different interface.
2209 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002210 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2211 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002212 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002213 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2214 FromObjCPtr->getPointeeType()))
2215 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002216 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002217 ToObjCPtr->getPointeeType(),
2218 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002219 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002220 return true;
2221 }
2222
2223 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2224 // Okay: this is some kind of implicit downcast of Objective-C
2225 // interfaces, which is permitted. However, we're going to
2226 // complain about it.
2227 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002228 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002229 ToObjCPtr->getPointeeType(),
2230 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002231 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002232 return true;
2233 }
Mike Stump11289f42009-09-09 15:08:12 +00002234 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002235 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002236 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002237 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002238 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002239 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002240 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002241 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002242 // to a block pointer type.
2243 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002245 return true;
2246 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002247 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002249 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002250 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002251 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002252 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002253 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002254 return true;
2255 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002256 else
Douglas Gregora119f102008-12-19 19:13:09 +00002257 return false;
2258
Douglas Gregor033f56d2008-12-23 00:53:59 +00002259 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002260 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002261 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002262 else if (const BlockPointerType *FromBlockPtr =
2263 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002264 FromPointeeType = FromBlockPtr->getPointeeType();
2265 else
Douglas Gregora119f102008-12-19 19:13:09 +00002266 return false;
2267
Douglas Gregora119f102008-12-19 19:13:09 +00002268 // If we have pointers to pointers, recursively check whether this
2269 // is an Objective-C conversion.
2270 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2271 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2272 IncompatibleObjC)) {
2273 // We always complain about this conversion.
2274 IncompatibleObjC = true;
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);
Douglas Gregora119f102008-12-19 19:13:09 +00002277 return true;
2278 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002279 // Allow conversion of pointee being objective-c pointer to another one;
2280 // as in I* to id.
2281 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2282 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2283 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2284 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002285
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002286 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002287 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002288 return true;
2289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290
Douglas Gregor033f56d2008-12-23 00:53:59 +00002291 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002292 // differences in the argument and result types are in Objective-C
2293 // pointer conversions. If so, we permit the conversion (but
2294 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002295 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002296 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002297 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002298 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002299 if (FromFunctionType && ToFunctionType) {
2300 // If the function types are exactly the same, this isn't an
2301 // Objective-C pointer conversion.
2302 if (Context.getCanonicalType(FromPointeeType)
2303 == Context.getCanonicalType(ToPointeeType))
2304 return false;
2305
2306 // Perform the quick checks that will tell us whether these
2307 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002308 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002309 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2310 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2311 return false;
2312
2313 bool HasObjCConversion = false;
2314 if (Context.getCanonicalType(FromFunctionType->getResultType())
2315 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2316 // Okay, the types match exactly. Nothing to do.
2317 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2318 ToFunctionType->getResultType(),
2319 ConvertedType, IncompatibleObjC)) {
2320 // Okay, we have an Objective-C pointer conversion.
2321 HasObjCConversion = true;
2322 } else {
2323 // Function types are too different. Abort.
2324 return false;
2325 }
Mike Stump11289f42009-09-09 15:08:12 +00002326
Douglas Gregora119f102008-12-19 19:13:09 +00002327 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002328 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002329 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002330 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2331 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002332 if (Context.getCanonicalType(FromArgType)
2333 == Context.getCanonicalType(ToArgType)) {
2334 // Okay, the types match exactly. Nothing to do.
2335 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2336 ConvertedType, IncompatibleObjC)) {
2337 // Okay, we have an Objective-C pointer conversion.
2338 HasObjCConversion = true;
2339 } else {
2340 // Argument types are too different. Abort.
2341 return false;
2342 }
2343 }
2344
2345 if (HasObjCConversion) {
2346 // We had an Objective-C conversion. Allow this pointer
2347 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002348 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002349 IncompatibleObjC = true;
2350 return true;
2351 }
2352 }
2353
Sebastian Redl72b597d2009-01-25 19:43:20 +00002354 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002355}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002356
John McCall31168b02011-06-15 23:02:42 +00002357/// \brief Determine whether this is an Objective-C writeback conversion,
2358/// used for parameter passing when performing automatic reference counting.
2359///
2360/// \param FromType The type we're converting form.
2361///
2362/// \param ToType The type we're converting to.
2363///
2364/// \param ConvertedType The type that will be produced after applying
2365/// this conversion.
2366bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2367 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002368 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002369 Context.hasSameUnqualifiedType(FromType, ToType))
2370 return false;
2371
2372 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2373 QualType ToPointee;
2374 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2375 ToPointee = ToPointer->getPointeeType();
2376 else
2377 return false;
2378
2379 Qualifiers ToQuals = ToPointee.getQualifiers();
2380 if (!ToPointee->isObjCLifetimeType() ||
2381 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002382 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002383 return false;
2384
2385 // Argument must be a pointer to __strong to __weak.
2386 QualType FromPointee;
2387 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2388 FromPointee = FromPointer->getPointeeType();
2389 else
2390 return false;
2391
2392 Qualifiers FromQuals = FromPointee.getQualifiers();
2393 if (!FromPointee->isObjCLifetimeType() ||
2394 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2395 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2396 return false;
2397
2398 // Make sure that we have compatible qualifiers.
2399 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2400 if (!ToQuals.compatiblyIncludes(FromQuals))
2401 return false;
2402
2403 // Remove qualifiers from the pointee type we're converting from; they
2404 // aren't used in the compatibility check belong, and we'll be adding back
2405 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2406 FromPointee = FromPointee.getUnqualifiedType();
2407
2408 // The unqualified form of the pointee types must be compatible.
2409 ToPointee = ToPointee.getUnqualifiedType();
2410 bool IncompatibleObjC;
2411 if (Context.typesAreCompatible(FromPointee, ToPointee))
2412 FromPointee = ToPointee;
2413 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2414 IncompatibleObjC))
2415 return false;
2416
2417 /// \brief Construct the type we're converting to, which is a pointer to
2418 /// __autoreleasing pointee.
2419 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2420 ConvertedType = Context.getPointerType(FromPointee);
2421 return true;
2422}
2423
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002424bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2425 QualType& ConvertedType) {
2426 QualType ToPointeeType;
2427 if (const BlockPointerType *ToBlockPtr =
2428 ToType->getAs<BlockPointerType>())
2429 ToPointeeType = ToBlockPtr->getPointeeType();
2430 else
2431 return false;
2432
2433 QualType FromPointeeType;
2434 if (const BlockPointerType *FromBlockPtr =
2435 FromType->getAs<BlockPointerType>())
2436 FromPointeeType = FromBlockPtr->getPointeeType();
2437 else
2438 return false;
2439 // We have pointer to blocks, check whether the only
2440 // differences in the argument and result types are in Objective-C
2441 // pointer conversions. If so, we permit the conversion.
2442
2443 const FunctionProtoType *FromFunctionType
2444 = FromPointeeType->getAs<FunctionProtoType>();
2445 const FunctionProtoType *ToFunctionType
2446 = ToPointeeType->getAs<FunctionProtoType>();
2447
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002448 if (!FromFunctionType || !ToFunctionType)
2449 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002450
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002451 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002452 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002453
2454 // Perform the quick checks that will tell us whether these
2455 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002456 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002457 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2458 return false;
2459
2460 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2461 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2462 if (FromEInfo != ToEInfo)
2463 return false;
2464
2465 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002466 if (Context.hasSameType(FromFunctionType->getResultType(),
2467 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002468 // Okay, the types match exactly. Nothing to do.
2469 } else {
2470 QualType RHS = FromFunctionType->getResultType();
2471 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002472 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002473 !RHS.hasQualifiers() && LHS.hasQualifiers())
2474 LHS = LHS.getUnqualifiedType();
2475
2476 if (Context.hasSameType(RHS,LHS)) {
2477 // OK exact match.
2478 } else if (isObjCPointerConversion(RHS, LHS,
2479 ConvertedType, IncompatibleObjC)) {
2480 if (IncompatibleObjC)
2481 return false;
2482 // Okay, we have an Objective-C pointer conversion.
2483 }
2484 else
2485 return false;
2486 }
2487
2488 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002489 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002490 ArgIdx != NumArgs; ++ArgIdx) {
2491 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002492 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2493 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002494 if (Context.hasSameType(FromArgType, ToArgType)) {
2495 // Okay, the types match exactly. Nothing to do.
2496 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2497 ConvertedType, IncompatibleObjC)) {
2498 if (IncompatibleObjC)
2499 return false;
2500 // Okay, we have an Objective-C pointer conversion.
2501 } else
2502 // Argument types are too different. Abort.
2503 return false;
2504 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002505 if (LangOpts.ObjCAutoRefCount &&
2506 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2507 ToFunctionType))
2508 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002509
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002510 ConvertedType = ToType;
2511 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002512}
2513
Richard Trieucaff2472011-11-23 22:32:32 +00002514enum {
2515 ft_default,
2516 ft_different_class,
2517 ft_parameter_arity,
2518 ft_parameter_mismatch,
2519 ft_return_type,
2520 ft_qualifer_mismatch
2521};
2522
2523/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2524/// function types. Catches different number of parameter, mismatch in
2525/// parameter types, and different return types.
2526void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2527 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002528 // If either type is not valid, include no extra info.
2529 if (FromType.isNull() || ToType.isNull()) {
2530 PDiag << ft_default;
2531 return;
2532 }
2533
Richard Trieucaff2472011-11-23 22:32:32 +00002534 // Get the function type from the pointers.
2535 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2536 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2537 *ToMember = ToType->getAs<MemberPointerType>();
2538 if (FromMember->getClass() != ToMember->getClass()) {
2539 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2540 << QualType(FromMember->getClass(), 0);
2541 return;
2542 }
2543 FromType = FromMember->getPointeeType();
2544 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002545 }
2546
Richard Trieu96ed5b62011-12-13 23:19:45 +00002547 if (FromType->isPointerType())
2548 FromType = FromType->getPointeeType();
2549 if (ToType->isPointerType())
2550 ToType = ToType->getPointeeType();
2551
2552 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002553 FromType = FromType.getNonReferenceType();
2554 ToType = ToType.getNonReferenceType();
2555
Richard Trieucaff2472011-11-23 22:32:32 +00002556 // Don't print extra info for non-specialized template functions.
2557 if (FromType->isInstantiationDependentType() &&
2558 !FromType->getAs<TemplateSpecializationType>()) {
2559 PDiag << ft_default;
2560 return;
2561 }
2562
Richard Trieu96ed5b62011-12-13 23:19:45 +00002563 // No extra info for same types.
2564 if (Context.hasSameType(FromType, ToType)) {
2565 PDiag << ft_default;
2566 return;
2567 }
2568
Richard Trieucaff2472011-11-23 22:32:32 +00002569 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2570 *ToFunction = ToType->getAs<FunctionProtoType>();
2571
2572 // Both types need to be function types.
2573 if (!FromFunction || !ToFunction) {
2574 PDiag << ft_default;
2575 return;
2576 }
2577
Alp Toker9cacbab2014-01-20 20:26:09 +00002578 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2579 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2580 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002581 return;
2582 }
2583
2584 // Handle different parameter types.
2585 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002586 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002587 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002588 << ToFunction->getParamType(ArgPos)
2589 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002590 return;
2591 }
2592
2593 // Handle different return type.
2594 if (!Context.hasSameType(FromFunction->getResultType(),
2595 ToFunction->getResultType())) {
2596 PDiag << ft_return_type << ToFunction->getResultType()
2597 << FromFunction->getResultType();
2598 return;
2599 }
2600
2601 unsigned FromQuals = FromFunction->getTypeQuals(),
2602 ToQuals = ToFunction->getTypeQuals();
2603 if (FromQuals != ToQuals) {
2604 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2605 return;
2606 }
2607
2608 // Unable to find a difference, so add no extra info.
2609 PDiag << ft_default;
2610}
2611
Alp Toker9cacbab2014-01-20 20:26:09 +00002612/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002613/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002614/// they have same number of arguments. If the parameters are different,
2615/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002616bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2617 const FunctionProtoType *NewType,
2618 unsigned *ArgPos) {
2619 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2620 N = NewType->param_type_begin(),
2621 E = OldType->param_type_end();
2622 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002623 if (!Context.hasSameType(O->getUnqualifiedType(),
2624 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002625 if (ArgPos)
2626 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002627 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002628 }
2629 }
2630 return true;
2631}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002632
Douglas Gregor39c16d42008-10-24 04:54:22 +00002633/// CheckPointerConversion - Check the pointer conversion from the
2634/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002635/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002636/// conversions for which IsPointerConversion has already returned
2637/// true. It returns true and produces a diagnostic if there was an
2638/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002639bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002640 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002641 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002642 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002643 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002644 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002645
John McCall8cb679e2010-11-15 09:13:47 +00002646 Kind = CK_BitCast;
2647
David Blaikie1c7c8f72012-08-08 17:33:31 +00002648 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2649 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2650 Expr::NPCK_ZeroExpression) {
2651 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2652 DiagRuntimeBehavior(From->getExprLoc(), From,
2653 PDiag(diag::warn_impcast_bool_to_null_pointer)
2654 << ToType << From->getSourceRange());
2655 else if (!isUnevaluatedContext())
2656 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2657 << ToType << From->getSourceRange();
2658 }
John McCall9320b872011-09-09 05:25:32 +00002659 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2660 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002661 QualType FromPointeeType = FromPtrType->getPointeeType(),
2662 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002663
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002664 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2665 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002666 // We must have a derived-to-base conversion. Check an
2667 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002668 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2669 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002670 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002671 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002672 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002673
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002674 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002675 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002676 }
2677 }
John McCall9320b872011-09-09 05:25:32 +00002678 } else if (const ObjCObjectPointerType *ToPtrType =
2679 ToType->getAs<ObjCObjectPointerType>()) {
2680 if (const ObjCObjectPointerType *FromPtrType =
2681 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002682 // Objective-C++ conversions are always okay.
2683 // FIXME: We should have a different class of conversions for the
2684 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002685 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002686 return false;
John McCall9320b872011-09-09 05:25:32 +00002687 } else if (FromType->isBlockPointerType()) {
2688 Kind = CK_BlockPointerToObjCPointerCast;
2689 } else {
2690 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002691 }
John McCall9320b872011-09-09 05:25:32 +00002692 } else if (ToType->isBlockPointerType()) {
2693 if (!FromType->isBlockPointerType())
2694 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002695 }
John McCall8cb679e2010-11-15 09:13:47 +00002696
2697 // We shouldn't fall into this case unless it's valid for other
2698 // reasons.
2699 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2700 Kind = CK_NullToPointer;
2701
Douglas Gregor39c16d42008-10-24 04:54:22 +00002702 return false;
2703}
2704
Sebastian Redl72b597d2009-01-25 19:43:20 +00002705/// IsMemberPointerConversion - Determines whether the conversion of the
2706/// expression From, which has the (possibly adjusted) type FromType, can be
2707/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2708/// If so, returns true and places the converted type (that might differ from
2709/// ToType in its cv-qualifiers at some level) into ConvertedType.
2710bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002711 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002712 bool InOverloadResolution,
2713 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002714 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002715 if (!ToTypePtr)
2716 return false;
2717
2718 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002719 if (From->isNullPointerConstant(Context,
2720 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2721 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002722 ConvertedType = ToType;
2723 return true;
2724 }
2725
2726 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002727 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002728 if (!FromTypePtr)
2729 return false;
2730
2731 // A pointer to member of B can be converted to a pointer to member of D,
2732 // where D is derived from B (C++ 4.11p2).
2733 QualType FromClass(FromTypePtr->getClass(), 0);
2734 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002735
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002736 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002737 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002738 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002739 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2740 ToClass.getTypePtr());
2741 return true;
2742 }
2743
2744 return false;
2745}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746
Sebastian Redl72b597d2009-01-25 19:43:20 +00002747/// CheckMemberPointerConversion - Check the member pointer conversion from the
2748/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002749/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002750/// for which IsMemberPointerConversion has already returned true. It returns
2751/// true and produces a diagnostic if there was an error, or returns false
2752/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002753bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002754 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002755 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002756 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002757 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002758 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002759 if (!FromPtrType) {
2760 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002761 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002762 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002763 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002764 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002765 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002766 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002767
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002768 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002769 assert(ToPtrType && "No member pointer cast has a target type "
2770 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002771
Sebastian Redled8f2002009-01-28 18:33:18 +00002772 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2773 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002774
Sebastian Redled8f2002009-01-28 18:33:18 +00002775 // FIXME: What about dependent types?
2776 assert(FromClass->isRecordType() && "Pointer into non-class.");
2777 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002778
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002779 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002780 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002781 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2782 assert(DerivationOkay &&
2783 "Should not have been called if derivation isn't OK.");
2784 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002785
Sebastian Redled8f2002009-01-28 18:33:18 +00002786 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2787 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002788 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2789 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2790 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2791 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002792 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002793
Douglas Gregor89ee6822009-02-28 01:32:25 +00002794 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002795 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2796 << FromClass << ToClass << QualType(VBase, 0)
2797 << From->getSourceRange();
2798 return true;
2799 }
2800
John McCall5b0829a2010-02-10 09:31:12 +00002801 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002802 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2803 Paths.front(),
2804 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002805
Anders Carlssond7923c62009-08-22 23:33:40 +00002806 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002807 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002808 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002809 return false;
2810}
2811
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002812/// Determine whether the lifetime conversion between the two given
2813/// qualifiers sets is nontrivial.
2814static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2815 Qualifiers ToQuals) {
2816 // Converting anything to const __unsafe_unretained is trivial.
2817 if (ToQuals.hasConst() &&
2818 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2819 return false;
2820
2821 return true;
2822}
2823
Douglas Gregor9a657932008-10-21 23:43:52 +00002824/// IsQualificationConversion - Determines whether the conversion from
2825/// an rvalue of type FromType to ToType is a qualification conversion
2826/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002827///
2828/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2829/// when the qualification conversion involves a change in the Objective-C
2830/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002831bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002832Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002833 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002834 FromType = Context.getCanonicalType(FromType);
2835 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002836 ObjCLifetimeConversion = false;
2837
Douglas Gregor9a657932008-10-21 23:43:52 +00002838 // If FromType and ToType are the same type, this is not a
2839 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002840 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002842
Douglas Gregor9a657932008-10-21 23:43:52 +00002843 // (C++ 4.4p4):
2844 // A conversion can add cv-qualifiers at levels other than the first
2845 // in multi-level pointers, subject to the following rules: [...]
2846 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002847 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002848 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002849 // Within each iteration of the loop, we check the qualifiers to
2850 // determine if this still looks like a qualification
2851 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002852 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002853 // until there are no more pointers or pointers-to-members left to
2854 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002855 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002856
Douglas Gregor90609aa2011-04-25 18:40:17 +00002857 Qualifiers FromQuals = FromType.getQualifiers();
2858 Qualifiers ToQuals = ToType.getQualifiers();
2859
John McCall31168b02011-06-15 23:02:42 +00002860 // Objective-C ARC:
2861 // Check Objective-C lifetime conversions.
2862 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2863 UnwrappedAnyPointer) {
2864 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002865 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2866 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002867 FromQuals.removeObjCLifetime();
2868 ToQuals.removeObjCLifetime();
2869 } else {
2870 // Qualification conversions cannot cast between different
2871 // Objective-C lifetime qualifiers.
2872 return false;
2873 }
2874 }
2875
Douglas Gregorf30053d2011-05-08 06:09:53 +00002876 // Allow addition/removal of GC attributes but not changing GC attributes.
2877 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2878 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2879 FromQuals.removeObjCGCAttr();
2880 ToQuals.removeObjCGCAttr();
2881 }
2882
Douglas Gregor9a657932008-10-21 23:43:52 +00002883 // -- for every j > 0, if const is in cv 1,j then const is in cv
2884 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002885 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002886 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002887
Douglas Gregor9a657932008-10-21 23:43:52 +00002888 // -- if the cv 1,j and cv 2,j are different, then const is in
2889 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002890 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002891 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002892 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002893
Douglas Gregor9a657932008-10-21 23:43:52 +00002894 // Keep track of whether all prior cv-qualifiers in the "to" type
2895 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002896 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002897 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002898 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002899
2900 // We are left with FromType and ToType being the pointee types
2901 // after unwrapping the original FromType and ToType the same number
2902 // of types. If we unwrapped any pointers, and if FromType and
2903 // ToType have the same unqualified type (since we checked
2904 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002905 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002906}
2907
Douglas Gregorc79862f2012-04-12 17:51:55 +00002908/// \brief - Determine whether this is a conversion from a scalar type to an
2909/// atomic type.
2910///
2911/// If successful, updates \c SCS's second and third steps in the conversion
2912/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002913static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2914 bool InOverloadResolution,
2915 StandardConversionSequence &SCS,
2916 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002917 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2918 if (!ToAtomic)
2919 return false;
2920
2921 StandardConversionSequence InnerSCS;
2922 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2923 InOverloadResolution, InnerSCS,
2924 CStyle, /*AllowObjCWritebackConversion=*/false))
2925 return false;
2926
2927 SCS.Second = InnerSCS.Second;
2928 SCS.setToType(1, InnerSCS.getToType(1));
2929 SCS.Third = InnerSCS.Third;
2930 SCS.QualificationIncludesObjCLifetime
2931 = InnerSCS.QualificationIncludesObjCLifetime;
2932 SCS.setToType(2, InnerSCS.getToType(2));
2933 return true;
2934}
2935
Sebastian Redle5417162012-03-27 18:33:03 +00002936static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2937 CXXConstructorDecl *Constructor,
2938 QualType Type) {
2939 const FunctionProtoType *CtorType =
2940 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002941 if (CtorType->getNumParams() > 0) {
2942 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002943 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2944 return true;
2945 }
2946 return false;
2947}
2948
Sebastian Redl82ace982012-02-11 23:51:08 +00002949static OverloadingResult
2950IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2951 CXXRecordDecl *To,
2952 UserDefinedConversionSequence &User,
2953 OverloadCandidateSet &CandidateSet,
2954 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002955 DeclContext::lookup_result R = S.LookupConstructors(To);
2956 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002957 Con != ConEnd; ++Con) {
2958 NamedDecl *D = *Con;
2959 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2960
2961 // Find the constructor (which may be a template).
2962 CXXConstructorDecl *Constructor = 0;
2963 FunctionTemplateDecl *ConstructorTmpl
2964 = dyn_cast<FunctionTemplateDecl>(D);
2965 if (ConstructorTmpl)
2966 Constructor
2967 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2968 else
2969 Constructor = cast<CXXConstructorDecl>(D);
2970
2971 bool Usable = !Constructor->isInvalidDecl() &&
2972 S.isInitListConstructor(Constructor) &&
2973 (AllowExplicit || !Constructor->isExplicit());
2974 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002975 // If the first argument is (a reference to) the target type,
2976 // suppress conversions.
2977 bool SuppressUserConversions =
2978 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002979 if (ConstructorTmpl)
2980 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2981 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002982 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002983 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002984 else
2985 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002986 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002987 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002988 }
2989 }
2990
2991 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2992
2993 OverloadCandidateSet::iterator Best;
2994 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2995 case OR_Success: {
2996 // Record the standard conversion we used and the conversion function.
2997 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002998 QualType ThisType = Constructor->getThisType(S.Context);
2999 // Initializer lists don't have conversions as such.
3000 User.Before.setAsIdentityConversion();
3001 User.HadMultipleCandidates = HadMultipleCandidates;
3002 User.ConversionFunction = Constructor;
3003 User.FoundConversionFunction = Best->FoundDecl;
3004 User.After.setAsIdentityConversion();
3005 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3006 User.After.setAllToTypes(ToType);
3007 return OR_Success;
3008 }
3009
3010 case OR_No_Viable_Function:
3011 return OR_No_Viable_Function;
3012 case OR_Deleted:
3013 return OR_Deleted;
3014 case OR_Ambiguous:
3015 return OR_Ambiguous;
3016 }
3017
3018 llvm_unreachable("Invalid OverloadResult!");
3019}
3020
Douglas Gregor576e98c2009-01-30 23:27:23 +00003021/// Determines whether there is a user-defined conversion sequence
3022/// (C++ [over.ics.user]) that converts expression From to the type
3023/// ToType. If such a conversion exists, User will contain the
3024/// user-defined conversion sequence that performs such a conversion
3025/// and this routine will return true. Otherwise, this routine returns
3026/// false and User is unspecified.
3027///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003028/// \param AllowExplicit true if the conversion should consider C++0x
3029/// "explicit" conversion functions as well as non-explicit conversion
3030/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003031///
3032/// \param AllowObjCConversionOnExplicit true if the conversion should
3033/// allow an extra Objective-C pointer conversion on uses of explicit
3034/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003035static OverloadingResult
3036IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003037 UserDefinedConversionSequence &User,
3038 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003039 bool AllowExplicit,
3040 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003041 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003042
Douglas Gregor5ab11652010-04-17 22:01:05 +00003043 // Whether we will only visit constructors.
3044 bool ConstructorsOnly = false;
3045
3046 // If the type we are conversion to is a class type, enumerate its
3047 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003048 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003049 // C++ [over.match.ctor]p1:
3050 // When objects of class type are direct-initialized (8.5), or
3051 // copy-initialized from an expression of the same or a
3052 // derived class type (8.5), overload resolution selects the
3053 // constructor. [...] For copy-initialization, the candidate
3054 // functions are all the converting constructors (12.3.1) of
3055 // that class. The argument list is the expression-list within
3056 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003057 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003058 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003059 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003060 ConstructorsOnly = true;
3061
Benjamin Kramer90633e32012-11-23 17:04:52 +00003062 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003063 // RequireCompleteType may have returned true due to some invalid decl
3064 // during template instantiation, but ToType may be complete enough now
3065 // to try to recover.
3066 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003067 // We're not going to find any constructors.
3068 } else if (CXXRecordDecl *ToRecordDecl
3069 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003070
3071 Expr **Args = &From;
3072 unsigned NumArgs = 1;
3073 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003074 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003075 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003076 OverloadingResult Result = IsInitializerListConstructorConversion(
3077 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3078 if (Result != OR_No_Viable_Function)
3079 return Result;
3080 // Never mind.
3081 CandidateSet.clear();
3082
3083 // If we're list-initializing, we pass the individual elements as
3084 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003085 Args = InitList->getInits();
3086 NumArgs = InitList->getNumInits();
3087 ListInitializing = true;
3088 }
3089
David Blaikieff7d47a2012-12-19 00:45:41 +00003090 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3091 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003092 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003093 NamedDecl *D = *Con;
3094 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3095
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003096 // Find the constructor (which may be a template).
3097 CXXConstructorDecl *Constructor = 0;
3098 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003099 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003100 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003101 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003102 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3103 else
John McCalla0296f72010-03-19 07:35:19 +00003104 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003105
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003106 bool Usable = !Constructor->isInvalidDecl();
3107 if (ListInitializing)
3108 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3109 else
3110 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3111 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003112 bool SuppressUserConversions = !ConstructorsOnly;
3113 if (SuppressUserConversions && ListInitializing) {
3114 SuppressUserConversions = false;
3115 if (NumArgs == 1) {
3116 // If the first argument is (a reference to) the target type,
3117 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003118 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3119 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003120 }
3121 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003122 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003123 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3124 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003125 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003126 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003127 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003128 // Allow one user-defined conversion when user specifies a
3129 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003130 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003131 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003132 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003133 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003134 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003135 }
3136 }
3137
Douglas Gregor5ab11652010-04-17 22:01:05 +00003138 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003139 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003140 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003141 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003142 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003143 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003144 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003145 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3146 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003147 std::pair<CXXRecordDecl::conversion_iterator,
3148 CXXRecordDecl::conversion_iterator>
3149 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3150 for (CXXRecordDecl::conversion_iterator
3151 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003152 DeclAccessPair FoundDecl = I.getPair();
3153 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003154 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3155 if (isa<UsingShadowDecl>(D))
3156 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3157
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003158 CXXConversionDecl *Conv;
3159 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003160 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3161 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003162 else
John McCallda4458e2010-03-31 01:36:47 +00003163 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003164
3165 if (AllowExplicit || !Conv->isExplicit()) {
3166 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003167 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3168 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003169 CandidateSet,
3170 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003171 else
John McCall5c32be02010-08-24 20:38:10 +00003172 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003173 From, ToType, CandidateSet,
3174 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003175 }
3176 }
3177 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003178 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003179
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003180 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3181
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003182 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003183 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003184 case OR_Success:
3185 // Record the standard conversion we used and the conversion function.
3186 if (CXXConstructorDecl *Constructor
3187 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3188 // C++ [over.ics.user]p1:
3189 // If the user-defined conversion is specified by a
3190 // constructor (12.3.1), the initial standard conversion
3191 // sequence converts the source type to the type required by
3192 // the argument of the constructor.
3193 //
3194 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003195 if (isa<InitListExpr>(From)) {
3196 // Initializer lists don't have conversions as such.
3197 User.Before.setAsIdentityConversion();
3198 } else {
3199 if (Best->Conversions[0].isEllipsis())
3200 User.EllipsisConversion = true;
3201 else {
3202 User.Before = Best->Conversions[0].Standard;
3203 User.EllipsisConversion = false;
3204 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003205 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003206 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003207 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003208 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003209 User.After.setAsIdentityConversion();
3210 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3211 User.After.setAllToTypes(ToType);
3212 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003213 }
3214 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003215 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3216 // C++ [over.ics.user]p1:
3217 //
3218 // [...] If the user-defined conversion is specified by a
3219 // conversion function (12.3.2), the initial standard
3220 // conversion sequence converts the source type to the
3221 // implicit object parameter of the conversion function.
3222 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003223 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003224 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003225 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003226 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003227
John McCall5c32be02010-08-24 20:38:10 +00003228 // C++ [over.ics.user]p2:
3229 // The second standard conversion sequence converts the
3230 // result of the user-defined conversion to the target type
3231 // for the sequence. Since an implicit conversion sequence
3232 // is an initialization, the special rules for
3233 // initialization by user-defined conversion apply when
3234 // selecting the best user-defined conversion for a
3235 // user-defined conversion sequence (see 13.3.3 and
3236 // 13.3.3.1).
3237 User.After = Best->FinalConversion;
3238 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003239 }
David Blaikie8a40f702012-01-17 06:56:22 +00003240 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003241
John McCall5c32be02010-08-24 20:38:10 +00003242 case OR_No_Viable_Function:
3243 return OR_No_Viable_Function;
3244 case OR_Deleted:
3245 // No conversion here! We're done.
3246 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003247
John McCall5c32be02010-08-24 20:38:10 +00003248 case OR_Ambiguous:
3249 return OR_Ambiguous;
3250 }
3251
David Blaikie8a40f702012-01-17 06:56:22 +00003252 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003253}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003255bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003256Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003257 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003258 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003260 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003261 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003262 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003263 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3264 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003265 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003266 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003267 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003268 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003269 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3270 << From->getType() << From->getSourceRange() << ToType;
3271 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003272 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003273 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003274 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003275}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003276
Douglas Gregor2837aa22012-02-22 17:32:19 +00003277/// \brief Compare the user-defined conversion functions or constructors
3278/// of two user-defined conversion sequences to determine whether any ordering
3279/// is possible.
3280static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003281compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003282 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003283 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003284 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003285
Douglas Gregor2837aa22012-02-22 17:32:19 +00003286 // Objective-C++:
3287 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003288 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003289 // respectively, always prefer the conversion to a function pointer,
3290 // because the function pointer is more lightweight and is more likely
3291 // to keep code working.
3292 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3293 if (!Conv1)
3294 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003295
Douglas Gregor2837aa22012-02-22 17:32:19 +00003296 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3297 if (!Conv2)
3298 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003299
Douglas Gregor2837aa22012-02-22 17:32:19 +00003300 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3301 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3302 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3303 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003304 return Block1 ? ImplicitConversionSequence::Worse
3305 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003306 }
3307
3308 return ImplicitConversionSequence::Indistinguishable;
3309}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003310
3311static bool hasDeprecatedStringLiteralToCharPtrConversion(
3312 const ImplicitConversionSequence &ICS) {
3313 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3314 (ICS.isUserDefined() &&
3315 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3316}
3317
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003318/// CompareImplicitConversionSequences - Compare two implicit
3319/// conversion sequences to determine whether one is better than the
3320/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003321static ImplicitConversionSequence::CompareKind
3322CompareImplicitConversionSequences(Sema &S,
3323 const ImplicitConversionSequence& ICS1,
3324 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003325{
3326 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3327 // conversion sequences (as defined in 13.3.3.1)
3328 // -- a standard conversion sequence (13.3.3.1.1) is a better
3329 // conversion sequence than a user-defined conversion sequence or
3330 // an ellipsis conversion sequence, and
3331 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3332 // conversion sequence than an ellipsis conversion sequence
3333 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003334 //
John McCall0d1da222010-01-12 00:44:57 +00003335 // C++0x [over.best.ics]p10:
3336 // For the purpose of ranking implicit conversion sequences as
3337 // described in 13.3.3.2, the ambiguous conversion sequence is
3338 // treated as a user-defined sequence that is indistinguishable
3339 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003340
3341 // String literal to 'char *' conversion has been deprecated in C++03. It has
3342 // been removed from C++11. We still accept this conversion, if it happens at
3343 // the best viable function. Otherwise, this conversion is considered worse
3344 // than ellipsis conversion. Consider this as an extension; this is not in the
3345 // standard. For example:
3346 //
3347 // int &f(...); // #1
3348 // void f(char*); // #2
3349 // void g() { int &r = f("foo"); }
3350 //
3351 // In C++03, we pick #2 as the best viable function.
3352 // In C++11, we pick #1 as the best viable function, because ellipsis
3353 // conversion is better than string-literal to char* conversion (since there
3354 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3355 // convert arguments, #2 would be the best viable function in C++11.
3356 // If the best viable function has this conversion, a warning will be issued
3357 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3358
3359 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3360 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3361 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3362 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3363 ? ImplicitConversionSequence::Worse
3364 : ImplicitConversionSequence::Better;
3365
Douglas Gregor5ab11652010-04-17 22:01:05 +00003366 if (ICS1.getKindRank() < ICS2.getKindRank())
3367 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003368 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003369 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003370
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003371 // The following checks require both conversion sequences to be of
3372 // the same kind.
3373 if (ICS1.getKind() != ICS2.getKind())
3374 return ImplicitConversionSequence::Indistinguishable;
3375
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003376 ImplicitConversionSequence::CompareKind Result =
3377 ImplicitConversionSequence::Indistinguishable;
3378
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003379 // Two implicit conversion sequences of the same form are
3380 // indistinguishable conversion sequences unless one of the
3381 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003382 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003383 Result = CompareStandardConversionSequences(S,
3384 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003385 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003386 // User-defined conversion sequence U1 is a better conversion
3387 // sequence than another user-defined conversion sequence U2 if
3388 // they contain the same user-defined conversion function or
3389 // constructor and if the second standard conversion sequence of
3390 // U1 is better than the second standard conversion sequence of
3391 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003392 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003393 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003394 Result = CompareStandardConversionSequences(S,
3395 ICS1.UserDefined.After,
3396 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003397 else
3398 Result = compareConversionFunctions(S,
3399 ICS1.UserDefined.ConversionFunction,
3400 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003401 }
3402
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003403 // List-initialization sequence L1 is a better conversion sequence than
3404 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3405 // for some X and L2 does not.
3406 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003407 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003408 if (ICS1.isStdInitializerListElement() &&
3409 !ICS2.isStdInitializerListElement())
3410 return ImplicitConversionSequence::Better;
3411 if (!ICS1.isStdInitializerListElement() &&
3412 ICS2.isStdInitializerListElement())
3413 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003414 }
3415
3416 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003417}
3418
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003419static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3420 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3421 Qualifiers Quals;
3422 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003424 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003425
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003426 return Context.hasSameUnqualifiedType(T1, T2);
3427}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003428
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003429// Per 13.3.3.2p3, compare the given standard conversion sequences to
3430// determine if one is a proper subset of the other.
3431static ImplicitConversionSequence::CompareKind
3432compareStandardConversionSubsets(ASTContext &Context,
3433 const StandardConversionSequence& SCS1,
3434 const StandardConversionSequence& SCS2) {
3435 ImplicitConversionSequence::CompareKind Result
3436 = ImplicitConversionSequence::Indistinguishable;
3437
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003439 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003440 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3441 return ImplicitConversionSequence::Better;
3442 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3443 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003445 if (SCS1.Second != SCS2.Second) {
3446 if (SCS1.Second == ICK_Identity)
3447 Result = ImplicitConversionSequence::Better;
3448 else if (SCS2.Second == ICK_Identity)
3449 Result = ImplicitConversionSequence::Worse;
3450 else
3451 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003452 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003453 return ImplicitConversionSequence::Indistinguishable;
3454
3455 if (SCS1.Third == SCS2.Third) {
3456 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3457 : ImplicitConversionSequence::Indistinguishable;
3458 }
3459
3460 if (SCS1.Third == ICK_Identity)
3461 return Result == ImplicitConversionSequence::Worse
3462 ? ImplicitConversionSequence::Indistinguishable
3463 : ImplicitConversionSequence::Better;
3464
3465 if (SCS2.Third == ICK_Identity)
3466 return Result == ImplicitConversionSequence::Better
3467 ? ImplicitConversionSequence::Indistinguishable
3468 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003470 return ImplicitConversionSequence::Indistinguishable;
3471}
3472
Douglas Gregore696ebb2011-01-26 14:52:12 +00003473/// \brief Determine whether one of the given reference bindings is better
3474/// than the other based on what kind of bindings they are.
3475static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3476 const StandardConversionSequence &SCS2) {
3477 // C++0x [over.ics.rank]p3b4:
3478 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3479 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003481 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003482 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003483 // reference*.
3484 //
3485 // FIXME: Rvalue references. We're going rogue with the above edits,
3486 // because the semantics in the current C++0x working paper (N3225 at the
3487 // time of this writing) break the standard definition of std::forward
3488 // and std::reference_wrapper when dealing with references to functions.
3489 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003490 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3491 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3492 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003493
Douglas Gregore696ebb2011-01-26 14:52:12 +00003494 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3495 SCS2.IsLvalueReference) ||
3496 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3497 !SCS2.IsLvalueReference);
3498}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003499
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003500/// CompareStandardConversionSequences - Compare two standard
3501/// conversion sequences to determine whether one is better than the
3502/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003503static ImplicitConversionSequence::CompareKind
3504CompareStandardConversionSequences(Sema &S,
3505 const StandardConversionSequence& SCS1,
3506 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003507{
3508 // Standard conversion sequence S1 is a better conversion sequence
3509 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3510
3511 // -- S1 is a proper subsequence of S2 (comparing the conversion
3512 // sequences in the canonical form defined by 13.3.3.1.1,
3513 // excluding any Lvalue Transformation; the identity conversion
3514 // sequence is considered to be a subsequence of any
3515 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003516 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003517 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003518 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003519
3520 // -- the rank of S1 is better than the rank of S2 (by the rules
3521 // defined below), or, if not that,
3522 ImplicitConversionRank Rank1 = SCS1.getRank();
3523 ImplicitConversionRank Rank2 = SCS2.getRank();
3524 if (Rank1 < Rank2)
3525 return ImplicitConversionSequence::Better;
3526 else if (Rank2 < Rank1)
3527 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003528
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003529 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3530 // are indistinguishable unless one of the following rules
3531 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003532
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003533 // A conversion that is not a conversion of a pointer, or
3534 // pointer to member, to bool is better than another conversion
3535 // that is such a conversion.
3536 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3537 return SCS2.isPointerConversionToBool()
3538 ? ImplicitConversionSequence::Better
3539 : ImplicitConversionSequence::Worse;
3540
Douglas Gregor5c407d92008-10-23 00:40:37 +00003541 // C++ [over.ics.rank]p4b2:
3542 //
3543 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003544 // conversion of B* to A* is better than conversion of B* to
3545 // void*, and conversion of A* to void* is better than conversion
3546 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003547 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003548 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003549 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003550 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003551 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3552 // Exactly one of the conversion sequences is a conversion to
3553 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003554 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3555 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003556 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3557 // Neither conversion sequence converts to a void pointer; compare
3558 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003559 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003560 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003561 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003562 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3563 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003564 // Both conversion sequences are conversions to void
3565 // pointers. Compare the source types to determine if there's an
3566 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003567 QualType FromType1 = SCS1.getFromType();
3568 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003569
3570 // Adjust the types we're converting from via the array-to-pointer
3571 // conversion, if we need to.
3572 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003573 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003574 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003575 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003576
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003577 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3578 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003579
John McCall5c32be02010-08-24 20:38:10 +00003580 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003581 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003582 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003583 return ImplicitConversionSequence::Worse;
3584
3585 // Objective-C++: If one interface is more specific than the
3586 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003587 const ObjCObjectPointerType* FromObjCPtr1
3588 = FromType1->getAs<ObjCObjectPointerType>();
3589 const ObjCObjectPointerType* FromObjCPtr2
3590 = FromType2->getAs<ObjCObjectPointerType>();
3591 if (FromObjCPtr1 && FromObjCPtr2) {
3592 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3593 FromObjCPtr2);
3594 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3595 FromObjCPtr1);
3596 if (AssignLeft != AssignRight) {
3597 return AssignLeft? ImplicitConversionSequence::Better
3598 : ImplicitConversionSequence::Worse;
3599 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003600 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003601 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003602
3603 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3604 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003605 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003606 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003607 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003608
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003609 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003610 // Check for a better reference binding based on the kind of bindings.
3611 if (isBetterReferenceBindingKind(SCS1, SCS2))
3612 return ImplicitConversionSequence::Better;
3613 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3614 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Sebastian Redlb28b4072009-03-22 23:49:27 +00003616 // C++ [over.ics.rank]p3b4:
3617 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3618 // which the references refer are the same type except for
3619 // top-level cv-qualifiers, and the type to which the reference
3620 // initialized by S2 refers is more cv-qualified than the type
3621 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003622 QualType T1 = SCS1.getToType(2);
3623 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003624 T1 = S.Context.getCanonicalType(T1);
3625 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003626 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003627 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3628 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003629 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003630 // Objective-C++ ARC: If the references refer to objects with different
3631 // lifetimes, prefer bindings that don't change lifetime.
3632 if (SCS1.ObjCLifetimeConversionBinding !=
3633 SCS2.ObjCLifetimeConversionBinding) {
3634 return SCS1.ObjCLifetimeConversionBinding
3635 ? ImplicitConversionSequence::Worse
3636 : ImplicitConversionSequence::Better;
3637 }
3638
Chandler Carruth8e543b32010-12-12 08:17:55 +00003639 // If the type is an array type, promote the element qualifiers to the
3640 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003641 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003642 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003643 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003644 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003645 if (T2.isMoreQualifiedThan(T1))
3646 return ImplicitConversionSequence::Better;
3647 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003648 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003649 }
3650 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003651
Francois Pichet08d2fa02011-09-18 21:37:37 +00003652 // In Microsoft mode, prefer an integral conversion to a
3653 // floating-to-integral conversion if the integral conversion
3654 // is between types of the same size.
3655 // For example:
3656 // void f(float);
3657 // void f(int);
3658 // int main {
3659 // long a;
3660 // f(a);
3661 // }
3662 // Here, MSVC will call f(int) instead of generating a compile error
3663 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003664 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3665 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003666 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003667 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003668 return ImplicitConversionSequence::Better;
3669
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003670 return ImplicitConversionSequence::Indistinguishable;
3671}
3672
3673/// CompareQualificationConversions - Compares two standard conversion
3674/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003675/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3676ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003677CompareQualificationConversions(Sema &S,
3678 const StandardConversionSequence& SCS1,
3679 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003680 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003681 // -- S1 and S2 differ only in their qualification conversion and
3682 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3683 // cv-qualification signature of type T1 is a proper subset of
3684 // the cv-qualification signature of type T2, and S1 is not the
3685 // deprecated string literal array-to-pointer conversion (4.2).
3686 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3687 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3688 return ImplicitConversionSequence::Indistinguishable;
3689
3690 // FIXME: the example in the standard doesn't use a qualification
3691 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003692 QualType T1 = SCS1.getToType(2);
3693 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003694 T1 = S.Context.getCanonicalType(T1);
3695 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003696 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003697 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3698 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003699
3700 // If the types are the same, we won't learn anything by unwrapped
3701 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003702 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003703 return ImplicitConversionSequence::Indistinguishable;
3704
Chandler Carruth607f38e2009-12-29 07:16:59 +00003705 // If the type is an array type, promote the element qualifiers to the type
3706 // for comparison.
3707 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003708 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003709 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003710 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003711
Mike Stump11289f42009-09-09 15:08:12 +00003712 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003713 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003714
3715 // Objective-C++ ARC:
3716 // Prefer qualification conversions not involving a change in lifetime
3717 // to qualification conversions that do not change lifetime.
3718 if (SCS1.QualificationIncludesObjCLifetime !=
3719 SCS2.QualificationIncludesObjCLifetime) {
3720 Result = SCS1.QualificationIncludesObjCLifetime
3721 ? ImplicitConversionSequence::Worse
3722 : ImplicitConversionSequence::Better;
3723 }
3724
John McCall5c32be02010-08-24 20:38:10 +00003725 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003726 // Within each iteration of the loop, we check the qualifiers to
3727 // determine if this still looks like a qualification
3728 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003729 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003730 // until there are no more pointers or pointers-to-members left
3731 // to unwrap. This essentially mimics what
3732 // IsQualificationConversion does, but here we're checking for a
3733 // strict subset of qualifiers.
3734 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3735 // The qualifiers are the same, so this doesn't tell us anything
3736 // about how the sequences rank.
3737 ;
3738 else if (T2.isMoreQualifiedThan(T1)) {
3739 // T1 has fewer qualifiers, so it could be the better sequence.
3740 if (Result == ImplicitConversionSequence::Worse)
3741 // Neither has qualifiers that are a subset of the other's
3742 // qualifiers.
3743 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003744
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003745 Result = ImplicitConversionSequence::Better;
3746 } else if (T1.isMoreQualifiedThan(T2)) {
3747 // T2 has fewer qualifiers, so it could be the better sequence.
3748 if (Result == ImplicitConversionSequence::Better)
3749 // Neither has qualifiers that are a subset of the other's
3750 // qualifiers.
3751 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003752
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003753 Result = ImplicitConversionSequence::Worse;
3754 } else {
3755 // Qualifiers are disjoint.
3756 return ImplicitConversionSequence::Indistinguishable;
3757 }
3758
3759 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003760 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003761 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003762 }
3763
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003764 // Check that the winning standard conversion sequence isn't using
3765 // the deprecated string literal array to pointer conversion.
3766 switch (Result) {
3767 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003768 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003769 Result = ImplicitConversionSequence::Indistinguishable;
3770 break;
3771
3772 case ImplicitConversionSequence::Indistinguishable:
3773 break;
3774
3775 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003776 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003777 Result = ImplicitConversionSequence::Indistinguishable;
3778 break;
3779 }
3780
3781 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003782}
3783
Douglas Gregor5c407d92008-10-23 00:40:37 +00003784/// CompareDerivedToBaseConversions - Compares two standard conversion
3785/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003786/// various kinds of derived-to-base conversions (C++
3787/// [over.ics.rank]p4b3). As part of these checks, we also look at
3788/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003789ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003790CompareDerivedToBaseConversions(Sema &S,
3791 const StandardConversionSequence& SCS1,
3792 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003793 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003794 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003795 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003796 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003797
3798 // Adjust the types we're converting from via the array-to-pointer
3799 // conversion, if we need to.
3800 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003801 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003802 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003803 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003804
3805 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003806 FromType1 = S.Context.getCanonicalType(FromType1);
3807 ToType1 = S.Context.getCanonicalType(ToType1);
3808 FromType2 = S.Context.getCanonicalType(FromType2);
3809 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003810
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003811 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003812 //
3813 // If class B is derived directly or indirectly from class A and
3814 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003815 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003816 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003817 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003818 SCS2.Second == ICK_Pointer_Conversion &&
3819 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3820 FromType1->isPointerType() && FromType2->isPointerType() &&
3821 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003822 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003823 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003824 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003825 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003826 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003827 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003828 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003829 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003830
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003831 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003832 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003833 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003834 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003835 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003836 return ImplicitConversionSequence::Worse;
3837 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003838
3839 // -- conversion of B* to A* is better than conversion of C* to A*,
3840 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003841 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003842 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003843 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003844 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003845 }
3846 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3847 SCS2.Second == ICK_Pointer_Conversion) {
3848 const ObjCObjectPointerType *FromPtr1
3849 = FromType1->getAs<ObjCObjectPointerType>();
3850 const ObjCObjectPointerType *FromPtr2
3851 = FromType2->getAs<ObjCObjectPointerType>();
3852 const ObjCObjectPointerType *ToPtr1
3853 = ToType1->getAs<ObjCObjectPointerType>();
3854 const ObjCObjectPointerType *ToPtr2
3855 = ToType2->getAs<ObjCObjectPointerType>();
3856
3857 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3858 // Apply the same conversion ranking rules for Objective-C pointer types
3859 // that we do for C++ pointers to class types. However, we employ the
3860 // Objective-C pseudo-subtyping relationship used for assignment of
3861 // Objective-C pointer types.
3862 bool FromAssignLeft
3863 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3864 bool FromAssignRight
3865 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3866 bool ToAssignLeft
3867 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3868 bool ToAssignRight
3869 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3870
3871 // A conversion to an a non-id object pointer type or qualified 'id'
3872 // type is better than a conversion to 'id'.
3873 if (ToPtr1->isObjCIdType() &&
3874 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3875 return ImplicitConversionSequence::Worse;
3876 if (ToPtr2->isObjCIdType() &&
3877 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3878 return ImplicitConversionSequence::Better;
3879
3880 // A conversion to a non-id object pointer type is better than a
3881 // conversion to a qualified 'id' type
3882 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3883 return ImplicitConversionSequence::Worse;
3884 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3885 return ImplicitConversionSequence::Better;
3886
3887 // A conversion to an a non-Class object pointer type or qualified 'Class'
3888 // type is better than a conversion to 'Class'.
3889 if (ToPtr1->isObjCClassType() &&
3890 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3891 return ImplicitConversionSequence::Worse;
3892 if (ToPtr2->isObjCClassType() &&
3893 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3894 return ImplicitConversionSequence::Better;
3895
3896 // A conversion to a non-Class object pointer type is better than a
3897 // conversion to a qualified 'Class' type.
3898 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3899 return ImplicitConversionSequence::Worse;
3900 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3901 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003902
Douglas Gregor058d3de2011-01-31 18:51:41 +00003903 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3904 if (S.Context.hasSameType(FromType1, FromType2) &&
3905 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3906 (ToAssignLeft != ToAssignRight))
3907 return ToAssignLeft? ImplicitConversionSequence::Worse
3908 : ImplicitConversionSequence::Better;
3909
3910 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3911 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3912 (FromAssignLeft != FromAssignRight))
3913 return FromAssignLeft? ImplicitConversionSequence::Better
3914 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003915 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003916 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003917
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003918 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003919 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3920 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3921 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003923 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003925 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003927 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003928 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003929 ToType2->getAs<MemberPointerType>();
3930 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3931 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3932 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3933 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3934 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3935 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3936 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3937 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003938 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003939 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003940 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003941 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003942 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003943 return ImplicitConversionSequence::Better;
3944 }
3945 // conversion of B::* to C::* is better than conversion of A::* to C::*
3946 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003947 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003948 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003949 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003950 return ImplicitConversionSequence::Worse;
3951 }
3952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003953
Douglas Gregor5ab11652010-04-17 22:01:05 +00003954 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003955 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003956 // -- binding of an expression of type C to a reference of type
3957 // B& is better than binding an expression of type C to a
3958 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003959 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3960 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3961 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003962 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003963 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003964 return ImplicitConversionSequence::Worse;
3965 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003966
Douglas Gregor2fe98832008-11-03 19:09:14 +00003967 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003968 // -- binding of an expression of type B to a reference of type
3969 // A& is better than binding an expression of type C to a
3970 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003971 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3972 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3973 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003974 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003975 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003976 return ImplicitConversionSequence::Worse;
3977 }
3978 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003979
Douglas Gregor5c407d92008-10-23 00:40:37 +00003980 return ImplicitConversionSequence::Indistinguishable;
3981}
3982
Douglas Gregor45bb4832013-03-26 23:36:30 +00003983/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3984/// C++ class.
3985static bool isTypeValid(QualType T) {
3986 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3987 return !Record->isInvalidDecl();
3988
3989 return true;
3990}
3991
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003992/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3993/// determine whether they are reference-related,
3994/// reference-compatible, reference-compatible with added
3995/// qualification, or incompatible, for use in C++ initialization by
3996/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3997/// type, and the first type (T1) is the pointee type of the reference
3998/// type being initialized.
3999Sema::ReferenceCompareResult
4000Sema::CompareReferenceRelationship(SourceLocation Loc,
4001 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004002 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004003 bool &ObjCConversion,
4004 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004005 assert(!OrigT1->isReferenceType() &&
4006 "T1 must be the pointee type of the reference type");
4007 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4008
4009 QualType T1 = Context.getCanonicalType(OrigT1);
4010 QualType T2 = Context.getCanonicalType(OrigT2);
4011 Qualifiers T1Quals, T2Quals;
4012 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4013 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4014
4015 // C++ [dcl.init.ref]p4:
4016 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4017 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4018 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004019 DerivedToBase = false;
4020 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004021 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004022 if (UnqualT1 == UnqualT2) {
4023 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004024 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004025 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4026 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004027 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004028 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4029 UnqualT2->isObjCObjectOrInterfaceType() &&
4030 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4031 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004032 else
4033 return Ref_Incompatible;
4034
4035 // At this point, we know that T1 and T2 are reference-related (at
4036 // least).
4037
4038 // If the type is an array type, promote the element qualifiers to the type
4039 // for comparison.
4040 if (isa<ArrayType>(T1) && T1Quals)
4041 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4042 if (isa<ArrayType>(T2) && T2Quals)
4043 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4044
4045 // C++ [dcl.init.ref]p4:
4046 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4047 // reference-related to T2 and cv1 is the same cv-qualification
4048 // as, or greater cv-qualification than, cv2. For purposes of
4049 // overload resolution, cases for which cv1 is greater
4050 // cv-qualification than cv2 are identified as
4051 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004052 //
4053 // Note that we also require equivalence of Objective-C GC and address-space
4054 // qualifiers when performing these computations, so that e.g., an int in
4055 // address space 1 is not reference-compatible with an int in address
4056 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004057 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4058 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004059 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4060 ObjCLifetimeConversion = true;
4061
John McCall31168b02011-06-15 23:02:42 +00004062 T1Quals.removeObjCLifetime();
4063 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004064 }
4065
Douglas Gregord517d552011-04-28 17:56:11 +00004066 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004067 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004068 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004069 return Ref_Compatible_With_Added_Qualification;
4070 else
4071 return Ref_Related;
4072}
4073
Douglas Gregor836a7e82010-08-11 02:15:33 +00004074/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004075/// with DeclType. Return true if something definite is found.
4076static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004077FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4078 QualType DeclType, SourceLocation DeclLoc,
4079 Expr *Init, QualType T2, bool AllowRvalues,
4080 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004081 assert(T2->isRecordType() && "Can only find conversions of record types.");
4082 CXXRecordDecl *T2RecordDecl
4083 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4084
4085 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004086 std::pair<CXXRecordDecl::conversion_iterator,
4087 CXXRecordDecl::conversion_iterator>
4088 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4089 for (CXXRecordDecl::conversion_iterator
4090 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004091 NamedDecl *D = *I;
4092 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4093 if (isa<UsingShadowDecl>(D))
4094 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4095
4096 FunctionTemplateDecl *ConvTemplate
4097 = dyn_cast<FunctionTemplateDecl>(D);
4098 CXXConversionDecl *Conv;
4099 if (ConvTemplate)
4100 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4101 else
4102 Conv = cast<CXXConversionDecl>(D);
4103
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004104 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004105 // explicit conversions, skip it.
4106 if (!AllowExplicit && Conv->isExplicit())
4107 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Douglas Gregor836a7e82010-08-11 02:15:33 +00004109 if (AllowRvalues) {
4110 bool DerivedToBase = false;
4111 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004112 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004113
4114 // If we are initializing an rvalue reference, don't permit conversion
4115 // functions that return lvalues.
4116 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4117 const ReferenceType *RefType
4118 = Conv->getConversionType()->getAs<LValueReferenceType>();
4119 if (RefType && !RefType->getPointeeType()->isFunctionType())
4120 continue;
4121 }
4122
Douglas Gregor836a7e82010-08-11 02:15:33 +00004123 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004124 S.CompareReferenceRelationship(
4125 DeclLoc,
4126 Conv->getConversionType().getNonReferenceType()
4127 .getUnqualifiedType(),
4128 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004129 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004130 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004131 continue;
4132 } else {
4133 // If the conversion function doesn't return a reference type,
4134 // it can't be considered for this conversion. An rvalue reference
4135 // is only acceptable if its referencee is a function type.
4136
4137 const ReferenceType *RefType =
4138 Conv->getConversionType()->getAs<ReferenceType>();
4139 if (!RefType ||
4140 (!RefType->isLValueReferenceType() &&
4141 !RefType->getPointeeType()->isFunctionType()))
4142 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144
Douglas Gregor836a7e82010-08-11 02:15:33 +00004145 if (ConvTemplate)
4146 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004147 Init, DeclType, CandidateSet,
4148 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004149 else
4150 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004151 DeclType, CandidateSet,
4152 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004153 }
4154
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004155 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4156
Sebastian Redld92badf2010-06-30 18:13:39 +00004157 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004158 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004159 case OR_Success:
4160 // C++ [over.ics.ref]p1:
4161 //
4162 // [...] If the parameter binds directly to the result of
4163 // applying a conversion function to the argument
4164 // expression, the implicit conversion sequence is a
4165 // user-defined conversion sequence (13.3.3.1.2), with the
4166 // second standard conversion sequence either an identity
4167 // conversion or, if the conversion function returns an
4168 // entity of a type that is a derived class of the parameter
4169 // type, a derived-to-base Conversion.
4170 if (!Best->FinalConversion.DirectBinding)
4171 return false;
4172
4173 ICS.setUserDefined();
4174 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4175 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004176 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004177 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004178 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004179 ICS.UserDefined.EllipsisConversion = false;
4180 assert(ICS.UserDefined.After.ReferenceBinding &&
4181 ICS.UserDefined.After.DirectBinding &&
4182 "Expected a direct reference binding!");
4183 return true;
4184
4185 case OR_Ambiguous:
4186 ICS.setAmbiguous();
4187 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4188 Cand != CandidateSet.end(); ++Cand)
4189 if (Cand->Viable)
4190 ICS.Ambiguous.addConversion(Cand->Function);
4191 return true;
4192
4193 case OR_No_Viable_Function:
4194 case OR_Deleted:
4195 // There was no suitable conversion, or we found a deleted
4196 // conversion; continue with other checks.
4197 return false;
4198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004199
David Blaikie8a40f702012-01-17 06:56:22 +00004200 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004201}
4202
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004203/// \brief Compute an implicit conversion sequence for reference
4204/// initialization.
4205static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004206TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004207 SourceLocation DeclLoc,
4208 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004209 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004210 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4211
4212 // Most paths end in a failed conversion.
4213 ImplicitConversionSequence ICS;
4214 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4215
4216 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4217 QualType T2 = Init->getType();
4218
4219 // If the initializer is the address of an overloaded function, try
4220 // to resolve the overloaded function. If all goes well, T2 is the
4221 // type of the resulting function.
4222 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4223 DeclAccessPair Found;
4224 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4225 false, Found))
4226 T2 = Fn->getType();
4227 }
4228
4229 // Compute some basic properties of the types and the initializer.
4230 bool isRValRef = DeclType->isRValueReferenceType();
4231 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004232 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004233 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004234 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004235 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004236 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004237 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004238
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004239
Sebastian Redld92badf2010-06-30 18:13:39 +00004240 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004241 // A reference to type "cv1 T1" is initialized by an expression
4242 // of type "cv2 T2" as follows:
4243
Sebastian Redld92badf2010-06-30 18:13:39 +00004244 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004245 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004246 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4247 // reference-compatible with "cv2 T2," or
4248 //
4249 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4250 if (InitCategory.isLValue() &&
4251 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004252 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004253 // When a parameter of reference type binds directly (8.5.3)
4254 // to an argument expression, the implicit conversion sequence
4255 // is the identity conversion, unless the argument expression
4256 // has a type that is a derived class of the parameter type,
4257 // in which case the implicit conversion sequence is a
4258 // derived-to-base Conversion (13.3.3.1).
4259 ICS.setStandard();
4260 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004261 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4262 : ObjCConversion? ICK_Compatible_Conversion
4263 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004264 ICS.Standard.Third = ICK_Identity;
4265 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4266 ICS.Standard.setToType(0, T2);
4267 ICS.Standard.setToType(1, T1);
4268 ICS.Standard.setToType(2, T1);
4269 ICS.Standard.ReferenceBinding = true;
4270 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004271 ICS.Standard.IsLvalueReference = !isRValRef;
4272 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4273 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004274 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004275 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004276 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004277 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004278
Sebastian Redld92badf2010-06-30 18:13:39 +00004279 // Nothing more to do: the inaccessibility/ambiguity check for
4280 // derived-to-base conversions is suppressed when we're
4281 // computing the implicit conversion sequence (C++
4282 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004283 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004284 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004285
Sebastian Redld92badf2010-06-30 18:13:39 +00004286 // -- has a class type (i.e., T2 is a class type), where T1 is
4287 // not reference-related to T2, and can be implicitly
4288 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4289 // is reference-compatible with "cv3 T3" 92) (this
4290 // conversion is selected by enumerating the applicable
4291 // conversion functions (13.3.1.6) and choosing the best
4292 // one through overload resolution (13.3)),
4293 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004295 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004296 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4297 Init, T2, /*AllowRvalues=*/false,
4298 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004299 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004300 }
4301 }
4302
Sebastian Redld92badf2010-06-30 18:13:39 +00004303 // -- Otherwise, the reference shall be an lvalue reference to a
4304 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004305 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004307 // We actually handle one oddity of C++ [over.ics.ref] at this
4308 // point, which is that, due to p2 (which short-circuits reference
4309 // binding by only attempting a simple conversion for non-direct
4310 // bindings) and p3's strange wording, we allow a const volatile
4311 // reference to bind to an rvalue. Hence the check for the presence
4312 // of "const" rather than checking for "const" being the only
4313 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004314 // This is also the point where rvalue references and lvalue inits no longer
4315 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004316 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004317 return ICS;
4318
Douglas Gregorf143cd52011-01-24 16:14:37 +00004319 // -- If the initializer expression
4320 //
4321 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004322 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004323 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4324 (InitCategory.isXValue() ||
4325 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4326 (InitCategory.isLValue() && T2->isFunctionType()))) {
4327 ICS.setStandard();
4328 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004329 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004330 : ObjCConversion? ICK_Compatible_Conversion
4331 : ICK_Identity;
4332 ICS.Standard.Third = ICK_Identity;
4333 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4334 ICS.Standard.setToType(0, T2);
4335 ICS.Standard.setToType(1, T1);
4336 ICS.Standard.setToType(2, T1);
4337 ICS.Standard.ReferenceBinding = true;
4338 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4339 // binding unless we're binding to a class prvalue.
4340 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4341 // allow the use of rvalue references in C++98/03 for the benefit of
4342 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004343 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004344 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004345 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004346 ICS.Standard.IsLvalueReference = !isRValRef;
4347 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004349 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004350 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004351 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004352 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355
Douglas Gregorf143cd52011-01-24 16:14:37 +00004356 // -- has a class type (i.e., T2 is a class type), where T1 is not
4357 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358 // an xvalue, class prvalue, or function lvalue of type
4359 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004360 // "cv3 T3",
4361 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004363 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004364 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004365 // class subobject).
4366 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004368 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4369 Init, T2, /*AllowRvalues=*/true,
4370 AllowExplicit)) {
4371 // In the second case, if the reference is an rvalue reference
4372 // and the second standard conversion sequence of the
4373 // user-defined conversion sequence includes an lvalue-to-rvalue
4374 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004375 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004376 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4377 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4378
Douglas Gregor95273c32011-01-21 16:36:05 +00004379 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004380 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004381
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004382 // -- Otherwise, a temporary of type "cv1 T1" is created and
4383 // initialized from the initializer expression using the
4384 // rules for a non-reference copy initialization (8.5). The
4385 // reference is then bound to the temporary. If T1 is
4386 // reference-related to T2, cv1 must be the same
4387 // cv-qualification as, or greater cv-qualification than,
4388 // cv2; otherwise, the program is ill-formed.
4389 if (RefRelationship == Sema::Ref_Related) {
4390 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4391 // we would be reference-compatible or reference-compatible with
4392 // added qualification. But that wasn't the case, so the reference
4393 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004394 //
4395 // Note that we only want to check address spaces and cvr-qualifiers here.
4396 // ObjC GC and lifetime qualifiers aren't important.
4397 Qualifiers T1Quals = T1.getQualifiers();
4398 Qualifiers T2Quals = T2.getQualifiers();
4399 T1Quals.removeObjCGCAttr();
4400 T1Quals.removeObjCLifetime();
4401 T2Quals.removeObjCGCAttr();
4402 T2Quals.removeObjCLifetime();
4403 if (!T1Quals.compatiblyIncludes(T2Quals))
4404 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004405 }
4406
4407 // If at least one of the types is a class type, the types are not
4408 // related, and we aren't allowed any user conversions, the
4409 // reference binding fails. This case is important for breaking
4410 // recursion, since TryImplicitConversion below will attempt to
4411 // create a temporary through the use of a copy constructor.
4412 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4413 (T1->isRecordType() || T2->isRecordType()))
4414 return ICS;
4415
Douglas Gregorcba72b12011-01-21 05:18:22 +00004416 // If T1 is reference-related to T2 and the reference is an rvalue
4417 // reference, the initializer expression shall not be an lvalue.
4418 if (RefRelationship >= Sema::Ref_Related &&
4419 isRValRef && Init->Classify(S.Context).isLValue())
4420 return ICS;
4421
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004422 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004423 // When a parameter of reference type is not bound directly to
4424 // an argument expression, the conversion sequence is the one
4425 // required to convert the argument expression to the
4426 // underlying type of the reference according to
4427 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4428 // to copy-initializing a temporary of the underlying type with
4429 // the argument expression. Any difference in top-level
4430 // cv-qualification is subsumed by the initialization itself
4431 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004432 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4433 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004434 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004435 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004436 /*AllowObjCWritebackConversion=*/false,
4437 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004438
4439 // Of course, that's still a reference binding.
4440 if (ICS.isStandard()) {
4441 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004442 ICS.Standard.IsLvalueReference = !isRValRef;
4443 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4444 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004445 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004446 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004447 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004448 // Don't allow rvalue references to bind to lvalues.
4449 if (DeclType->isRValueReferenceType()) {
4450 if (const ReferenceType *RefType
4451 = ICS.UserDefined.ConversionFunction->getResultType()
4452 ->getAs<LValueReferenceType>()) {
4453 if (!RefType->getPointeeType()->isFunctionType()) {
4454 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4455 DeclType);
4456 return ICS;
4457 }
4458 }
4459 }
4460
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004461 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004462 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4463 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4464 ICS.UserDefined.After.BindsToRvalue = true;
4465 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4466 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004467 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004468
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004469 return ICS;
4470}
4471
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004472static ImplicitConversionSequence
4473TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4474 bool SuppressUserConversions,
4475 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004476 bool AllowObjCWritebackConversion,
4477 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004478
4479/// TryListConversion - Try to copy-initialize a value of type ToType from the
4480/// initializer list From.
4481static ImplicitConversionSequence
4482TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4483 bool SuppressUserConversions,
4484 bool InOverloadResolution,
4485 bool AllowObjCWritebackConversion) {
4486 // C++11 [over.ics.list]p1:
4487 // When an argument is an initializer list, it is not an expression and
4488 // special rules apply for converting it to a parameter type.
4489
4490 ImplicitConversionSequence Result;
4491 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4492
Sebastian Redl09edce02012-01-23 22:09:39 +00004493 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004494 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004495 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004496 return Result;
4497
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004498 // C++11 [over.ics.list]p2:
4499 // If the parameter type is std::initializer_list<X> or "array of X" and
4500 // all the elements can be implicitly converted to X, the implicit
4501 // conversion sequence is the worst conversion necessary to convert an
4502 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004503 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004504 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004505 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004506 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004507 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004508 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004509 if (!X.isNull()) {
4510 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4511 Expr *Init = From->getInit(i);
4512 ImplicitConversionSequence ICS =
4513 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4514 InOverloadResolution,
4515 AllowObjCWritebackConversion);
4516 // If a single element isn't convertible, fail.
4517 if (ICS.isBad()) {
4518 Result = ICS;
4519 break;
4520 }
4521 // Otherwise, look for the worst conversion.
4522 if (Result.isBad() ||
4523 CompareImplicitConversionSequences(S, ICS, Result) ==
4524 ImplicitConversionSequence::Worse)
4525 Result = ICS;
4526 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004527
4528 // For an empty list, we won't have computed any conversion sequence.
4529 // Introduce the identity conversion sequence.
4530 if (From->getNumInits() == 0) {
4531 Result.setStandard();
4532 Result.Standard.setAsIdentityConversion();
4533 Result.Standard.setFromType(ToType);
4534 Result.Standard.setAllToTypes(ToType);
4535 }
4536
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004537 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004538 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004539 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004540
4541 // C++11 [over.ics.list]p3:
4542 // Otherwise, if the parameter is a non-aggregate class X and overload
4543 // resolution chooses a single best constructor [...] the implicit
4544 // conversion sequence is a user-defined conversion sequence. If multiple
4545 // constructors are viable but none is better than the others, the
4546 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004547 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4548 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004549 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4550 /*AllowExplicit=*/false,
4551 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004552 AllowObjCWritebackConversion,
4553 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004554 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004555
4556 // C++11 [over.ics.list]p4:
4557 // Otherwise, if the parameter has an aggregate type which can be
4558 // initialized from the initializer list [...] the implicit conversion
4559 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004560 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004561 // Type is an aggregate, argument is an init list. At this point it comes
4562 // down to checking whether the initialization works.
4563 // FIXME: Find out whether this parameter is consumed or not.
4564 InitializedEntity Entity =
4565 InitializedEntity::InitializeParameter(S.Context, ToType,
4566 /*Consumed=*/false);
4567 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4568 Result.setUserDefined();
4569 Result.UserDefined.Before.setAsIdentityConversion();
4570 // Initializer lists don't have a type.
4571 Result.UserDefined.Before.setFromType(QualType());
4572 Result.UserDefined.Before.setAllToTypes(QualType());
4573
4574 Result.UserDefined.After.setAsIdentityConversion();
4575 Result.UserDefined.After.setFromType(ToType);
4576 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004577 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004578 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004579 return Result;
4580 }
4581
4582 // C++11 [over.ics.list]p5:
4583 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004584 if (ToType->isReferenceType()) {
4585 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4586 // mention initializer lists in any way. So we go by what list-
4587 // initialization would do and try to extrapolate from that.
4588
4589 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4590
4591 // If the initializer list has a single element that is reference-related
4592 // to the parameter type, we initialize the reference from that.
4593 if (From->getNumInits() == 1) {
4594 Expr *Init = From->getInit(0);
4595
4596 QualType T2 = Init->getType();
4597
4598 // If the initializer is the address of an overloaded function, try
4599 // to resolve the overloaded function. If all goes well, T2 is the
4600 // type of the resulting function.
4601 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4602 DeclAccessPair Found;
4603 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4604 Init, ToType, false, Found))
4605 T2 = Fn->getType();
4606 }
4607
4608 // Compute some basic properties of the types and the initializer.
4609 bool dummy1 = false;
4610 bool dummy2 = false;
4611 bool dummy3 = false;
4612 Sema::ReferenceCompareResult RefRelationship
4613 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4614 dummy2, dummy3);
4615
Richard Smith4d2bbd72013-09-06 01:22:42 +00004616 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004617 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4618 SuppressUserConversions,
4619 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004620 }
Sebastian Redldf888642011-12-03 14:54:30 +00004621 }
4622
4623 // Otherwise, we bind the reference to a temporary created from the
4624 // initializer list.
4625 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4626 InOverloadResolution,
4627 AllowObjCWritebackConversion);
4628 if (Result.isFailure())
4629 return Result;
4630 assert(!Result.isEllipsis() &&
4631 "Sub-initialization cannot result in ellipsis conversion.");
4632
4633 // Can we even bind to a temporary?
4634 if (ToType->isRValueReferenceType() ||
4635 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4636 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4637 Result.UserDefined.After;
4638 SCS.ReferenceBinding = true;
4639 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4640 SCS.BindsToRvalue = true;
4641 SCS.BindsToFunctionLvalue = false;
4642 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4643 SCS.ObjCLifetimeConversionBinding = false;
4644 } else
4645 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4646 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004647 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004648 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004649
4650 // C++11 [over.ics.list]p6:
4651 // Otherwise, if the parameter type is not a class:
4652 if (!ToType->isRecordType()) {
4653 // - if the initializer list has one element, the implicit conversion
4654 // sequence is the one required to convert the element to the
4655 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004656 unsigned NumInits = From->getNumInits();
4657 if (NumInits == 1)
4658 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4659 SuppressUserConversions,
4660 InOverloadResolution,
4661 AllowObjCWritebackConversion);
4662 // - if the initializer list has no elements, the implicit conversion
4663 // sequence is the identity conversion.
4664 else if (NumInits == 0) {
4665 Result.setStandard();
4666 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004667 Result.Standard.setFromType(ToType);
4668 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004669 }
4670 return Result;
4671 }
4672
4673 // C++11 [over.ics.list]p7:
4674 // In all cases other than those enumerated above, no conversion is possible
4675 return Result;
4676}
4677
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004678/// TryCopyInitialization - Try to copy-initialize a value of type
4679/// ToType from the expression From. Return the implicit conversion
4680/// sequence required to pass this argument, which may be a bad
4681/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004682/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004683/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004684static ImplicitConversionSequence
4685TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004687 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004688 bool AllowObjCWritebackConversion,
4689 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004690 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4691 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4692 InOverloadResolution,AllowObjCWritebackConversion);
4693
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004694 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004695 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004696 /*FIXME:*/From->getLocStart(),
4697 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004698 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004699
John McCall5c32be02010-08-24 20:38:10 +00004700 return TryImplicitConversion(S, From, ToType,
4701 SuppressUserConversions,
4702 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004703 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004704 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004705 AllowObjCWritebackConversion,
4706 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004707}
4708
Anna Zaks1b068122011-07-28 19:46:48 +00004709static bool TryCopyInitialization(const CanQualType FromQTy,
4710 const CanQualType ToQTy,
4711 Sema &S,
4712 SourceLocation Loc,
4713 ExprValueKind FromVK) {
4714 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4715 ImplicitConversionSequence ICS =
4716 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4717
4718 return !ICS.isBad();
4719}
4720
Douglas Gregor436424c2008-11-18 23:14:02 +00004721/// TryObjectArgumentInitialization - Try to initialize the object
4722/// parameter of the given member function (@c Method) from the
4723/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004724static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004725TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004726 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004727 CXXMethodDecl *Method,
4728 CXXRecordDecl *ActingContext) {
4729 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004730 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4731 // const volatile object.
4732 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4733 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004734 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004735
4736 // Set up the conversion sequence as a "bad" conversion, to allow us
4737 // to exit early.
4738 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004739
4740 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004741 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004742 FromType = PT->getPointeeType();
4743
Douglas Gregor02824322011-01-26 19:30:28 +00004744 // When we had a pointer, it's implicitly dereferenced, so we
4745 // better have an lvalue.
4746 assert(FromClassification.isLValue());
4747 }
4748
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004749 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004750
Douglas Gregor02824322011-01-26 19:30:28 +00004751 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004752 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004753 // parameter is
4754 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004755 // - "lvalue reference to cv X" for functions declared without a
4756 // ref-qualifier or with the & ref-qualifier
4757 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004758 // ref-qualifier
4759 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004760 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004761 // cv-qualification on the member function declaration.
4762 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004763 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004764 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004765 // (C++ [over.match.funcs]p5). We perform a simplified version of
4766 // reference binding here, that allows class rvalues to bind to
4767 // non-constant references.
4768
Douglas Gregor02824322011-01-26 19:30:28 +00004769 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004770 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004772 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004773 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004774 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004775 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004776 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004777 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004778
4779 // Check that we have either the same type or a derived type. It
4780 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004781 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004782 ImplicitConversionKind SecondKind;
4783 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4784 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004785 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004786 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004787 else {
John McCall65eb8792010-02-25 01:37:24 +00004788 ICS.setBad(BadConversionSequence::unrelated_class,
4789 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004790 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004791 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004792
Douglas Gregor02824322011-01-26 19:30:28 +00004793 // Check the ref-qualifier.
4794 switch (Method->getRefQualifier()) {
4795 case RQ_None:
4796 // Do nothing; we don't care about lvalueness or rvalueness.
4797 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004798
Douglas Gregor02824322011-01-26 19:30:28 +00004799 case RQ_LValue:
4800 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4801 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004803 ImplicitParamType);
4804 return ICS;
4805 }
4806 break;
4807
4808 case RQ_RValue:
4809 if (!FromClassification.isRValue()) {
4810 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004811 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004812 ImplicitParamType);
4813 return ICS;
4814 }
4815 break;
4816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817
Douglas Gregor436424c2008-11-18 23:14:02 +00004818 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004819 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004820 ICS.Standard.setAsIdentityConversion();
4821 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004822 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004823 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004824 ICS.Standard.ReferenceBinding = true;
4825 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004826 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004827 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004828 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4829 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4830 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004831 return ICS;
4832}
4833
4834/// PerformObjectArgumentInitialization - Perform initialization of
4835/// the implicit object parameter for the given Method with the given
4836/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004837ExprResult
4838Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004840 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004841 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004842 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004843 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004844 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004845
Douglas Gregor02824322011-01-26 19:30:28 +00004846 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004847 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004848 FromRecordType = PT->getPointeeType();
4849 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004850 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004851 } else {
4852 FromRecordType = From->getType();
4853 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004854 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004855 }
4856
John McCall6e9f8f62009-12-03 04:06:58 +00004857 // Note that we always use the true parent context when performing
4858 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004859 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004860 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4861 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004862 if (ICS.isBad()) {
4863 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4864 Qualifiers FromQs = FromRecordType.getQualifiers();
4865 Qualifiers ToQs = DestType.getQualifiers();
4866 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4867 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004868 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004869 diag::err_member_function_call_bad_cvr)
4870 << Method->getDeclName() << FromRecordType << (CVR - 1)
4871 << From->getSourceRange();
4872 Diag(Method->getLocation(), diag::note_previous_decl)
4873 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004874 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004875 }
4876 }
4877
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004878 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004879 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004880 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004881 }
Mike Stump11289f42009-09-09 15:08:12 +00004882
John Wiegley01296292011-04-08 18:41:53 +00004883 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4884 ExprResult FromRes =
4885 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4886 if (FromRes.isInvalid())
4887 return ExprError();
4888 From = FromRes.take();
4889 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004890
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004891 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004892 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004893 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004894 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004895}
4896
Douglas Gregor5fb53972009-01-14 15:45:31 +00004897/// TryContextuallyConvertToBool - Attempt to contextually convert the
4898/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004899static ImplicitConversionSequence
4900TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004901 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004902 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004903 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004904 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004905 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004906 /*AllowObjCWritebackConversion=*/false,
4907 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004908}
4909
4910/// PerformContextuallyConvertToBool - Perform a contextual conversion
4911/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004912ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004913 if (checkPlaceholderForOverload(*this, From))
4914 return ExprError();
4915
John McCall5c32be02010-08-24 20:38:10 +00004916 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004917 if (!ICS.isBad())
4918 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004919
Fariborz Jahanian76197412009-11-18 18:26:29 +00004920 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004921 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004922 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004923 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004924 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004925}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004926
Richard Smithf8379a02012-01-18 23:55:52 +00004927/// Check that the specified conversion is permitted in a converted constant
4928/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4929/// is acceptable.
4930static bool CheckConvertedConstantConversions(Sema &S,
4931 StandardConversionSequence &SCS) {
4932 // Since we know that the target type is an integral or unscoped enumeration
4933 // type, most conversion kinds are impossible. All possible First and Third
4934 // conversions are fine.
4935 switch (SCS.Second) {
4936 case ICK_Identity:
4937 case ICK_Integral_Promotion:
4938 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004939 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004940 return true;
4941
4942 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004943 // Conversion from an integral or unscoped enumeration type to bool is
4944 // classified as ICK_Boolean_Conversion, but it's also an integral
4945 // conversion, so it's permitted in a converted constant expression.
4946 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4947 SCS.getToType(2)->isBooleanType();
4948
Richard Smithf8379a02012-01-18 23:55:52 +00004949 case ICK_Floating_Integral:
4950 case ICK_Complex_Real:
4951 return false;
4952
4953 case ICK_Lvalue_To_Rvalue:
4954 case ICK_Array_To_Pointer:
4955 case ICK_Function_To_Pointer:
4956 case ICK_NoReturn_Adjustment:
4957 case ICK_Qualification:
4958 case ICK_Compatible_Conversion:
4959 case ICK_Vector_Conversion:
4960 case ICK_Vector_Splat:
4961 case ICK_Derived_To_Base:
4962 case ICK_Pointer_Conversion:
4963 case ICK_Pointer_Member:
4964 case ICK_Block_Pointer_Conversion:
4965 case ICK_Writeback_Conversion:
4966 case ICK_Floating_Promotion:
4967 case ICK_Complex_Promotion:
4968 case ICK_Complex_Conversion:
4969 case ICK_Floating_Conversion:
4970 case ICK_TransparentUnionConversion:
4971 llvm_unreachable("unexpected second conversion kind");
4972
4973 case ICK_Num_Conversion_Kinds:
4974 break;
4975 }
4976
4977 llvm_unreachable("unknown conversion kind");
4978}
4979
4980/// CheckConvertedConstantExpression - Check that the expression From is a
4981/// converted constant expression of type T, perform the conversion and produce
4982/// the converted expression, per C++11 [expr.const]p3.
4983ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4984 llvm::APSInt &Value,
4985 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004986 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004987 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4988
4989 if (checkPlaceholderForOverload(*this, From))
4990 return ExprError();
4991
4992 // C++11 [expr.const]p3 with proposed wording fixes:
4993 // A converted constant expression of type T is a core constant expression,
4994 // implicitly converted to a prvalue of type T, where the converted
4995 // expression is a literal constant expression and the implicit conversion
4996 // sequence contains only user-defined conversions, lvalue-to-rvalue
4997 // conversions, integral promotions, and integral conversions other than
4998 // narrowing conversions.
4999 ImplicitConversionSequence ICS =
5000 TryImplicitConversion(From, T,
5001 /*SuppressUserConversions=*/false,
5002 /*AllowExplicit=*/false,
5003 /*InOverloadResolution=*/false,
5004 /*CStyle=*/false,
5005 /*AllowObjcWritebackConversion=*/false);
5006 StandardConversionSequence *SCS = 0;
5007 switch (ICS.getKind()) {
5008 case ImplicitConversionSequence::StandardConversion:
5009 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005010 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005011 diag::err_typecheck_converted_constant_expression_disallowed)
5012 << From->getType() << From->getSourceRange() << T;
5013 SCS = &ICS.Standard;
5014 break;
5015 case ImplicitConversionSequence::UserDefinedConversion:
5016 // We are converting from class type to an integral or enumeration type, so
5017 // the Before sequence must be trivial.
5018 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005019 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005020 diag::err_typecheck_converted_constant_expression_disallowed)
5021 << From->getType() << From->getSourceRange() << T;
5022 SCS = &ICS.UserDefined.After;
5023 break;
5024 case ImplicitConversionSequence::AmbiguousConversion:
5025 case ImplicitConversionSequence::BadConversion:
5026 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005027 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005028 diag::err_typecheck_converted_constant_expression)
5029 << From->getType() << From->getSourceRange() << T;
5030 return ExprError();
5031
5032 case ImplicitConversionSequence::EllipsisConversion:
5033 llvm_unreachable("ellipsis conversion in converted constant expression");
5034 }
5035
5036 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5037 if (Result.isInvalid())
5038 return Result;
5039
5040 // Check for a narrowing implicit conversion.
5041 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005042 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005043 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5044 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005045 case NK_Variable_Narrowing:
5046 // Implicit conversion to a narrower type, and the value is not a constant
5047 // expression. We'll diagnose this in a moment.
5048 case NK_Not_Narrowing:
5049 break;
5050
5051 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005052 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005053 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005054 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005055 break;
5056
5057 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005058 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005059 << CCE << /*Constant*/0 << From->getType() << T;
5060 break;
5061 }
5062
5063 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005064 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005065 Expr::EvalResult Eval;
5066 Eval.Diag = &Notes;
5067
Douglas Gregorebe2db72013-04-08 23:24:07 +00005068 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005069 // The expression can't be folded, so we can't keep it at this position in
5070 // the AST.
5071 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005072 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005073 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005074
5075 if (Notes.empty()) {
5076 // It's a constant expression.
5077 return Result;
5078 }
Richard Smithf8379a02012-01-18 23:55:52 +00005079 }
5080
5081 // It's not a constant expression. Produce an appropriate diagnostic.
5082 if (Notes.size() == 1 &&
5083 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5084 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5085 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005086 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005087 << CCE << From->getSourceRange();
5088 for (unsigned I = 0; I < Notes.size(); ++I)
5089 Diag(Notes[I].first, Notes[I].second);
5090 }
Richard Smith911e1422012-01-30 22:27:01 +00005091 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005092}
5093
John McCallfec112d2011-09-09 06:11:02 +00005094/// dropPointerConversions - If the given standard conversion sequence
5095/// involves any pointer conversions, remove them. This may change
5096/// the result type of the conversion sequence.
5097static void dropPointerConversion(StandardConversionSequence &SCS) {
5098 if (SCS.Second == ICK_Pointer_Conversion) {
5099 SCS.Second = ICK_Identity;
5100 SCS.Third = ICK_Identity;
5101 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5102 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005103}
John McCall5c32be02010-08-24 20:38:10 +00005104
John McCallfec112d2011-09-09 06:11:02 +00005105/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5106/// convert the expression From to an Objective-C pointer type.
5107static ImplicitConversionSequence
5108TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5109 // Do an implicit conversion to 'id'.
5110 QualType Ty = S.Context.getObjCIdType();
5111 ImplicitConversionSequence ICS
5112 = TryImplicitConversion(S, From, Ty,
5113 // FIXME: Are these flags correct?
5114 /*SuppressUserConversions=*/false,
5115 /*AllowExplicit=*/true,
5116 /*InOverloadResolution=*/false,
5117 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005118 /*AllowObjCWritebackConversion=*/false,
5119 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005120
5121 // Strip off any final conversions to 'id'.
5122 switch (ICS.getKind()) {
5123 case ImplicitConversionSequence::BadConversion:
5124 case ImplicitConversionSequence::AmbiguousConversion:
5125 case ImplicitConversionSequence::EllipsisConversion:
5126 break;
5127
5128 case ImplicitConversionSequence::UserDefinedConversion:
5129 dropPointerConversion(ICS.UserDefined.After);
5130 break;
5131
5132 case ImplicitConversionSequence::StandardConversion:
5133 dropPointerConversion(ICS.Standard);
5134 break;
5135 }
5136
5137 return ICS;
5138}
5139
5140/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5141/// conversion of the expression From to an Objective-C pointer type.
5142ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005143 if (checkPlaceholderForOverload(*this, From))
5144 return ExprError();
5145
John McCall8b07ec22010-05-15 11:32:37 +00005146 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005147 ImplicitConversionSequence ICS =
5148 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005149 if (!ICS.isBad())
5150 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005151 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005152}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005153
Richard Smith8dd34252012-02-04 07:07:42 +00005154/// Determine whether the provided type is an integral type, or an enumeration
5155/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005156bool Sema::ICEConvertDiagnoser::match(QualType T) {
5157 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5158 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005159}
5160
Larisse Voufo236bec22013-06-10 06:50:24 +00005161static ExprResult
5162diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5163 Sema::ContextualImplicitConverter &Converter,
5164 QualType T, UnresolvedSetImpl &ViableConversions) {
5165
5166 if (Converter.Suppress)
5167 return ExprError();
5168
5169 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5170 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5171 CXXConversionDecl *Conv =
5172 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5173 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5174 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5175 }
5176 return SemaRef.Owned(From);
5177}
5178
5179static bool
5180diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5181 Sema::ContextualImplicitConverter &Converter,
5182 QualType T, bool HadMultipleCandidates,
5183 UnresolvedSetImpl &ExplicitConversions) {
5184 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5185 DeclAccessPair Found = ExplicitConversions[0];
5186 CXXConversionDecl *Conversion =
5187 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5188
5189 // The user probably meant to invoke the given explicit
5190 // conversion; use it.
5191 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5192 std::string TypeStr;
5193 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5194
5195 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5196 << FixItHint::CreateInsertion(From->getLocStart(),
5197 "static_cast<" + TypeStr + ">(")
5198 << FixItHint::CreateInsertion(
5199 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5200 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5201
5202 // If we aren't in a SFINAE context, build a call to the
5203 // explicit conversion function.
5204 if (SemaRef.isSFINAEContext())
5205 return true;
5206
5207 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5208 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5209 HadMultipleCandidates);
5210 if (Result.isInvalid())
5211 return true;
5212 // Record usage of conversion in an implicit cast.
5213 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5214 CK_UserDefinedConversion, Result.get(), 0,
5215 Result.get()->getValueKind());
5216 }
5217 return false;
5218}
5219
5220static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5221 Sema::ContextualImplicitConverter &Converter,
5222 QualType T, bool HadMultipleCandidates,
5223 DeclAccessPair &Found) {
5224 CXXConversionDecl *Conversion =
5225 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5226 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5227
5228 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5229 if (!Converter.SuppressConversion) {
5230 if (SemaRef.isSFINAEContext())
5231 return true;
5232
5233 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5234 << From->getSourceRange();
5235 }
5236
5237 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5238 HadMultipleCandidates);
5239 if (Result.isInvalid())
5240 return true;
5241 // Record usage of conversion in an implicit cast.
5242 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5243 CK_UserDefinedConversion, Result.get(), 0,
5244 Result.get()->getValueKind());
5245 return false;
5246}
5247
5248static ExprResult finishContextualImplicitConversion(
5249 Sema &SemaRef, SourceLocation Loc, Expr *From,
5250 Sema::ContextualImplicitConverter &Converter) {
5251 if (!Converter.match(From->getType()) && !Converter.Suppress)
5252 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5253 << From->getSourceRange();
5254
5255 return SemaRef.DefaultLvalueConversion(From);
5256}
5257
5258static void
5259collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5260 UnresolvedSetImpl &ViableConversions,
5261 OverloadCandidateSet &CandidateSet) {
5262 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5263 DeclAccessPair FoundDecl = ViableConversions[I];
5264 NamedDecl *D = FoundDecl.getDecl();
5265 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5266 if (isa<UsingShadowDecl>(D))
5267 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5268
5269 CXXConversionDecl *Conv;
5270 FunctionTemplateDecl *ConvTemplate;
5271 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5272 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5273 else
5274 Conv = cast<CXXConversionDecl>(D);
5275
5276 if (ConvTemplate)
5277 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005278 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5279 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005280 else
5281 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005282 ToType, CandidateSet,
5283 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005284 }
5285}
5286
Richard Smithccc11812013-05-21 19:05:48 +00005287/// \brief Attempt to convert the given expression to a type which is accepted
5288/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005289///
Richard Smithccc11812013-05-21 19:05:48 +00005290/// This routine will attempt to convert an expression of class type to a
5291/// type accepted by the specified converter. In C++11 and before, the class
5292/// must have a single non-explicit conversion function converting to a matching
5293/// type. In C++1y, there can be multiple such conversion functions, but only
5294/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005295///
Douglas Gregor4799d032010-06-30 00:20:43 +00005296/// \param Loc The source location of the construct that requires the
5297/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005298///
James Dennett18348b62012-06-22 08:52:37 +00005299/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005300///
Richard Smithccc11812013-05-21 19:05:48 +00005301/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005302///
Douglas Gregor4799d032010-06-30 00:20:43 +00005303/// \returns The expression, converted to an integral or enumeration type if
5304/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005305ExprResult Sema::PerformContextualImplicitConversion(
5306 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005307 // We can't perform any more checking for type-dependent expressions.
5308 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005309 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005310
Eli Friedman1da70392012-01-26 00:26:18 +00005311 // Process placeholders immediately.
5312 if (From->hasPlaceholderType()) {
5313 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005314 if (result.isInvalid())
5315 return result;
Eli Friedman1da70392012-01-26 00:26:18 +00005316 From = result.take();
5317 }
5318
Richard Smithccc11812013-05-21 19:05:48 +00005319 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005320 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005321 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005322 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005323
5324 // FIXME: Check for missing '()' if T is a function type?
5325
Richard Smithccc11812013-05-21 19:05:48 +00005326 // We can only perform contextual implicit conversions on objects of class
5327 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005328 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005329 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005330 if (!Converter.Suppress)
5331 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005332 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005334
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005335 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005336 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005337 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005338 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005339
5340 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5341 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5342
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005343 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smithccc11812013-05-21 19:05:48 +00005344 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005345 }
Richard Smithccc11812013-05-21 19:05:48 +00005346 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005347
5348 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005349 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005350
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005351 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005352 UnresolvedSet<4>
5353 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005354 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005355 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005356 CXXRecordDecl::conversion_iterator> Conversions =
5357 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005358
Larisse Voufo236bec22013-06-10 06:50:24 +00005359 bool HadMultipleCandidates =
5360 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005361
Larisse Voufo236bec22013-06-10 06:50:24 +00005362 // To check that there is only one target type, in C++1y:
5363 QualType ToType;
5364 bool HasUniqueTargetType = true;
5365
5366 // Collect explicit or viable (potentially in C++1y) conversions.
5367 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5368 E = Conversions.second;
5369 I != E; ++I) {
5370 NamedDecl *D = (*I)->getUnderlyingDecl();
5371 CXXConversionDecl *Conversion;
5372 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5373 if (ConvTemplate) {
5374 if (getLangOpts().CPlusPlus1y)
5375 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5376 else
5377 continue; // C++11 does not consider conversion operator templates(?).
5378 } else
5379 Conversion = cast<CXXConversionDecl>(D);
5380
5381 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5382 "Conversion operator templates are considered potentially "
5383 "viable in C++1y");
5384
5385 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5386 if (Converter.match(CurToType) || ConvTemplate) {
5387
5388 if (Conversion->isExplicit()) {
5389 // FIXME: For C++1y, do we need this restriction?
5390 // cf. diagnoseNoViableConversion()
5391 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005392 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005393 } else {
5394 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5395 if (ToType.isNull())
5396 ToType = CurToType.getUnqualifiedType();
5397 else if (HasUniqueTargetType &&
5398 (CurToType.getUnqualifiedType() != ToType))
5399 HasUniqueTargetType = false;
5400 }
5401 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005402 }
Richard Smith8dd34252012-02-04 07:07:42 +00005403 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005404 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005405
Larisse Voufo236bec22013-06-10 06:50:24 +00005406 if (getLangOpts().CPlusPlus1y) {
5407 // C++1y [conv]p6:
5408 // ... An expression e of class type E appearing in such a context
5409 // is said to be contextually implicitly converted to a specified
5410 // type T and is well-formed if and only if e can be implicitly
5411 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005412 // for conversion functions whose return type is cv T or reference to
5413 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005414 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005415
Larisse Voufo236bec22013-06-10 06:50:24 +00005416 // If no unique T is found:
5417 if (ToType.isNull()) {
5418 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5419 HadMultipleCandidates,
5420 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005421 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005422 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005423 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005424
Larisse Voufo236bec22013-06-10 06:50:24 +00005425 // If more than one unique Ts are found:
5426 if (!HasUniqueTargetType)
5427 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5428 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005429
Larisse Voufo236bec22013-06-10 06:50:24 +00005430 // If one unique T is found:
5431 // First, build a candidate set from the previously recorded
5432 // potentially viable conversions.
5433 OverloadCandidateSet CandidateSet(Loc);
5434 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5435 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005436
Larisse Voufo236bec22013-06-10 06:50:24 +00005437 // Then, perform overload resolution over the candidate set.
5438 OverloadCandidateSet::iterator Best;
5439 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5440 case OR_Success: {
5441 // Apply this conversion.
5442 DeclAccessPair Found =
5443 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5444 if (recordConversion(*this, Loc, From, Converter, T,
5445 HadMultipleCandidates, Found))
5446 return ExprError();
5447 break;
5448 }
5449 case OR_Ambiguous:
5450 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5451 ViableConversions);
5452 case OR_No_Viable_Function:
5453 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5454 HadMultipleCandidates,
5455 ExplicitConversions))
5456 return ExprError();
5457 // fall through 'OR_Deleted' case.
5458 case OR_Deleted:
5459 // We'll complain below about a non-integral condition type.
5460 break;
5461 }
5462 } else {
5463 switch (ViableConversions.size()) {
5464 case 0: {
5465 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5466 HadMultipleCandidates,
5467 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005468 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469
Larisse Voufo236bec22013-06-10 06:50:24 +00005470 // We'll complain below about a non-integral condition type.
5471 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005472 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005473 case 1: {
5474 // Apply this conversion.
5475 DeclAccessPair Found = ViableConversions[0];
5476 if (recordConversion(*this, Loc, From, Converter, T,
5477 HadMultipleCandidates, Found))
5478 return ExprError();
5479 break;
5480 }
5481 default:
5482 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5483 ViableConversions);
5484 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005485 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005486
Larisse Voufo236bec22013-06-10 06:50:24 +00005487 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005488}
5489
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005490/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005491/// candidate functions, using the given function call arguments. If
5492/// @p SuppressUserConversions, then don't allow user-defined
5493/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005494///
James Dennett2a4d13c2012-06-15 07:13:21 +00005495/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005496/// based on an incomplete set of function arguments. This feature is used by
5497/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005498void
5499Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005500 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005501 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005502 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005503 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005504 bool PartialOverloading,
5505 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005506 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005507 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005508 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005509 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005510 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005511
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005513 if (!isa<CXXConstructorDecl>(Method)) {
5514 // If we get here, it's because we're calling a member function
5515 // that is named without a member access expression (e.g.,
5516 // "this->f") that was either written explicitly or created
5517 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005518 // function, e.g., X::f(). We use an empty type for the implied
5519 // object argument (C++ [over.call.func]p3), and the acting context
5520 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005521 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005523 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005524 return;
5525 }
5526 // We treat a constructor like a non-member function, since its object
5527 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005528 }
5529
Douglas Gregorff7028a2009-11-13 23:59:09 +00005530 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005531 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005532
Richard Smith8b86f2d2013-11-04 01:48:18 +00005533 // C++11 [class.copy]p11: [DR1402]
5534 // A defaulted move constructor that is defined as deleted is ignored by
5535 // overload resolution.
5536 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5537 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5538 Constructor->isMoveConstructor())
5539 return;
5540
Douglas Gregor27381f32009-11-23 12:27:39 +00005541 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005542 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005543
Richard Smith8b86f2d2013-11-04 01:48:18 +00005544 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005545 // C++ [class.copy]p3:
5546 // A member function template is never instantiated to perform the copy
5547 // of a class object to an object of its class type.
5548 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005549 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005550 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005551 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5552 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005553 return;
5554 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005556 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005557 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005558 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005559 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005560 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005561 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005562 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005563 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005564
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005565 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005566
5567 // (C++ 13.3.2p2): A candidate function having fewer than m
5568 // parameters is viable only if it has an ellipsis in its parameter
5569 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005570 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005571 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005572 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005573 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005574 return;
5575 }
5576
5577 // (C++ 13.3.2p2): A candidate function having more than m parameters
5578 // is viable only if the (m+1)st parameter has a default argument
5579 // (8.3.6). For the purposes of overload resolution, the
5580 // parameter list is truncated on the right, so that there are
5581 // exactly m parameters.
5582 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005583 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005584 // Not enough arguments.
5585 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005586 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005587 return;
5588 }
5589
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005590 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005591 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005592 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5593 if (CheckCUDATarget(Caller, Function)) {
5594 Candidate.Viable = false;
5595 Candidate.FailureKind = ovl_fail_bad_target;
5596 return;
5597 }
5598
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005599 // Determine the implicit conversion sequences for each of the
5600 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005601 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005602 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005603 // (C++ 13.3.2p3): for F to be a viable function, there shall
5604 // exist for each argument an implicit conversion sequence
5605 // (13.3.3.1) that converts that argument to the corresponding
5606 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005607 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005608 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005609 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005610 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005611 /*InOverloadResolution=*/true,
5612 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005613 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005614 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005615 if (Candidate.Conversions[ArgIdx].isBad()) {
5616 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005617 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005618 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005619 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005620 } else {
5621 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5622 // argument for which there is no corresponding parameter is
5623 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005624 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005625 }
5626 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005627
5628 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5629 Candidate.Viable = false;
5630 Candidate.FailureKind = ovl_fail_enable_if;
5631 Candidate.DeductionFailure.Data = FailedAttr;
5632 return;
5633 }
5634}
5635
5636static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5637
5638EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5639 bool MissingImplicitThis) {
5640 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5641 // we need to find the first failing one.
5642 if (!Function->hasAttrs())
5643 return 0;
5644 AttrVec Attrs = Function->getAttrs();
5645 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5646 IsNotEnableIfAttr);
5647 if (Attrs.begin() == E)
5648 return 0;
5649 std::reverse(Attrs.begin(), E);
5650
5651 SFINAETrap Trap(*this);
5652
5653 // Convert the arguments.
5654 SmallVector<Expr *, 16> ConvertedArgs;
5655 bool InitializationFailed = false;
5656 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5657 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5658 !cast<CXXMethodDecl>(Function)->isStatic()) {
5659 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5660 ExprResult R =
5661 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5662 Method, Method);
5663 if (R.isInvalid()) {
5664 InitializationFailed = true;
5665 break;
5666 }
5667 ConvertedArgs.push_back(R.take());
5668 } else {
5669 ExprResult R =
5670 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5671 Context,
5672 Function->getParamDecl(i)),
5673 SourceLocation(),
5674 Args[i]);
5675 if (R.isInvalid()) {
5676 InitializationFailed = true;
5677 break;
5678 }
5679 ConvertedArgs.push_back(R.take());
5680 }
5681 }
5682
5683 if (InitializationFailed || Trap.hasErrorOccurred())
5684 return cast<EnableIfAttr>(Attrs[0]);
5685
5686 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5687 APValue Result;
5688 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5689 if (!EIA->getCond()->EvaluateWithSubstitution(
5690 Result, Context, Function,
5691 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(),
5692 ConvertedArgs.size())) ||
5693 !Result.isInt() || !Result.getInt().getBoolValue()) {
5694 return EIA;
5695 }
5696 }
5697 return 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005698}
5699
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005700/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005701/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005702void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005703 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005704 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005705 bool SuppressUserConversions,
5706 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005707 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005708 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5709 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005710 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005711 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005712 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005713 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005714 Args.slice(1), CandidateSet,
5715 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005716 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005717 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005718 SuppressUserConversions);
5719 } else {
John McCalla0296f72010-03-19 07:35:19 +00005720 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005721 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5722 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005723 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005724 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005725 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005726 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005727 Args[0]->Classify(Context), Args.slice(1),
5728 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005729 else
John McCalla0296f72010-03-19 07:35:19 +00005730 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005731 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005732 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005733 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005734 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005735}
5736
John McCallf0f1cf02009-11-17 07:50:12 +00005737/// AddMethodCandidate - Adds a named decl (which is some kind of
5738/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005739void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005740 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005741 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005742 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005743 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005744 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005745 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005746 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005747
5748 if (isa<UsingShadowDecl>(Decl))
5749 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005750
John McCallf0f1cf02009-11-17 07:50:12 +00005751 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5752 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5753 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005754 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5755 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005756 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005757 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005758 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005759 } else {
John McCalla0296f72010-03-19 07:35:19 +00005760 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005761 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005762 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005763 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005764 }
5765}
5766
Douglas Gregor436424c2008-11-18 23:14:02 +00005767/// AddMethodCandidate - Adds the given C++ member function to the set
5768/// of candidate functions, using the given function call arguments
5769/// and the object argument (@c Object). For example, in a call
5770/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5771/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5772/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005773/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005774void
John McCalla0296f72010-03-19 07:35:19 +00005775Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005776 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005777 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005778 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005779 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005780 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005781 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005782 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005783 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005784 assert(!isa<CXXConstructorDecl>(Method) &&
5785 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005786
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005787 if (!CandidateSet.isNewCandidate(Method))
5788 return;
5789
Richard Smith8b86f2d2013-11-04 01:48:18 +00005790 // C++11 [class.copy]p23: [DR1402]
5791 // A defaulted move assignment operator that is defined as deleted is
5792 // ignored by overload resolution.
5793 if (Method->isDefaulted() && Method->isDeleted() &&
5794 Method->isMoveAssignmentOperator())
5795 return;
5796
Douglas Gregor27381f32009-11-23 12:27:39 +00005797 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005798 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005799
Douglas Gregor436424c2008-11-18 23:14:02 +00005800 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005801 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005802 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005803 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005804 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005805 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005806 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005807
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005808 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005809
5810 // (C++ 13.3.2p2): A candidate function having fewer than m
5811 // parameters is viable only if it has an ellipsis in its parameter
5812 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005813 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005814 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005815 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005816 return;
5817 }
5818
5819 // (C++ 13.3.2p2): A candidate function having more than m parameters
5820 // is viable only if the (m+1)st parameter has a default argument
5821 // (8.3.6). For the purposes of overload resolution, the
5822 // parameter list is truncated on the right, so that there are
5823 // exactly m parameters.
5824 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005825 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005826 // Not enough arguments.
5827 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005828 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005829 return;
5830 }
5831
5832 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005833
John McCall6e9f8f62009-12-03 04:06:58 +00005834 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005835 // The implicit object argument is ignored.
5836 Candidate.IgnoreObjectArgument = true;
5837 else {
5838 // Determine the implicit conversion sequence for the object
5839 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005840 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005841 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5842 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005843 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005844 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005845 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005846 return;
5847 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005848 }
5849
5850 // Determine the implicit conversion sequences for each of the
5851 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005852 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005853 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005854 // (C++ 13.3.2p3): for F to be a viable function, there shall
5855 // exist for each argument an implicit conversion sequence
5856 // (13.3.3.1) that converts that argument to the corresponding
5857 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005858 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005859 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005860 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005861 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005862 /*InOverloadResolution=*/true,
5863 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005864 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005865 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005866 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005867 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005868 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005869 }
5870 } else {
5871 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5872 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005873 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005874 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005875 }
5876 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005877
5878 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5879 Candidate.Viable = false;
5880 Candidate.FailureKind = ovl_fail_enable_if;
5881 Candidate.DeductionFailure.Data = FailedAttr;
5882 return;
5883 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005884}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005885
Douglas Gregor97628d62009-08-21 00:16:32 +00005886/// \brief Add a C++ member function template as a candidate to the candidate
5887/// set, using template argument deduction to produce an appropriate member
5888/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005889void
Douglas Gregor97628d62009-08-21 00:16:32 +00005890Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005891 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005892 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005893 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005894 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005895 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005896 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005897 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005898 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005899 if (!CandidateSet.isNewCandidate(MethodTmpl))
5900 return;
5901
Douglas Gregor97628d62009-08-21 00:16:32 +00005902 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005903 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005904 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005905 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005906 // candidate functions in the usual way.113) A given name can refer to one
5907 // or more function templates and also to a set of overloaded non-template
5908 // functions. In such a case, the candidate functions generated from each
5909 // function template are combined with the set of non-template candidate
5910 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005911 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005912 FunctionDecl *Specialization = 0;
5913 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005914 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5915 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005916 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005917 Candidate.FoundDecl = FoundDecl;
5918 Candidate.Function = MethodTmpl->getTemplatedDecl();
5919 Candidate.Viable = false;
5920 Candidate.FailureKind = ovl_fail_bad_deduction;
5921 Candidate.IsSurrogate = false;
5922 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005923 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005924 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005925 Info);
5926 return;
5927 }
Mike Stump11289f42009-09-09 15:08:12 +00005928
Douglas Gregor97628d62009-08-21 00:16:32 +00005929 // Add the function template specialization produced by template argument
5930 // deduction as a candidate.
5931 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005932 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005933 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005934 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005935 ActingContext, ObjectType, ObjectClassification, Args,
5936 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005937}
5938
Douglas Gregor05155d82009-08-21 23:19:43 +00005939/// \brief Add a C++ function template specialization as a candidate
5940/// in the candidate set, using template argument deduction to produce
5941/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005942void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005943Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005944 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005945 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005946 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005947 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005948 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005949 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5950 return;
5951
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005952 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005953 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005954 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005955 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005956 // candidate functions in the usual way.113) A given name can refer to one
5957 // or more function templates and also to a set of overloaded non-template
5958 // functions. In such a case, the candidate functions generated from each
5959 // function template are combined with the set of non-template candidate
5960 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005961 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005962 FunctionDecl *Specialization = 0;
5963 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005964 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5965 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005966 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005967 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005968 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5969 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005970 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005971 Candidate.IsSurrogate = false;
5972 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005973 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005974 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005975 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005976 return;
5977 }
Mike Stump11289f42009-09-09 15:08:12 +00005978
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005979 // Add the function template specialization produced by template argument
5980 // deduction as a candidate.
5981 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005982 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005983 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005984}
Mike Stump11289f42009-09-09 15:08:12 +00005985
Douglas Gregor4b60a152013-11-07 22:34:54 +00005986/// Determine whether this is an allowable conversion from the result
5987/// of an explicit conversion operator to the expected type, per C++
5988/// [over.match.conv]p1 and [over.match.ref]p1.
5989///
5990/// \param ConvType The return type of the conversion function.
5991///
5992/// \param ToType The type we are converting to.
5993///
5994/// \param AllowObjCPointerConversion Allow a conversion from one
5995/// Objective-C pointer to another.
5996///
5997/// \returns true if the conversion is allowable, false otherwise.
5998static bool isAllowableExplicitConversion(Sema &S,
5999 QualType ConvType, QualType ToType,
6000 bool AllowObjCPointerConversion) {
6001 QualType ToNonRefType = ToType.getNonReferenceType();
6002
6003 // Easy case: the types are the same.
6004 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6005 return true;
6006
6007 // Allow qualification conversions.
6008 bool ObjCLifetimeConversion;
6009 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6010 ObjCLifetimeConversion))
6011 return true;
6012
6013 // If we're not allowed to consider Objective-C pointer conversions,
6014 // we're done.
6015 if (!AllowObjCPointerConversion)
6016 return false;
6017
6018 // Is this an Objective-C pointer conversion?
6019 bool IncompatibleObjC = false;
6020 QualType ConvertedType;
6021 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6022 IncompatibleObjC);
6023}
6024
Douglas Gregora1f013e2008-11-07 22:36:19 +00006025/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006026/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006027/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006028/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006029/// (which may or may not be the same type as the type that the
6030/// conversion function produces).
6031void
6032Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006033 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006034 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006035 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006036 OverloadCandidateSet& CandidateSet,
6037 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006038 assert(!Conversion->getDescribedFunctionTemplate() &&
6039 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006040 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006041 if (!CandidateSet.isNewCandidate(Conversion))
6042 return;
6043
Richard Smith2a7d4812013-05-04 07:00:32 +00006044 // If the conversion function has an undeduced return type, trigger its
6045 // deduction now.
6046 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6047 if (DeduceReturnType(Conversion, From->getExprLoc()))
6048 return;
6049 ConvType = Conversion->getConversionType().getNonReferenceType();
6050 }
6051
Richard Smith089c3162013-09-21 21:55:46 +00006052 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6053 // operator is only a candidate if its return type is the target type or
6054 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006055 if (Conversion->isExplicit() &&
6056 !isAllowableExplicitConversion(*this, ConvType, ToType,
6057 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006058 return;
6059
Douglas Gregor27381f32009-11-23 12:27:39 +00006060 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006061 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006062
Douglas Gregora1f013e2008-11-07 22:36:19 +00006063 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006064 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006065 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006066 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006067 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006068 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006069 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006070 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006071 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006072 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006073 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006074
Douglas Gregor6affc782010-08-19 15:37:02 +00006075 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006076 // For conversion functions, the function is considered to be a member of
6077 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006078 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006079 //
6080 // Determine the implicit conversion sequence for the implicit
6081 // object parameter.
6082 QualType ImplicitParamType = From->getType();
6083 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6084 ImplicitParamType = FromPtrType->getPointeeType();
6085 CXXRecordDecl *ConversionContext
6086 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006088 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006089 = TryObjectArgumentInitialization(*this, From->getType(),
6090 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006091 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006092
John McCall0d1da222010-01-12 00:44:57 +00006093 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006094 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006095 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006096 return;
6097 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006098
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006099 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006100 // derived to base as such conversions are given Conversion Rank. They only
6101 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6102 QualType FromCanon
6103 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6104 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6105 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6106 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006107 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006108 return;
6109 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006110
Douglas Gregora1f013e2008-11-07 22:36:19 +00006111 // To determine what the conversion from the result of calling the
6112 // conversion function to the type we're eventually trying to
6113 // convert to (ToType), we need to synthesize a call to the
6114 // conversion function and attempt copy initialization from it. This
6115 // makes sure that we get the right semantics with respect to
6116 // lvalues/rvalues and the type. Fortunately, we can allocate this
6117 // call on the stack and we don't need its arguments to be
6118 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006119 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006120 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006121 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6122 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006123 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006124 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006125
Richard Smith48d24642011-07-13 22:53:21 +00006126 QualType ConversionType = Conversion->getConversionType();
6127 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006128 Candidate.Viable = false;
6129 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6130 return;
6131 }
6132
Richard Smith48d24642011-07-13 22:53:21 +00006133 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006134
Mike Stump11289f42009-09-09 15:08:12 +00006135 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006136 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6137 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006138 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006139 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006140 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006141 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006142 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006143 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006144 /*InOverloadResolution=*/false,
6145 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006146
John McCall0d1da222010-01-12 00:44:57 +00006147 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006148 case ImplicitConversionSequence::StandardConversion:
6149 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006150
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006151 // C++ [over.ics.user]p3:
6152 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006153 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006154 // shall have exact match rank.
6155 if (Conversion->getPrimaryTemplate() &&
6156 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6157 Candidate.Viable = false;
6158 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006159 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006161
Douglas Gregorcba72b12011-01-21 05:18:22 +00006162 // C++0x [dcl.init.ref]p5:
6163 // In the second case, if the reference is an rvalue reference and
6164 // the second standard conversion sequence of the user-defined
6165 // conversion sequence includes an lvalue-to-rvalue conversion, the
6166 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006167 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006168 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6169 Candidate.Viable = false;
6170 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006171 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006172 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006173 break;
6174
6175 case ImplicitConversionSequence::BadConversion:
6176 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006177 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006178 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006179
6180 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006181 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006182 "Can only end up with a standard conversion sequence or failure");
6183 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006184
6185 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6186 Candidate.Viable = false;
6187 Candidate.FailureKind = ovl_fail_enable_if;
6188 Candidate.DeductionFailure.Data = FailedAttr;
6189 return;
6190 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006191}
6192
Douglas Gregor05155d82009-08-21 23:19:43 +00006193/// \brief Adds a conversion function template specialization
6194/// candidate to the overload set, using template argument deduction
6195/// to deduce the template arguments of the conversion function
6196/// template from the type that we are converting to (C++
6197/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006198void
Douglas Gregor05155d82009-08-21 23:19:43 +00006199Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006200 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006201 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006202 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006203 OverloadCandidateSet &CandidateSet,
6204 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006205 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6206 "Only conversion function templates permitted here");
6207
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006208 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6209 return;
6210
Craig Toppere6706e42012-09-19 02:26:47 +00006211 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00006212 CXXConversionDecl *Specialization = 0;
6213 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006214 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006215 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006216 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006217 Candidate.FoundDecl = FoundDecl;
6218 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6219 Candidate.Viable = false;
6220 Candidate.FailureKind = ovl_fail_bad_deduction;
6221 Candidate.IsSurrogate = false;
6222 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006223 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006224 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006225 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006226 return;
6227 }
Mike Stump11289f42009-09-09 15:08:12 +00006228
Douglas Gregor05155d82009-08-21 23:19:43 +00006229 // Add the conversion function template specialization produced by
6230 // template argument deduction as a candidate.
6231 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006232 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006233 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006234}
6235
Douglas Gregorab7897a2008-11-19 22:57:39 +00006236/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6237/// converts the given @c Object to a function pointer via the
6238/// conversion function @c Conversion, and then attempts to call it
6239/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6240/// the type of function that we'll eventually be calling.
6241void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006242 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006243 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006244 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006245 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006246 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006247 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006248 if (!CandidateSet.isNewCandidate(Conversion))
6249 return;
6250
Douglas Gregor27381f32009-11-23 12:27:39 +00006251 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006252 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006253
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006254 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006255 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006256 Candidate.Function = 0;
6257 Candidate.Surrogate = Conversion;
6258 Candidate.Viable = true;
6259 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006260 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006261 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006262
6263 // Determine the implicit conversion sequence for the implicit
6264 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006265 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006266 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006267 Object->Classify(Context),
6268 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006269 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006270 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006271 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006272 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006273 return;
6274 }
6275
6276 // The first conversion is actually a user-defined conversion whose
6277 // first conversion is ObjectInit's standard conversion (which is
6278 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006279 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006280 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006281 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006282 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006283 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006284 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006285 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006286 = Candidate.Conversions[0].UserDefined.Before;
6287 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6288
Mike Stump11289f42009-09-09 15:08:12 +00006289 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006290 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006291
6292 // (C++ 13.3.2p2): A candidate function having fewer than m
6293 // parameters is viable only if it has an ellipsis in its parameter
6294 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006295 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006296 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006297 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006298 return;
6299 }
6300
6301 // Function types don't have any default arguments, so just check if
6302 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006303 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006304 // Not enough arguments.
6305 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006306 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006307 return;
6308 }
6309
6310 // Determine the implicit conversion sequences for each of the
6311 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006312 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006313 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006314 // (C++ 13.3.2p3): for F to be a viable function, there shall
6315 // exist for each argument an implicit conversion sequence
6316 // (13.3.3.1) that converts that argument to the corresponding
6317 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006318 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006319 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006320 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006321 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006322 /*InOverloadResolution=*/false,
6323 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006324 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006325 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006326 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006327 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006328 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006329 }
6330 } else {
6331 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6332 // argument for which there is no corresponding parameter is
6333 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006334 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006335 }
6336 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006337
6338 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6339 Candidate.Viable = false;
6340 Candidate.FailureKind = ovl_fail_enable_if;
6341 Candidate.DeductionFailure.Data = FailedAttr;
6342 return;
6343 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006344}
6345
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006346/// \brief Add overload candidates for overloaded operators that are
6347/// member functions.
6348///
6349/// Add the overloaded operator candidates that are member functions
6350/// for the operator Op that was used in an operator expression such
6351/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6352/// CandidateSet will store the added overload candidates. (C++
6353/// [over.match.oper]).
6354void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6355 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006356 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006357 OverloadCandidateSet& CandidateSet,
6358 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006359 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6360
6361 // C++ [over.match.oper]p3:
6362 // For a unary operator @ with an operand of a type whose
6363 // cv-unqualified version is T1, and for a binary operator @ with
6364 // a left operand of a type whose cv-unqualified version is T1 and
6365 // a right operand of a type whose cv-unqualified version is T2,
6366 // three sets of candidate functions, designated member
6367 // candidates, non-member candidates and built-in candidates, are
6368 // constructed as follows:
6369 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006370
Richard Smith0feaf0c2013-04-20 12:41:22 +00006371 // -- If T1 is a complete class type or a class currently being
6372 // defined, the set of member candidates is the result of the
6373 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6374 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006375 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006376 // Complete the type if it can be completed.
6377 RequireCompleteType(OpLoc, T1, 0);
6378 // If the type is neither complete nor being defined, bail out now.
6379 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006380 return;
Mike Stump11289f42009-09-09 15:08:12 +00006381
John McCall27b18f82009-11-17 02:14:36 +00006382 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6383 LookupQualifiedName(Operators, T1Rec->getDecl());
6384 Operators.suppressDiagnostics();
6385
Mike Stump11289f42009-09-09 15:08:12 +00006386 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006387 OperEnd = Operators.end();
6388 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006389 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006390 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006391 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006392 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006393 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006394 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006395 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006396}
6397
Douglas Gregora11693b2008-11-12 17:17:38 +00006398/// AddBuiltinCandidate - Add a candidate for a built-in
6399/// operator. ResultTy and ParamTys are the result and parameter types
6400/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006401/// arguments being passed to the candidate. IsAssignmentOperator
6402/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006403/// operator. NumContextualBoolArguments is the number of arguments
6404/// (at the beginning of the argument list) that will be contextually
6405/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006406void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006407 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006408 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006409 bool IsAssignmentOperator,
6410 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006411 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006412 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006413
Douglas Gregora11693b2008-11-12 17:17:38 +00006414 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006415 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00006416 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00006417 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006418 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006419 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006420 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006421 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006422 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6423
6424 // Determine the implicit conversion sequences for each of the
6425 // arguments.
6426 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006427 Candidate.ExplicitCallArguments = Args.size();
6428 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006429 // C++ [over.match.oper]p4:
6430 // For the built-in assignment operators, conversions of the
6431 // left operand are restricted as follows:
6432 // -- no temporaries are introduced to hold the left operand, and
6433 // -- no user-defined conversions are applied to the left
6434 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006435 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006436 //
6437 // We block these conversions by turning off user-defined
6438 // conversions, since that is the only way that initialization of
6439 // a reference to a non-class type can occur from something that
6440 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006441 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006442 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006443 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006444 Candidate.Conversions[ArgIdx]
6445 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006446 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006447 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006448 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006449 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006450 /*InOverloadResolution=*/false,
6451 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006452 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006453 }
John McCall0d1da222010-01-12 00:44:57 +00006454 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006455 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006456 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006457 break;
6458 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006459 }
6460}
6461
Craig Toppercd7b0332013-07-01 06:29:40 +00006462namespace {
6463
Douglas Gregora11693b2008-11-12 17:17:38 +00006464/// BuiltinCandidateTypeSet - A set of types that will be used for the
6465/// candidate operator functions for built-in operators (C++
6466/// [over.built]). The types are separated into pointer types and
6467/// enumeration types.
6468class BuiltinCandidateTypeSet {
6469 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006470 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006471
6472 /// PointerTypes - The set of pointer types that will be used in the
6473 /// built-in candidates.
6474 TypeSet PointerTypes;
6475
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006476 /// MemberPointerTypes - The set of member pointer types that will be
6477 /// used in the built-in candidates.
6478 TypeSet MemberPointerTypes;
6479
Douglas Gregora11693b2008-11-12 17:17:38 +00006480 /// EnumerationTypes - The set of enumeration types that will be
6481 /// used in the built-in candidates.
6482 TypeSet EnumerationTypes;
6483
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006484 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006485 /// candidates.
6486 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006487
6488 /// \brief A flag indicating non-record types are viable candidates
6489 bool HasNonRecordTypes;
6490
6491 /// \brief A flag indicating whether either arithmetic or enumeration types
6492 /// were present in the candidate set.
6493 bool HasArithmeticOrEnumeralTypes;
6494
Douglas Gregor80af3132011-05-21 23:15:46 +00006495 /// \brief A flag indicating whether the nullptr type was present in the
6496 /// candidate set.
6497 bool HasNullPtrType;
6498
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006499 /// Sema - The semantic analysis instance where we are building the
6500 /// candidate type set.
6501 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006502
Douglas Gregora11693b2008-11-12 17:17:38 +00006503 /// Context - The AST context in which we will build the type sets.
6504 ASTContext &Context;
6505
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006506 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6507 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006508 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006509
6510public:
6511 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006512 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006513
Mike Stump11289f42009-09-09 15:08:12 +00006514 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006515 : HasNonRecordTypes(false),
6516 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006517 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006518 SemaRef(SemaRef),
6519 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006520
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006522 SourceLocation Loc,
6523 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006524 bool AllowExplicitConversions,
6525 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006526
6527 /// pointer_begin - First pointer type found;
6528 iterator pointer_begin() { return PointerTypes.begin(); }
6529
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006530 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006531 iterator pointer_end() { return PointerTypes.end(); }
6532
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006533 /// member_pointer_begin - First member pointer type found;
6534 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6535
6536 /// member_pointer_end - Past the last member pointer type found;
6537 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6538
Douglas Gregora11693b2008-11-12 17:17:38 +00006539 /// enumeration_begin - First enumeration type found;
6540 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6541
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006542 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006543 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006545 iterator vector_begin() { return VectorTypes.begin(); }
6546 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006547
6548 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6549 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006550 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006551};
6552
Craig Toppercd7b0332013-07-01 06:29:40 +00006553} // end anonymous namespace
6554
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006555/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006556/// the set of pointer types along with any more-qualified variants of
6557/// that type. For example, if @p Ty is "int const *", this routine
6558/// will add "int const *", "int const volatile *", "int const
6559/// restrict *", and "int const volatile restrict *" to the set of
6560/// pointer types. Returns true if the add of @p Ty itself succeeded,
6561/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006562///
6563/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006564bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006565BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6566 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006567
Douglas Gregora11693b2008-11-12 17:17:38 +00006568 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006569 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006570 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006571
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006572 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006573 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006574 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006575 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006576 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6577 PointeeTy = PTy->getPointeeType();
6578 buildObjCPtr = true;
6579 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006580 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006581 }
6582
Sebastian Redl4990a632009-11-18 20:39:26 +00006583 // Don't add qualified variants of arrays. For one, they're not allowed
6584 // (the qualifier would sink to the element type), and for another, the
6585 // only overload situation where it matters is subscript or pointer +- int,
6586 // and those shouldn't have qualifier variants anyway.
6587 if (PointeeTy->isArrayType())
6588 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006589
John McCall8ccfcb52009-09-24 19:53:00 +00006590 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006591 bool hasVolatile = VisibleQuals.hasVolatile();
6592 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006593
John McCall8ccfcb52009-09-24 19:53:00 +00006594 // Iterate through all strict supersets of BaseCVR.
6595 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6596 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006597 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006598 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006599
6600 // Skip over restrict if no restrict found anywhere in the types, or if
6601 // the type cannot be restrict-qualified.
6602 if ((CVR & Qualifiers::Restrict) &&
6603 (!hasRestrict ||
6604 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6605 continue;
6606
6607 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006608 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006609
6610 // Build qualified pointer type.
6611 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006612 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006613 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006614 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006615 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6616
6617 // Insert qualified pointer type.
6618 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006619 }
6620
6621 return true;
6622}
6623
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006624/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6625/// to the set of pointer types along with any more-qualified variants of
6626/// that type. For example, if @p Ty is "int const *", this routine
6627/// will add "int const *", "int const volatile *", "int const
6628/// restrict *", and "int const volatile restrict *" to the set of
6629/// pointer types. Returns true if the add of @p Ty itself succeeded,
6630/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006631///
6632/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006633bool
6634BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6635 QualType Ty) {
6636 // Insert this type.
6637 if (!MemberPointerTypes.insert(Ty))
6638 return false;
6639
John McCall8ccfcb52009-09-24 19:53:00 +00006640 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6641 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006642
John McCall8ccfcb52009-09-24 19:53:00 +00006643 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006644 // Don't add qualified variants of arrays. For one, they're not allowed
6645 // (the qualifier would sink to the element type), and for another, the
6646 // only overload situation where it matters is subscript or pointer +- int,
6647 // and those shouldn't have qualifier variants anyway.
6648 if (PointeeTy->isArrayType())
6649 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006650 const Type *ClassTy = PointerTy->getClass();
6651
6652 // Iterate through all strict supersets of the pointee type's CVR
6653 // qualifiers.
6654 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6655 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6656 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006657
John McCall8ccfcb52009-09-24 19:53:00 +00006658 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006659 MemberPointerTypes.insert(
6660 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006661 }
6662
6663 return true;
6664}
6665
Douglas Gregora11693b2008-11-12 17:17:38 +00006666/// AddTypesConvertedFrom - Add each of the types to which the type @p
6667/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006668/// primarily interested in pointer types and enumeration types. We also
6669/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006670/// AllowUserConversions is true if we should look at the conversion
6671/// functions of a class type, and AllowExplicitConversions if we
6672/// should also include the explicit conversion functions of a class
6673/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006674void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006675BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006676 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006677 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006678 bool AllowExplicitConversions,
6679 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006680 // Only deal with canonical types.
6681 Ty = Context.getCanonicalType(Ty);
6682
6683 // Look through reference types; they aren't part of the type of an
6684 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006685 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006686 Ty = RefTy->getPointeeType();
6687
John McCall33ddac02011-01-19 10:06:00 +00006688 // If we're dealing with an array type, decay to the pointer.
6689 if (Ty->isArrayType())
6690 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6691
6692 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006693 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006694
Chandler Carruth00a38332010-12-13 01:44:01 +00006695 // Flag if we ever add a non-record type.
6696 const RecordType *TyRec = Ty->getAs<RecordType>();
6697 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6698
Chandler Carruth00a38332010-12-13 01:44:01 +00006699 // Flag if we encounter an arithmetic type.
6700 HasArithmeticOrEnumeralTypes =
6701 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6702
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006703 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6704 PointerTypes.insert(Ty);
6705 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006706 // Insert our type, and its more-qualified variants, into the set
6707 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006708 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006709 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006710 } else if (Ty->isMemberPointerType()) {
6711 // Member pointers are far easier, since the pointee can't be converted.
6712 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6713 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006714 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006715 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006716 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006717 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006718 // We treat vector types as arithmetic types in many contexts as an
6719 // extension.
6720 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006721 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006722 } else if (Ty->isNullPtrType()) {
6723 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006724 } else if (AllowUserConversions && TyRec) {
6725 // No conversion functions in incomplete types.
6726 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6727 return;
Mike Stump11289f42009-09-09 15:08:12 +00006728
Chandler Carruth00a38332010-12-13 01:44:01 +00006729 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006730 std::pair<CXXRecordDecl::conversion_iterator,
6731 CXXRecordDecl::conversion_iterator>
6732 Conversions = ClassDecl->getVisibleConversionFunctions();
6733 for (CXXRecordDecl::conversion_iterator
6734 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006735 NamedDecl *D = I.getDecl();
6736 if (isa<UsingShadowDecl>(D))
6737 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006738
Chandler Carruth00a38332010-12-13 01:44:01 +00006739 // Skip conversion function templates; they don't tell us anything
6740 // about which builtin types we can convert to.
6741 if (isa<FunctionTemplateDecl>(D))
6742 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006743
Chandler Carruth00a38332010-12-13 01:44:01 +00006744 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6745 if (AllowExplicitConversions || !Conv->isExplicit()) {
6746 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6747 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006748 }
6749 }
6750 }
6751}
6752
Douglas Gregor84605ae2009-08-24 13:43:27 +00006753/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6754/// the volatile- and non-volatile-qualified assignment operators for the
6755/// given type to the candidate set.
6756static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6757 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006758 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006759 OverloadCandidateSet &CandidateSet) {
6760 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006761
Douglas Gregor84605ae2009-08-24 13:43:27 +00006762 // T& operator=(T&, T)
6763 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6764 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006765 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006766 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006767
Douglas Gregor84605ae2009-08-24 13:43:27 +00006768 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6769 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006770 ParamTypes[0]
6771 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006772 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006773 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006774 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006775 }
6776}
Mike Stump11289f42009-09-09 15:08:12 +00006777
Sebastian Redl1054fae2009-10-25 17:03:50 +00006778/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6779/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006780static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6781 Qualifiers VRQuals;
6782 const RecordType *TyRec;
6783 if (const MemberPointerType *RHSMPType =
6784 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006785 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006786 else
6787 TyRec = ArgExpr->getType()->getAs<RecordType>();
6788 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006789 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006790 VRQuals.addVolatile();
6791 VRQuals.addRestrict();
6792 return VRQuals;
6793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006794
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006795 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006796 if (!ClassDecl->hasDefinition())
6797 return VRQuals;
6798
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006799 std::pair<CXXRecordDecl::conversion_iterator,
6800 CXXRecordDecl::conversion_iterator>
6801 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006802
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006803 for (CXXRecordDecl::conversion_iterator
6804 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006805 NamedDecl *D = I.getDecl();
6806 if (isa<UsingShadowDecl>(D))
6807 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6808 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006809 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6810 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6811 CanTy = ResTypeRef->getPointeeType();
6812 // Need to go down the pointer/mempointer chain and add qualifiers
6813 // as see them.
6814 bool done = false;
6815 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006816 if (CanTy.isRestrictQualified())
6817 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006818 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6819 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006821 CanTy->getAs<MemberPointerType>())
6822 CanTy = ResTypeMPtr->getPointeeType();
6823 else
6824 done = true;
6825 if (CanTy.isVolatileQualified())
6826 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006827 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6828 return VRQuals;
6829 }
6830 }
6831 }
6832 return VRQuals;
6833}
John McCall52872982010-11-13 05:51:15 +00006834
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006835namespace {
John McCall52872982010-11-13 05:51:15 +00006836
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006837/// \brief Helper class to manage the addition of builtin operator overload
6838/// candidates. It provides shared state and utility methods used throughout
6839/// the process, as well as a helper method to add each group of builtin
6840/// operator overloads from the standard to a candidate set.
6841class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006842 // Common instance state available to all overload candidate addition methods.
6843 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006844 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006845 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006846 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006847 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006848 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006849
Chandler Carruthc6586e52010-12-12 10:35:00 +00006850 // Define some constants used to index and iterate over the arithemetic types
6851 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006852 // The "promoted arithmetic types" are the arithmetic
6853 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006854 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006855 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006856 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006857 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006858 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006859 LastPromotedArithmeticType = 11;
6860 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006861
Chandler Carruthc6586e52010-12-12 10:35:00 +00006862 /// \brief Get the canonical type for a given arithmetic type index.
6863 CanQualType getArithmeticType(unsigned index) {
6864 assert(index < NumArithmeticTypes);
6865 static CanQualType ASTContext::* const
6866 ArithmeticTypes[NumArithmeticTypes] = {
6867 // Start of promoted types.
6868 &ASTContext::FloatTy,
6869 &ASTContext::DoubleTy,
6870 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006871
Chandler Carruthc6586e52010-12-12 10:35:00 +00006872 // Start of integral types.
6873 &ASTContext::IntTy,
6874 &ASTContext::LongTy,
6875 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006876 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006877 &ASTContext::UnsignedIntTy,
6878 &ASTContext::UnsignedLongTy,
6879 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006880 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006881 // End of promoted types.
6882
6883 &ASTContext::BoolTy,
6884 &ASTContext::CharTy,
6885 &ASTContext::WCharTy,
6886 &ASTContext::Char16Ty,
6887 &ASTContext::Char32Ty,
6888 &ASTContext::SignedCharTy,
6889 &ASTContext::ShortTy,
6890 &ASTContext::UnsignedCharTy,
6891 &ASTContext::UnsignedShortTy,
6892 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006893 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006894 };
6895 return S.Context.*ArithmeticTypes[index];
6896 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006897
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006898 /// \brief Gets the canonical type resulting from the usual arithemetic
6899 /// converions for the given arithmetic types.
6900 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6901 // Accelerator table for performing the usual arithmetic conversions.
6902 // The rules are basically:
6903 // - if either is floating-point, use the wider floating-point
6904 // - if same signedness, use the higher rank
6905 // - if same size, use unsigned of the higher rank
6906 // - use the larger type
6907 // These rules, together with the axiom that higher ranks are
6908 // never smaller, are sufficient to precompute all of these results
6909 // *except* when dealing with signed types of higher rank.
6910 // (we could precompute SLL x UI for all known platforms, but it's
6911 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006912 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006913 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006914 Dep=-1,
6915 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006916 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006917 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006918 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006919/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6920/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6921/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6922/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6923/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6924/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6925/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6926/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6927/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6928/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6929/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006930 };
6931
6932 assert(L < LastPromotedArithmeticType);
6933 assert(R < LastPromotedArithmeticType);
6934 int Idx = ConversionsTable[L][R];
6935
6936 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006937 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006938
6939 // Slow path: we need to compare widths.
6940 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006941 CanQualType LT = getArithmeticType(L),
6942 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006943 unsigned LW = S.Context.getIntWidth(LT),
6944 RW = S.Context.getIntWidth(RT);
6945
6946 // If they're different widths, use the signed type.
6947 if (LW > RW) return LT;
6948 else if (LW < RW) return RT;
6949
6950 // Otherwise, use the unsigned type of the signed type's rank.
6951 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6952 assert(L == SLL || R == SLL);
6953 return S.Context.UnsignedLongLongTy;
6954 }
6955
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006956 /// \brief Helper method to factor out the common pattern of adding overloads
6957 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006958 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006959 bool HasVolatile,
6960 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006961 QualType ParamTypes[2] = {
6962 S.Context.getLValueReferenceType(CandidateTy),
6963 S.Context.IntTy
6964 };
6965
6966 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00006967 if (Args.size() == 1)
6968 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006969 else
Richard Smithe54c3072013-05-05 15:51:06 +00006970 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006971
6972 // Use a heuristic to reduce number of builtin candidates in the set:
6973 // add volatile version only if there are conversions to a volatile type.
6974 if (HasVolatile) {
6975 ParamTypes[0] =
6976 S.Context.getLValueReferenceType(
6977 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00006978 if (Args.size() == 1)
6979 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006980 else
Richard Smithe54c3072013-05-05 15:51:06 +00006981 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006982 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006983
6984 // Add restrict version only if there are conversions to a restrict type
6985 // and our candidate type is a non-restrict-qualified pointer.
6986 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6987 !CandidateTy.isRestrictQualified()) {
6988 ParamTypes[0]
6989 = S.Context.getLValueReferenceType(
6990 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00006991 if (Args.size() == 1)
6992 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006993 else
Richard Smithe54c3072013-05-05 15:51:06 +00006994 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006995
6996 if (HasVolatile) {
6997 ParamTypes[0]
6998 = S.Context.getLValueReferenceType(
6999 S.Context.getCVRQualifiedType(CandidateTy,
7000 (Qualifiers::Volatile |
7001 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007002 if (Args.size() == 1)
7003 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007004 else
Richard Smithe54c3072013-05-05 15:51:06 +00007005 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007006 }
7007 }
7008
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007009 }
7010
7011public:
7012 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007013 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007014 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007015 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007016 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007017 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007018 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007019 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007020 HasArithmeticOrEnumeralCandidateType(
7021 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007022 CandidateTypes(CandidateTypes),
7023 CandidateSet(CandidateSet) {
7024 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007025 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007026 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007027 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007028 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007029 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007030 assert(getArithmeticType(FirstPromotedArithmeticType)
7031 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007032 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007033 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007034 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007035 "Invalid last promoted arithmetic type");
7036 }
7037
7038 // C++ [over.built]p3:
7039 //
7040 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7041 // is either volatile or empty, there exist candidate operator
7042 // functions of the form
7043 //
7044 // VQ T& operator++(VQ T&);
7045 // T operator++(VQ T&, int);
7046 //
7047 // C++ [over.built]p4:
7048 //
7049 // For every pair (T, VQ), where T is an arithmetic type other
7050 // than bool, and VQ is either volatile or empty, there exist
7051 // candidate operator functions of the form
7052 //
7053 // VQ T& operator--(VQ T&);
7054 // T operator--(VQ T&, int);
7055 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007056 if (!HasArithmeticOrEnumeralCandidateType)
7057 return;
7058
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007059 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7060 Arith < NumArithmeticTypes; ++Arith) {
7061 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007062 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007063 VisibleTypeConversionsQuals.hasVolatile(),
7064 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007065 }
7066 }
7067
7068 // C++ [over.built]p5:
7069 //
7070 // For every pair (T, VQ), where T is a cv-qualified or
7071 // cv-unqualified object type, and VQ is either volatile or
7072 // empty, there exist candidate operator functions of the form
7073 //
7074 // T*VQ& operator++(T*VQ&);
7075 // T*VQ& operator--(T*VQ&);
7076 // T* operator++(T*VQ&, int);
7077 // T* operator--(T*VQ&, int);
7078 void addPlusPlusMinusMinusPointerOverloads() {
7079 for (BuiltinCandidateTypeSet::iterator
7080 Ptr = CandidateTypes[0].pointer_begin(),
7081 PtrEnd = CandidateTypes[0].pointer_end();
7082 Ptr != PtrEnd; ++Ptr) {
7083 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007084 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007085 continue;
7086
7087 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007088 (!(*Ptr).isVolatileQualified() &&
7089 VisibleTypeConversionsQuals.hasVolatile()),
7090 (!(*Ptr).isRestrictQualified() &&
7091 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007092 }
7093 }
7094
7095 // C++ [over.built]p6:
7096 // For every cv-qualified or cv-unqualified object type T, there
7097 // exist candidate operator functions of the form
7098 //
7099 // T& operator*(T*);
7100 //
7101 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007102 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007103 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007104 // T& operator*(T*);
7105 void addUnaryStarPointerOverloads() {
7106 for (BuiltinCandidateTypeSet::iterator
7107 Ptr = CandidateTypes[0].pointer_begin(),
7108 PtrEnd = CandidateTypes[0].pointer_end();
7109 Ptr != PtrEnd; ++Ptr) {
7110 QualType ParamTy = *Ptr;
7111 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007112 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7113 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007114
Douglas Gregor02824322011-01-26 19:30:28 +00007115 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7116 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7117 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007118
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007119 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007120 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007121 }
7122 }
7123
7124 // C++ [over.built]p9:
7125 // For every promoted arithmetic type T, there exist candidate
7126 // operator functions of the form
7127 //
7128 // T operator+(T);
7129 // T operator-(T);
7130 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007131 if (!HasArithmeticOrEnumeralCandidateType)
7132 return;
7133
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007134 for (unsigned Arith = FirstPromotedArithmeticType;
7135 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007136 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007137 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007138 }
7139
7140 // Extension: We also add these operators for vector types.
7141 for (BuiltinCandidateTypeSet::iterator
7142 Vec = CandidateTypes[0].vector_begin(),
7143 VecEnd = CandidateTypes[0].vector_end();
7144 Vec != VecEnd; ++Vec) {
7145 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007146 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007147 }
7148 }
7149
7150 // C++ [over.built]p8:
7151 // For every type T, there exist candidate operator functions of
7152 // the form
7153 //
7154 // T* operator+(T*);
7155 void addUnaryPlusPointerOverloads() {
7156 for (BuiltinCandidateTypeSet::iterator
7157 Ptr = CandidateTypes[0].pointer_begin(),
7158 PtrEnd = CandidateTypes[0].pointer_end();
7159 Ptr != PtrEnd; ++Ptr) {
7160 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007161 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007162 }
7163 }
7164
7165 // C++ [over.built]p10:
7166 // For every promoted integral type T, there exist candidate
7167 // operator functions of the form
7168 //
7169 // T operator~(T);
7170 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007171 if (!HasArithmeticOrEnumeralCandidateType)
7172 return;
7173
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007174 for (unsigned Int = FirstPromotedIntegralType;
7175 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007176 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007177 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007178 }
7179
7180 // Extension: We also add this operator for vector types.
7181 for (BuiltinCandidateTypeSet::iterator
7182 Vec = CandidateTypes[0].vector_begin(),
7183 VecEnd = CandidateTypes[0].vector_end();
7184 Vec != VecEnd; ++Vec) {
7185 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007186 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007187 }
7188 }
7189
7190 // C++ [over.match.oper]p16:
7191 // For every pointer to member type T, there exist candidate operator
7192 // functions of the form
7193 //
7194 // bool operator==(T,T);
7195 // bool operator!=(T,T);
7196 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7197 /// Set of (canonical) types that we've already handled.
7198 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7199
Richard Smithe54c3072013-05-05 15:51:06 +00007200 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007201 for (BuiltinCandidateTypeSet::iterator
7202 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7203 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7204 MemPtr != MemPtrEnd;
7205 ++MemPtr) {
7206 // Don't add the same builtin candidate twice.
7207 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7208 continue;
7209
7210 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007211 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007212 }
7213 }
7214 }
7215
7216 // C++ [over.built]p15:
7217 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007218 // For every T, where T is an enumeration type, a pointer type, or
7219 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007220 //
7221 // bool operator<(T, T);
7222 // bool operator>(T, T);
7223 // bool operator<=(T, T);
7224 // bool operator>=(T, T);
7225 // bool operator==(T, T);
7226 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007227 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007228 // C++ [over.match.oper]p3:
7229 // [...]the built-in candidates include all of the candidate operator
7230 // functions defined in 13.6 that, compared to the given operator, [...]
7231 // do not have the same parameter-type-list as any non-template non-member
7232 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007233 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007234 // Note that in practice, this only affects enumeration types because there
7235 // aren't any built-in candidates of record type, and a user-defined operator
7236 // must have an operand of record or enumeration type. Also, the only other
7237 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007238 // cannot be overloaded for enumeration types, so this is the only place
7239 // where we must suppress candidates like this.
7240 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7241 UserDefinedBinaryOperators;
7242
Richard Smithe54c3072013-05-05 15:51:06 +00007243 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007244 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7245 CandidateTypes[ArgIdx].enumeration_end()) {
7246 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7247 CEnd = CandidateSet.end();
7248 C != CEnd; ++C) {
7249 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7250 continue;
7251
Eli Friedman14f082b2012-09-18 21:52:24 +00007252 if (C->Function->isFunctionTemplateSpecialization())
7253 continue;
7254
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007255 QualType FirstParamType =
7256 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7257 QualType SecondParamType =
7258 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7259
7260 // Skip if either parameter isn't of enumeral type.
7261 if (!FirstParamType->isEnumeralType() ||
7262 !SecondParamType->isEnumeralType())
7263 continue;
7264
7265 // Add this operator to the set of known user-defined operators.
7266 UserDefinedBinaryOperators.insert(
7267 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7268 S.Context.getCanonicalType(SecondParamType)));
7269 }
7270 }
7271 }
7272
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007273 /// Set of (canonical) types that we've already handled.
7274 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7275
Richard Smithe54c3072013-05-05 15:51:06 +00007276 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007277 for (BuiltinCandidateTypeSet::iterator
7278 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7279 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7280 Ptr != PtrEnd; ++Ptr) {
7281 // Don't add the same builtin candidate twice.
7282 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7283 continue;
7284
7285 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007286 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007287 }
7288 for (BuiltinCandidateTypeSet::iterator
7289 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7290 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7291 Enum != EnumEnd; ++Enum) {
7292 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7293
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007294 // Don't add the same builtin candidate twice, or if a user defined
7295 // candidate exists.
7296 if (!AddedTypes.insert(CanonType) ||
7297 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7298 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007299 continue;
7300
7301 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007302 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007303 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007304
7305 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7306 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7307 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007308 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007309 NullPtrTy))) {
7310 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007311 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007312 CandidateSet);
7313 }
7314 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007315 }
7316 }
7317
7318 // C++ [over.built]p13:
7319 //
7320 // For every cv-qualified or cv-unqualified object type T
7321 // there exist candidate operator functions of the form
7322 //
7323 // T* operator+(T*, ptrdiff_t);
7324 // T& operator[](T*, ptrdiff_t); [BELOW]
7325 // T* operator-(T*, ptrdiff_t);
7326 // T* operator+(ptrdiff_t, T*);
7327 // T& operator[](ptrdiff_t, T*); [BELOW]
7328 //
7329 // C++ [over.built]p14:
7330 //
7331 // For every T, where T is a pointer to object type, there
7332 // exist candidate operator functions of the form
7333 //
7334 // ptrdiff_t operator-(T, T);
7335 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7336 /// Set of (canonical) types that we've already handled.
7337 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7338
7339 for (int Arg = 0; Arg < 2; ++Arg) {
7340 QualType AsymetricParamTypes[2] = {
7341 S.Context.getPointerDiffType(),
7342 S.Context.getPointerDiffType(),
7343 };
7344 for (BuiltinCandidateTypeSet::iterator
7345 Ptr = CandidateTypes[Arg].pointer_begin(),
7346 PtrEnd = CandidateTypes[Arg].pointer_end();
7347 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007348 QualType PointeeTy = (*Ptr)->getPointeeType();
7349 if (!PointeeTy->isObjectType())
7350 continue;
7351
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007352 AsymetricParamTypes[Arg] = *Ptr;
7353 if (Arg == 0 || Op == OO_Plus) {
7354 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7355 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007356 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007357 }
7358 if (Op == OO_Minus) {
7359 // ptrdiff_t operator-(T, T);
7360 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7361 continue;
7362
7363 QualType ParamTypes[2] = { *Ptr, *Ptr };
7364 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007365 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007366 }
7367 }
7368 }
7369 }
7370
7371 // C++ [over.built]p12:
7372 //
7373 // For every pair of promoted arithmetic types L and R, there
7374 // exist candidate operator functions of the form
7375 //
7376 // LR operator*(L, R);
7377 // LR operator/(L, R);
7378 // LR operator+(L, R);
7379 // LR operator-(L, R);
7380 // bool operator<(L, R);
7381 // bool operator>(L, R);
7382 // bool operator<=(L, R);
7383 // bool operator>=(L, R);
7384 // bool operator==(L, R);
7385 // bool operator!=(L, R);
7386 //
7387 // where LR is the result of the usual arithmetic conversions
7388 // between types L and R.
7389 //
7390 // C++ [over.built]p24:
7391 //
7392 // For every pair of promoted arithmetic types L and R, there exist
7393 // candidate operator functions of the form
7394 //
7395 // LR operator?(bool, L, R);
7396 //
7397 // where LR is the result of the usual arithmetic conversions
7398 // between types L and R.
7399 // Our candidates ignore the first parameter.
7400 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007401 if (!HasArithmeticOrEnumeralCandidateType)
7402 return;
7403
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007404 for (unsigned Left = FirstPromotedArithmeticType;
7405 Left < LastPromotedArithmeticType; ++Left) {
7406 for (unsigned Right = FirstPromotedArithmeticType;
7407 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007408 QualType LandR[2] = { getArithmeticType(Left),
7409 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007410 QualType Result =
7411 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007412 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007413 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007414 }
7415 }
7416
7417 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7418 // conditional operator for vector types.
7419 for (BuiltinCandidateTypeSet::iterator
7420 Vec1 = CandidateTypes[0].vector_begin(),
7421 Vec1End = CandidateTypes[0].vector_end();
7422 Vec1 != Vec1End; ++Vec1) {
7423 for (BuiltinCandidateTypeSet::iterator
7424 Vec2 = CandidateTypes[1].vector_begin(),
7425 Vec2End = CandidateTypes[1].vector_end();
7426 Vec2 != Vec2End; ++Vec2) {
7427 QualType LandR[2] = { *Vec1, *Vec2 };
7428 QualType Result = S.Context.BoolTy;
7429 if (!isComparison) {
7430 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7431 Result = *Vec1;
7432 else
7433 Result = *Vec2;
7434 }
7435
Richard Smithe54c3072013-05-05 15:51:06 +00007436 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007437 }
7438 }
7439 }
7440
7441 // C++ [over.built]p17:
7442 //
7443 // For every pair of promoted integral types L and R, there
7444 // exist candidate operator functions of the form
7445 //
7446 // LR operator%(L, R);
7447 // LR operator&(L, R);
7448 // LR operator^(L, R);
7449 // LR operator|(L, R);
7450 // L operator<<(L, R);
7451 // L operator>>(L, R);
7452 //
7453 // where LR is the result of the usual arithmetic conversions
7454 // between types L and R.
7455 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007456 if (!HasArithmeticOrEnumeralCandidateType)
7457 return;
7458
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007459 for (unsigned Left = FirstPromotedIntegralType;
7460 Left < LastPromotedIntegralType; ++Left) {
7461 for (unsigned Right = FirstPromotedIntegralType;
7462 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007463 QualType LandR[2] = { getArithmeticType(Left),
7464 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007465 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7466 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007467 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007468 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007469 }
7470 }
7471 }
7472
7473 // C++ [over.built]p20:
7474 //
7475 // For every pair (T, VQ), where T is an enumeration or
7476 // pointer to member type and VQ is either volatile or
7477 // empty, there exist candidate operator functions of the form
7478 //
7479 // VQ T& operator=(VQ T&, T);
7480 void addAssignmentMemberPointerOrEnumeralOverloads() {
7481 /// Set of (canonical) types that we've already handled.
7482 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7483
7484 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7485 for (BuiltinCandidateTypeSet::iterator
7486 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7487 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7488 Enum != EnumEnd; ++Enum) {
7489 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7490 continue;
7491
Richard Smithe54c3072013-05-05 15:51:06 +00007492 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007493 }
7494
7495 for (BuiltinCandidateTypeSet::iterator
7496 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7497 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7498 MemPtr != MemPtrEnd; ++MemPtr) {
7499 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7500 continue;
7501
Richard Smithe54c3072013-05-05 15:51:06 +00007502 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007503 }
7504 }
7505 }
7506
7507 // C++ [over.built]p19:
7508 //
7509 // For every pair (T, VQ), where T is any type and VQ is either
7510 // volatile or empty, there exist candidate operator functions
7511 // of the form
7512 //
7513 // T*VQ& operator=(T*VQ&, T*);
7514 //
7515 // C++ [over.built]p21:
7516 //
7517 // For every pair (T, VQ), where T is a cv-qualified or
7518 // cv-unqualified object type and VQ is either volatile or
7519 // empty, there exist candidate operator functions of the form
7520 //
7521 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7522 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7523 void addAssignmentPointerOverloads(bool isEqualOp) {
7524 /// Set of (canonical) types that we've already handled.
7525 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7526
7527 for (BuiltinCandidateTypeSet::iterator
7528 Ptr = CandidateTypes[0].pointer_begin(),
7529 PtrEnd = CandidateTypes[0].pointer_end();
7530 Ptr != PtrEnd; ++Ptr) {
7531 // If this is operator=, keep track of the builtin candidates we added.
7532 if (isEqualOp)
7533 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007534 else if (!(*Ptr)->getPointeeType()->isObjectType())
7535 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007536
7537 // non-volatile version
7538 QualType ParamTypes[2] = {
7539 S.Context.getLValueReferenceType(*Ptr),
7540 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7541 };
Richard Smithe54c3072013-05-05 15:51:06 +00007542 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007543 /*IsAssigmentOperator=*/ isEqualOp);
7544
Douglas Gregor5bee2582012-06-04 00:15:09 +00007545 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7546 VisibleTypeConversionsQuals.hasVolatile();
7547 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007548 // volatile version
7549 ParamTypes[0] =
7550 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007551 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007552 /*IsAssigmentOperator=*/isEqualOp);
7553 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007554
7555 if (!(*Ptr).isRestrictQualified() &&
7556 VisibleTypeConversionsQuals.hasRestrict()) {
7557 // restrict version
7558 ParamTypes[0]
7559 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
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 if (NeedVolatile) {
7564 // volatile restrict version
7565 ParamTypes[0]
7566 = S.Context.getLValueReferenceType(
7567 S.Context.getCVRQualifiedType(*Ptr,
7568 (Qualifiers::Volatile |
7569 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007570 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007571 /*IsAssigmentOperator=*/isEqualOp);
7572 }
7573 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007574 }
7575
7576 if (isEqualOp) {
7577 for (BuiltinCandidateTypeSet::iterator
7578 Ptr = CandidateTypes[1].pointer_begin(),
7579 PtrEnd = CandidateTypes[1].pointer_end();
7580 Ptr != PtrEnd; ++Ptr) {
7581 // Make sure we don't add the same candidate twice.
7582 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7583 continue;
7584
Chandler Carruth8e543b32010-12-12 08:17:55 +00007585 QualType ParamTypes[2] = {
7586 S.Context.getLValueReferenceType(*Ptr),
7587 *Ptr,
7588 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007589
7590 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007591 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 /*IsAssigmentOperator=*/true);
7593
Douglas Gregor5bee2582012-06-04 00:15:09 +00007594 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7595 VisibleTypeConversionsQuals.hasVolatile();
7596 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007597 // volatile version
7598 ParamTypes[0] =
7599 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007600 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7601 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007602 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007603
7604 if (!(*Ptr).isRestrictQualified() &&
7605 VisibleTypeConversionsQuals.hasRestrict()) {
7606 // restrict version
7607 ParamTypes[0]
7608 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
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 if (NeedVolatile) {
7613 // volatile restrict version
7614 ParamTypes[0]
7615 = S.Context.getLValueReferenceType(
7616 S.Context.getCVRQualifiedType(*Ptr,
7617 (Qualifiers::Volatile |
7618 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007619 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7620 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007621 }
7622 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007623 }
7624 }
7625 }
7626
7627 // C++ [over.built]p18:
7628 //
7629 // For every triple (L, VQ, R), where L is an arithmetic type,
7630 // VQ is either volatile or empty, and R is a promoted
7631 // arithmetic type, there exist candidate operator functions of
7632 // the form
7633 //
7634 // VQ L& operator=(VQ L&, R);
7635 // VQ L& operator*=(VQ L&, R);
7636 // VQ L& operator/=(VQ L&, R);
7637 // VQ L& operator+=(VQ L&, R);
7638 // VQ L& operator-=(VQ L&, R);
7639 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007640 if (!HasArithmeticOrEnumeralCandidateType)
7641 return;
7642
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007643 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7644 for (unsigned Right = FirstPromotedArithmeticType;
7645 Right < LastPromotedArithmeticType; ++Right) {
7646 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007647 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007648
7649 // Add this built-in operator as a candidate (VQ is empty).
7650 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007651 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007652 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007653 /*IsAssigmentOperator=*/isEqualOp);
7654
7655 // Add this built-in operator as a candidate (VQ is 'volatile').
7656 if (VisibleTypeConversionsQuals.hasVolatile()) {
7657 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007658 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007660 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007661 /*IsAssigmentOperator=*/isEqualOp);
7662 }
7663 }
7664 }
7665
7666 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7667 for (BuiltinCandidateTypeSet::iterator
7668 Vec1 = CandidateTypes[0].vector_begin(),
7669 Vec1End = CandidateTypes[0].vector_end();
7670 Vec1 != Vec1End; ++Vec1) {
7671 for (BuiltinCandidateTypeSet::iterator
7672 Vec2 = CandidateTypes[1].vector_begin(),
7673 Vec2End = CandidateTypes[1].vector_end();
7674 Vec2 != Vec2End; ++Vec2) {
7675 QualType ParamTypes[2];
7676 ParamTypes[1] = *Vec2;
7677 // Add this built-in operator as a candidate (VQ is empty).
7678 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007679 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007680 /*IsAssigmentOperator=*/isEqualOp);
7681
7682 // Add this built-in operator as a candidate (VQ is 'volatile').
7683 if (VisibleTypeConversionsQuals.hasVolatile()) {
7684 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7685 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007686 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007687 /*IsAssigmentOperator=*/isEqualOp);
7688 }
7689 }
7690 }
7691 }
7692
7693 // C++ [over.built]p22:
7694 //
7695 // For every triple (L, VQ, R), where L is an integral type, VQ
7696 // is either volatile or empty, and R is a promoted integral
7697 // type, there exist candidate operator functions of the form
7698 //
7699 // VQ L& operator%=(VQ L&, R);
7700 // VQ L& operator<<=(VQ L&, R);
7701 // VQ L& operator>>=(VQ L&, R);
7702 // VQ L& operator&=(VQ L&, R);
7703 // VQ L& operator^=(VQ L&, R);
7704 // VQ L& operator|=(VQ L&, R);
7705 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007706 if (!HasArithmeticOrEnumeralCandidateType)
7707 return;
7708
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007709 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7710 for (unsigned Right = FirstPromotedIntegralType;
7711 Right < LastPromotedIntegralType; ++Right) {
7712 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007713 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007714
7715 // Add this built-in operator as a candidate (VQ is empty).
7716 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007717 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007719 if (VisibleTypeConversionsQuals.hasVolatile()) {
7720 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007721 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007722 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7723 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007724 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007725 }
7726 }
7727 }
7728 }
7729
7730 // C++ [over.operator]p23:
7731 //
7732 // There also exist candidate operator functions of the form
7733 //
7734 // bool operator!(bool);
7735 // bool operator&&(bool, bool);
7736 // bool operator||(bool, bool);
7737 void addExclaimOverload() {
7738 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007739 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007740 /*IsAssignmentOperator=*/false,
7741 /*NumContextualBoolArguments=*/1);
7742 }
7743 void addAmpAmpOrPipePipeOverload() {
7744 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007745 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007746 /*IsAssignmentOperator=*/false,
7747 /*NumContextualBoolArguments=*/2);
7748 }
7749
7750 // C++ [over.built]p13:
7751 //
7752 // For every cv-qualified or cv-unqualified object type T there
7753 // exist candidate operator functions of the form
7754 //
7755 // T* operator+(T*, ptrdiff_t); [ABOVE]
7756 // T& operator[](T*, ptrdiff_t);
7757 // T* operator-(T*, ptrdiff_t); [ABOVE]
7758 // T* operator+(ptrdiff_t, T*); [ABOVE]
7759 // T& operator[](ptrdiff_t, T*);
7760 void addSubscriptOverloads() {
7761 for (BuiltinCandidateTypeSet::iterator
7762 Ptr = CandidateTypes[0].pointer_begin(),
7763 PtrEnd = CandidateTypes[0].pointer_end();
7764 Ptr != PtrEnd; ++Ptr) {
7765 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7766 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007767 if (!PointeeType->isObjectType())
7768 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007769
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007770 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7771
7772 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007773 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007774 }
7775
7776 for (BuiltinCandidateTypeSet::iterator
7777 Ptr = CandidateTypes[1].pointer_begin(),
7778 PtrEnd = CandidateTypes[1].pointer_end();
7779 Ptr != PtrEnd; ++Ptr) {
7780 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7781 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007782 if (!PointeeType->isObjectType())
7783 continue;
7784
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007785 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7786
7787 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007788 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007789 }
7790 }
7791
7792 // C++ [over.built]p11:
7793 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7794 // C1 is the same type as C2 or is a derived class of C2, T is an object
7795 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7796 // there exist candidate operator functions of the form
7797 //
7798 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7799 //
7800 // where CV12 is the union of CV1 and CV2.
7801 void addArrowStarOverloads() {
7802 for (BuiltinCandidateTypeSet::iterator
7803 Ptr = CandidateTypes[0].pointer_begin(),
7804 PtrEnd = CandidateTypes[0].pointer_end();
7805 Ptr != PtrEnd; ++Ptr) {
7806 QualType C1Ty = (*Ptr);
7807 QualType C1;
7808 QualifierCollector Q1;
7809 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7810 if (!isa<RecordType>(C1))
7811 continue;
7812 // heuristic to reduce number of builtin candidates in the set.
7813 // Add volatile/restrict version only if there are conversions to a
7814 // volatile/restrict type.
7815 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7816 continue;
7817 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7818 continue;
7819 for (BuiltinCandidateTypeSet::iterator
7820 MemPtr = CandidateTypes[1].member_pointer_begin(),
7821 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7822 MemPtr != MemPtrEnd; ++MemPtr) {
7823 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7824 QualType C2 = QualType(mptr->getClass(), 0);
7825 C2 = C2.getUnqualifiedType();
7826 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7827 break;
7828 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7829 // build CV12 T&
7830 QualType T = mptr->getPointeeType();
7831 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7832 T.isVolatileQualified())
7833 continue;
7834 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7835 T.isRestrictQualified())
7836 continue;
7837 T = Q1.apply(S.Context, T);
7838 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007839 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007840 }
7841 }
7842 }
7843
7844 // Note that we don't consider the first argument, since it has been
7845 // contextually converted to bool long ago. The candidates below are
7846 // therefore added as binary.
7847 //
7848 // C++ [over.built]p25:
7849 // For every type T, where T is a pointer, pointer-to-member, or scoped
7850 // enumeration type, there exist candidate operator functions of the form
7851 //
7852 // T operator?(bool, T, T);
7853 //
7854 void addConditionalOperatorOverloads() {
7855 /// Set of (canonical) types that we've already handled.
7856 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7857
7858 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7859 for (BuiltinCandidateTypeSet::iterator
7860 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7861 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7862 Ptr != PtrEnd; ++Ptr) {
7863 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7864 continue;
7865
7866 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007867 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007868 }
7869
7870 for (BuiltinCandidateTypeSet::iterator
7871 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7872 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7873 MemPtr != MemPtrEnd; ++MemPtr) {
7874 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7875 continue;
7876
7877 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007878 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007879 }
7880
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007881 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007882 for (BuiltinCandidateTypeSet::iterator
7883 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7884 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7885 Enum != EnumEnd; ++Enum) {
7886 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7887 continue;
7888
7889 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7890 continue;
7891
7892 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007893 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007894 }
7895 }
7896 }
7897 }
7898};
7899
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007900} // end anonymous namespace
7901
7902/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7903/// operator overloads to the candidate set (C++ [over.built]), based
7904/// on the operator @p Op and the arguments given. For example, if the
7905/// operator is a binary '+', this routine might add "int
7906/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00007907void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7908 SourceLocation OpLoc,
7909 ArrayRef<Expr *> Args,
7910 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007911 // Find all of the types that the arguments can convert to, but only
7912 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007913 // that make use of these types. Also record whether we encounter non-record
7914 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007915 Qualifiers VisibleTypeConversionsQuals;
7916 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00007917 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007918 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007919
7920 bool HasNonRecordCandidateType = false;
7921 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007922 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00007923 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007924 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7925 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7926 OpLoc,
7927 true,
7928 (Op == OO_Exclaim ||
7929 Op == OO_AmpAmp ||
7930 Op == OO_PipePipe),
7931 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007932 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7933 CandidateTypes[ArgIdx].hasNonRecordTypes();
7934 HasArithmeticOrEnumeralCandidateType =
7935 HasArithmeticOrEnumeralCandidateType ||
7936 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007937 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007938
Chandler Carruth00a38332010-12-13 01:44:01 +00007939 // Exit early when no non-record types have been added to the candidate set
7940 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007941 //
7942 // We can't exit early for !, ||, or &&, since there we have always have
7943 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007944 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007945 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007946 return;
7947
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007948 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007949 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007951 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007952 CandidateTypes, CandidateSet);
7953
7954 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007955 switch (Op) {
7956 case OO_None:
7957 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007958 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007959
Chandler Carruth5184de02010-12-12 08:51:33 +00007960 case OO_New:
7961 case OO_Delete:
7962 case OO_Array_New:
7963 case OO_Array_Delete:
7964 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007965 llvm_unreachable(
7966 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007967
7968 case OO_Comma:
7969 case OO_Arrow:
7970 // C++ [over.match.oper]p3:
7971 // -- For the operator ',', the unary operator '&', or the
7972 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007973 break;
7974
7975 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007976 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007978 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007979
7980 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007981 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007982 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007983 } else {
7984 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7985 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7986 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007987 break;
7988
Chandler Carruth5184de02010-12-12 08:51:33 +00007989 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007990 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007991 OpBuilder.addUnaryStarPointerOverloads();
7992 else
7993 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7994 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007995
Chandler Carruth5184de02010-12-12 08:51:33 +00007996 case OO_Slash:
7997 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007998 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007999
8000 case OO_PlusPlus:
8001 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008002 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8003 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008004 break;
8005
Douglas Gregor84605ae2009-08-24 13:43:27 +00008006 case OO_EqualEqual:
8007 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008008 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008009 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008010
Douglas Gregora11693b2008-11-12 17:17:38 +00008011 case OO_Less:
8012 case OO_Greater:
8013 case OO_LessEqual:
8014 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008015 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008016 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8017 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008018
Douglas Gregora11693b2008-11-12 17:17:38 +00008019 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008020 case OO_Caret:
8021 case OO_Pipe:
8022 case OO_LessLess:
8023 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008024 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008025 break;
8026
Chandler Carruth5184de02010-12-12 08:51:33 +00008027 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008028 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008029 // C++ [over.match.oper]p3:
8030 // -- For the operator ',', the unary operator '&', or the
8031 // operator '->', the built-in candidates set is empty.
8032 break;
8033
8034 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8035 break;
8036
8037 case OO_Tilde:
8038 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8039 break;
8040
Douglas Gregora11693b2008-11-12 17:17:38 +00008041 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008042 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008043 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008044
8045 case OO_PlusEqual:
8046 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008047 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008048 // Fall through.
8049
8050 case OO_StarEqual:
8051 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008052 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008053 break;
8054
8055 case OO_PercentEqual:
8056 case OO_LessLessEqual:
8057 case OO_GreaterGreaterEqual:
8058 case OO_AmpEqual:
8059 case OO_CaretEqual:
8060 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008061 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008062 break;
8063
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008064 case OO_Exclaim:
8065 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008066 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008067
Douglas Gregora11693b2008-11-12 17:17:38 +00008068 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 case OO_PipePipe:
8070 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008071 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008072
8073 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008074 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008075 break;
8076
8077 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008078 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008079 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008080
8081 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008082 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008083 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8084 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008085 }
8086}
8087
Douglas Gregore254f902009-02-04 00:32:51 +00008088/// \brief Add function candidates found via argument-dependent lookup
8089/// to the set of overloading candidates.
8090///
8091/// This routine performs argument-dependent name lookup based on the
8092/// given function name (which may also be an operator name) and adds
8093/// all of the overload candidates found by ADL to the overload
8094/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008095void
Douglas Gregore254f902009-02-04 00:32:51 +00008096Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00008097 bool Operator, SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008098 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008099 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008100 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008101 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008102 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008103
John McCall91f61fc2010-01-26 06:04:06 +00008104 // FIXME: This approach for uniquing ADL results (and removing
8105 // redundant candidates from the set) relies on pointer-equality,
8106 // which means we need to key off the canonical decl. However,
8107 // always going back to the canonical decl might not get us the
8108 // right set of default arguments. What default arguments are
8109 // we supposed to consider on ADL candidates, anyway?
8110
Douglas Gregorcabea402009-09-22 15:41:20 +00008111 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00008112 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008113
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008114 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008115 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8116 CandEnd = CandidateSet.end();
8117 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008118 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008119 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008120 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008121 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008122 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008123
8124 // For each of the ADL candidates we found, add it to the overload
8125 // set.
John McCall8fe68082010-01-26 07:16:45 +00008126 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008127 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008128 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008129 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008130 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008131
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008132 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8133 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008134 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008135 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008136 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008137 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008138 }
Douglas Gregore254f902009-02-04 00:32:51 +00008139}
8140
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008141/// isBetterOverloadCandidate - Determines whether the first overload
8142/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008143bool
John McCall5c32be02010-08-24 20:38:10 +00008144isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008145 const OverloadCandidate &Cand1,
8146 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008147 SourceLocation Loc,
8148 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008149 // Define viable functions to be better candidates than non-viable
8150 // functions.
8151 if (!Cand2.Viable)
8152 return Cand1.Viable;
8153 else if (!Cand1.Viable)
8154 return false;
8155
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008156 // C++ [over.match.best]p1:
8157 //
8158 // -- if F is a static member function, ICS1(F) is defined such
8159 // that ICS1(F) is neither better nor worse than ICS1(G) for
8160 // any function G, and, symmetrically, ICS1(G) is neither
8161 // better nor worse than ICS1(F).
8162 unsigned StartArg = 0;
8163 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8164 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008165
Douglas Gregord3cb3562009-07-07 23:38:56 +00008166 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008167 // A viable function F1 is defined to be a better function than another
8168 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008169 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008170 unsigned NumArgs = Cand1.NumConversions;
8171 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008172 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008173 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008174 switch (CompareImplicitConversionSequences(S,
8175 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008176 Cand2.Conversions[ArgIdx])) {
8177 case ImplicitConversionSequence::Better:
8178 // Cand1 has a better conversion sequence.
8179 HasBetterConversion = true;
8180 break;
8181
8182 case ImplicitConversionSequence::Worse:
8183 // Cand1 can't be better than Cand2.
8184 return false;
8185
8186 case ImplicitConversionSequence::Indistinguishable:
8187 // Do nothing.
8188 break;
8189 }
8190 }
8191
Mike Stump11289f42009-09-09 15:08:12 +00008192 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008193 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008194 if (HasBetterConversion)
8195 return true;
8196
Mike Stump11289f42009-09-09 15:08:12 +00008197 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00008198 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00008199 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00008200 Cand2.Function && Cand2.Function->getPrimaryTemplate())
8201 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008202
8203 // -- F1 and F2 are function template specializations, and the function
8204 // template for F1 is more specialized than the template for F2
8205 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00008206 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00008207 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00008208 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00008209 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00008210 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8211 Cand2.Function->getPrimaryTemplate(),
8212 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008213 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00008214 : TPOC_Call,
Richard Smithe5b52202013-09-11 00:52:39 +00008215 Cand1.ExplicitCallArguments,
8216 Cand2.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00008217 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00008218 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008219
Douglas Gregora1f013e2008-11-07 22:36:19 +00008220 // -- the context is an initialization by user-defined conversion
8221 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8222 // from the return type of F1 to the destination type (i.e.,
8223 // the type of the entity being initialized) is a better
8224 // conversion sequence than the standard conversion sequence
8225 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008226 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008227 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008228 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008229 // First check whether we prefer one of the conversion functions over the
8230 // other. This only distinguishes the results in non-standard, extension
8231 // cases such as the conversion from a lambda closure type to a function
8232 // pointer or block.
8233 ImplicitConversionSequence::CompareKind FuncResult
8234 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8235 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8236 return FuncResult;
8237
John McCall5c32be02010-08-24 20:38:10 +00008238 switch (CompareStandardConversionSequences(S,
8239 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00008240 Cand2.FinalConversion)) {
8241 case ImplicitConversionSequence::Better:
8242 // Cand1 has a better conversion sequence.
8243 return true;
8244
8245 case ImplicitConversionSequence::Worse:
8246 // Cand1 can't be better than Cand2.
8247 return false;
8248
8249 case ImplicitConversionSequence::Indistinguishable:
8250 // Do nothing
8251 break;
8252 }
8253 }
8254
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008255 // Check for enable_if value-based overload resolution.
8256 if (Cand1.Function && Cand2.Function &&
8257 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8258 Cand2.Function->hasAttr<EnableIfAttr>())) {
8259 // FIXME: The next several lines are just
8260 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8261 // instead of reverse order which is how they're stored in the AST.
8262 AttrVec Cand1Attrs;
8263 AttrVec::iterator Cand1E = Cand1Attrs.end();
8264 if (Cand1.Function->hasAttrs()) {
8265 Cand1Attrs = Cand1.Function->getAttrs();
8266 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8267 IsNotEnableIfAttr);
8268 std::reverse(Cand1Attrs.begin(), Cand1E);
8269 }
8270
8271 AttrVec Cand2Attrs;
8272 AttrVec::iterator Cand2E = Cand2Attrs.end();
8273 if (Cand2.Function->hasAttrs()) {
8274 Cand2Attrs = Cand2.Function->getAttrs();
8275 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8276 IsNotEnableIfAttr);
8277 std::reverse(Cand2Attrs.begin(), Cand2E);
8278 }
8279 for (AttrVec::iterator
8280 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin();
8281 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) {
8282 if (Cand1I == Cand1E)
8283 return false;
8284 if (Cand2I == Cand2E)
8285 return true;
8286 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8287 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID,
8288 S.getASTContext(), true);
8289 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID,
8290 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008291 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008292 return false;
8293 }
8294 }
8295
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008296 return false;
8297}
8298
Mike Stump11289f42009-09-09 15:08:12 +00008299/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008300/// within an overload candidate set.
8301///
James Dennettffad8b72012-06-22 08:10:18 +00008302/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008303/// which overload resolution occurs.
8304///
James Dennettffad8b72012-06-22 08:10:18 +00008305/// \param Best If overload resolution was successful or found a deleted
8306/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008307///
8308/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008309OverloadingResult
8310OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008311 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008312 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008313 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008314 Best = end();
8315 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8316 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008317 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008318 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008319 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008320 }
8321
8322 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008323 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008324 return OR_No_Viable_Function;
8325
8326 // Make sure that this function is better than every other viable
8327 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008328 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008329 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008330 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008331 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008332 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008333 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008334 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008335 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008336 }
Mike Stump11289f42009-09-09 15:08:12 +00008337
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008338 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008339 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008340 (Best->Function->isDeleted() ||
8341 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008342 return OR_Deleted;
8343
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008344 return OR_Success;
8345}
8346
John McCall53262c92010-01-12 02:15:36 +00008347namespace {
8348
8349enum OverloadCandidateKind {
8350 oc_function,
8351 oc_method,
8352 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008353 oc_function_template,
8354 oc_method_template,
8355 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008356 oc_implicit_default_constructor,
8357 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008358 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008359 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008360 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008361 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008362};
8363
John McCalle1ac8d12010-01-13 00:25:19 +00008364OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8365 FunctionDecl *Fn,
8366 std::string &Description) {
8367 bool isTemplate = false;
8368
8369 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8370 isTemplate = true;
8371 Description = S.getTemplateArgumentBindingsText(
8372 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8373 }
John McCallfd0b2f82010-01-06 09:43:14 +00008374
8375 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008376 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008377 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008378
Sebastian Redl08905022011-02-05 19:23:19 +00008379 if (Ctor->getInheritedConstructor())
8380 return oc_implicit_inherited_constructor;
8381
Alexis Hunt119c10e2011-05-25 23:16:36 +00008382 if (Ctor->isDefaultConstructor())
8383 return oc_implicit_default_constructor;
8384
8385 if (Ctor->isMoveConstructor())
8386 return oc_implicit_move_constructor;
8387
8388 assert(Ctor->isCopyConstructor() &&
8389 "unexpected sort of implicit constructor");
8390 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008391 }
8392
8393 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8394 // This actually gets spelled 'candidate function' for now, but
8395 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008396 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008397 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008398
Alexis Hunt119c10e2011-05-25 23:16:36 +00008399 if (Meth->isMoveAssignmentOperator())
8400 return oc_implicit_move_assignment;
8401
Douglas Gregor12695102012-02-10 08:36:38 +00008402 if (Meth->isCopyAssignmentOperator())
8403 return oc_implicit_copy_assignment;
8404
8405 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8406 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008407 }
8408
John McCalle1ac8d12010-01-13 00:25:19 +00008409 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008410}
8411
Larisse Voufo98b20f12013-07-19 23:00:19 +00008412void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008413 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8414 if (!Ctor) return;
8415
8416 Ctor = Ctor->getInheritedConstructor();
8417 if (!Ctor) return;
8418
8419 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8420}
8421
John McCall53262c92010-01-12 02:15:36 +00008422} // end anonymous namespace
8423
8424// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008425void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008426 std::string FnDesc;
8427 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008428 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8429 << (unsigned) K << FnDesc;
8430 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8431 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008432 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008433}
8434
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008435// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008436// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008437void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008438 assert(OverloadedExpr->getType() == Context.OverloadTy);
8439
8440 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8441 OverloadExpr *OvlExpr = Ovl.Expression;
8442
8443 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8444 IEnd = OvlExpr->decls_end();
8445 I != IEnd; ++I) {
8446 if (FunctionTemplateDecl *FunTmpl =
8447 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008448 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008449 } else if (FunctionDecl *Fun
8450 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008451 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008452 }
8453 }
8454}
8455
John McCall0d1da222010-01-12 00:44:57 +00008456/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8457/// "lead" diagnostic; it will be given two arguments, the source and
8458/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008459void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8460 Sema &S,
8461 SourceLocation CaretLoc,
8462 const PartialDiagnostic &PDiag) const {
8463 S.Diag(CaretLoc, PDiag)
8464 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008465 // FIXME: The note limiting machinery is borrowed from
8466 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8467 // refactoring here.
8468 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8469 unsigned CandsShown = 0;
8470 AmbiguousConversionSequence::const_iterator I, E;
8471 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8472 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8473 break;
8474 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008475 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008476 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008477 if (I != E)
8478 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008479}
8480
John McCall0d1da222010-01-12 00:44:57 +00008481namespace {
8482
John McCall6a61b522010-01-13 09:16:55 +00008483void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8484 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8485 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008486 assert(Cand->Function && "for now, candidate must be a function");
8487 FunctionDecl *Fn = Cand->Function;
8488
8489 // There's a conversion slot for the object argument if this is a
8490 // non-constructor method. Note that 'I' corresponds the
8491 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008492 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008493 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008494 if (I == 0)
8495 isObjectArgument = true;
8496 else
8497 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008498 }
8499
John McCalle1ac8d12010-01-13 00:25:19 +00008500 std::string FnDesc;
8501 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8502
John McCall6a61b522010-01-13 09:16:55 +00008503 Expr *FromExpr = Conv.Bad.FromExpr;
8504 QualType FromTy = Conv.Bad.getFromType();
8505 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008506
John McCallfb7ad0f2010-02-02 02:42:52 +00008507 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008508 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008509 Expr *E = FromExpr->IgnoreParens();
8510 if (isa<UnaryOperator>(E))
8511 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008512 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008513
8514 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8515 << (unsigned) FnKind << FnDesc
8516 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8517 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008518 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008519 return;
8520 }
8521
John McCall6d174642010-01-23 08:10:49 +00008522 // Do some hand-waving analysis to see if the non-viability is due
8523 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008524 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8525 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8526 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8527 CToTy = RT->getPointeeType();
8528 else {
8529 // TODO: detect and diagnose the full richness of const mismatches.
8530 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8531 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8532 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8533 }
8534
8535 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8536 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008537 Qualifiers FromQs = CFromTy.getQualifiers();
8538 Qualifiers ToQs = CToTy.getQualifiers();
8539
8540 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8541 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8542 << (unsigned) FnKind << FnDesc
8543 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8544 << FromTy
8545 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8546 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008547 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008548 return;
8549 }
8550
John McCall31168b02011-06-15 23:02:42 +00008551 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008552 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008553 << (unsigned) FnKind << FnDesc
8554 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8555 << FromTy
8556 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8557 << (unsigned) isObjectArgument << I+1;
8558 MaybeEmitInheritedConstructorNote(S, Fn);
8559 return;
8560 }
8561
Douglas Gregoraec25842011-04-26 23:16:46 +00008562 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8563 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8564 << (unsigned) FnKind << FnDesc
8565 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8566 << FromTy
8567 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8568 << (unsigned) isObjectArgument << I+1;
8569 MaybeEmitInheritedConstructorNote(S, Fn);
8570 return;
8571 }
8572
John McCall47000992010-01-14 03:28:57 +00008573 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8574 assert(CVR && "unexpected qualifiers mismatch");
8575
8576 if (isObjectArgument) {
8577 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8578 << (unsigned) FnKind << FnDesc
8579 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8580 << FromTy << (CVR - 1);
8581 } else {
8582 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8583 << (unsigned) FnKind << FnDesc
8584 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8585 << FromTy << (CVR - 1) << I+1;
8586 }
Sebastian Redl08905022011-02-05 19:23:19 +00008587 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008588 return;
8589 }
8590
Sebastian Redla72462c2011-09-24 17:48:32 +00008591 // Special diagnostic for failure to convert an initializer list, since
8592 // telling the user that it has type void is not useful.
8593 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8594 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8595 << (unsigned) FnKind << FnDesc
8596 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8597 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8598 MaybeEmitInheritedConstructorNote(S, Fn);
8599 return;
8600 }
8601
John McCall6d174642010-01-23 08:10:49 +00008602 // Diagnose references or pointers to incomplete types differently,
8603 // since it's far from impossible that the incompleteness triggered
8604 // the failure.
8605 QualType TempFromTy = FromTy.getNonReferenceType();
8606 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8607 TempFromTy = PTy->getPointeeType();
8608 if (TempFromTy->isIncompleteType()) {
8609 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8610 << (unsigned) FnKind << FnDesc
8611 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8612 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008613 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008614 return;
8615 }
8616
Douglas Gregor56f2e342010-06-30 23:01:39 +00008617 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008618 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008619 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8620 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8621 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8622 FromPtrTy->getPointeeType()) &&
8623 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8624 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008625 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008626 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008627 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008628 }
8629 } else if (const ObjCObjectPointerType *FromPtrTy
8630 = FromTy->getAs<ObjCObjectPointerType>()) {
8631 if (const ObjCObjectPointerType *ToPtrTy
8632 = ToTy->getAs<ObjCObjectPointerType>())
8633 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8634 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8635 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8636 FromPtrTy->getPointeeType()) &&
8637 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008638 BaseToDerivedConversion = 2;
8639 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008640 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8641 !FromTy->isIncompleteType() &&
8642 !ToRefTy->getPointeeType()->isIncompleteType() &&
8643 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8644 BaseToDerivedConversion = 3;
8645 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8646 ToTy.getNonReferenceType().getCanonicalType() ==
8647 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008648 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8649 << (unsigned) FnKind << FnDesc
8650 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8651 << (unsigned) isObjectArgument << I + 1;
8652 MaybeEmitInheritedConstructorNote(S, Fn);
8653 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008654 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008656
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008657 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008658 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008659 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008660 << (unsigned) FnKind << FnDesc
8661 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008662 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008663 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008664 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008665 return;
8666 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008667
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008668 if (isa<ObjCObjectPointerType>(CFromTy) &&
8669 isa<PointerType>(CToTy)) {
8670 Qualifiers FromQs = CFromTy.getQualifiers();
8671 Qualifiers ToQs = CToTy.getQualifiers();
8672 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8673 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8674 << (unsigned) FnKind << FnDesc
8675 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8676 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8677 MaybeEmitInheritedConstructorNote(S, Fn);
8678 return;
8679 }
8680 }
8681
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008682 // Emit the generic diagnostic and, optionally, add the hints to it.
8683 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8684 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008685 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008686 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8687 << (unsigned) (Cand->Fix.Kind);
8688
8689 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008690 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8691 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008692 FDiag << *HI;
8693 S.Diag(Fn->getLocation(), FDiag);
8694
Sebastian Redl08905022011-02-05 19:23:19 +00008695 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008696}
8697
Larisse Voufo98b20f12013-07-19 23:00:19 +00008698/// Additional arity mismatch diagnosis specific to a function overload
8699/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8700/// over a candidate in any candidate set.
8701bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8702 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008703 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008704 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008705
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008706 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008707 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008708 // right number of arguments, because only overloaded operators have
8709 // the weird behavior of overloading member and non-member functions.
8710 // Just don't report anything.
8711 if (Fn->isInvalidDecl() &&
8712 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008713 return true;
8714
8715 if (NumArgs < MinParams) {
8716 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8717 (Cand->FailureKind == ovl_fail_bad_deduction &&
8718 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8719 } else {
8720 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8721 (Cand->FailureKind == ovl_fail_bad_deduction &&
8722 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8723 }
8724
8725 return false;
8726}
8727
8728/// General arity mismatch diagnosis over a candidate in a candidate set.
8729void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8730 assert(isa<FunctionDecl>(D) &&
8731 "The templated declaration should at least be a function"
8732 " when diagnosing bad template argument deduction due to too many"
8733 " or too few arguments");
8734
8735 FunctionDecl *Fn = cast<FunctionDecl>(D);
8736
8737 // TODO: treat calls to a missing default constructor as a special case
8738 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8739 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008740
John McCall6a61b522010-01-13 09:16:55 +00008741 // at least / at most / exactly
8742 unsigned mode, modeCount;
8743 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008744 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8745 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008746 mode = 0; // "at least"
8747 else
8748 mode = 2; // "exactly"
8749 modeCount = MinParams;
8750 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008751 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008752 mode = 1; // "at most"
8753 else
8754 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008755 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008756 }
8757
8758 std::string Description;
8759 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8760
Richard Smith10ff50d2012-05-11 05:16:41 +00008761 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8762 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8763 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8764 << Fn->getParamDecl(0) << NumFormalArgs;
8765 else
8766 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8767 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8768 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008769 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008770}
8771
Larisse Voufo98b20f12013-07-19 23:00:19 +00008772/// Arity mismatch diagnosis specific to a function overload candidate.
8773void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8774 unsigned NumFormalArgs) {
8775 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8776 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8777}
Larisse Voufo47c08452013-07-19 22:53:23 +00008778
Larisse Voufo98b20f12013-07-19 23:00:19 +00008779TemplateDecl *getDescribedTemplate(Decl *Templated) {
8780 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8781 return FD->getDescribedFunctionTemplate();
8782 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8783 return RD->getDescribedClassTemplate();
8784
8785 llvm_unreachable("Unsupported: Getting the described template declaration"
8786 " for bad deduction diagnosis");
8787}
8788
8789/// Diagnose a failed template-argument deduction.
8790void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8791 DeductionFailureInfo &DeductionFailure,
8792 unsigned NumArgs) {
8793 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008794 NamedDecl *ParamD;
8795 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8796 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8797 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008798 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008799 case Sema::TDK_Success:
8800 llvm_unreachable("TDK_success while diagnosing bad deduction");
8801
8802 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008803 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008804 S.Diag(Templated->getLocation(),
8805 diag::note_ovl_candidate_incomplete_deduction)
8806 << ParamD->getDeclName();
8807 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008808 return;
8809 }
8810
John McCall42d7d192010-08-05 09:05:08 +00008811 case Sema::TDK_Underqualified: {
8812 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8813 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8814
Larisse Voufo98b20f12013-07-19 23:00:19 +00008815 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008816
8817 // Param will have been canonicalized, but it should just be a
8818 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008819 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008820 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008821 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008822 assert(S.Context.hasSameType(Param, NonCanonParam));
8823
8824 // Arg has also been canonicalized, but there's nothing we can do
8825 // about that. It also doesn't matter as much, because it won't
8826 // have any template parameters in it (because deduction isn't
8827 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008828 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008829
Larisse Voufo98b20f12013-07-19 23:00:19 +00008830 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8831 << ParamD->getDeclName() << Arg << NonCanonParam;
8832 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008833 return;
8834 }
8835
8836 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008837 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008838 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008839 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008840 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008841 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008842 which = 1;
8843 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008844 which = 2;
8845 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008846
Larisse Voufo98b20f12013-07-19 23:00:19 +00008847 S.Diag(Templated->getLocation(),
8848 diag::note_ovl_candidate_inconsistent_deduction)
8849 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8850 << *DeductionFailure.getSecondArg();
8851 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008852 return;
8853 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008854
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008855 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008856 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008857 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008858 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008859 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008860 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008861 else {
8862 int index = 0;
8863 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8864 index = TTP->getIndex();
8865 else if (NonTypeTemplateParmDecl *NTTP
8866 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8867 index = NTTP->getIndex();
8868 else
8869 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008870 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008871 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008872 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008873 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008874 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008875 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008876
Douglas Gregor02eb4832010-05-08 18:13:28 +00008877 case Sema::TDK_TooManyArguments:
8878 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008879 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008880 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008881
8882 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008883 S.Diag(Templated->getLocation(),
8884 diag::note_ovl_candidate_instantiation_depth);
8885 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008886 return;
8887
8888 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008889 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008890 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008891 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008892 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008893 TemplateArgString = " ";
8894 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00008895 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00008896 }
8897
Richard Smith6f8d2c62012-05-09 05:17:00 +00008898 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008899 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008900 if (PDiag && PDiag->second.getDiagID() ==
8901 diag::err_typename_nested_not_found_enable_if) {
8902 // FIXME: Use the source range of the condition, and the fully-qualified
8903 // name of the enable_if template. These are both present in PDiag.
8904 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8905 << "'enable_if'" << TemplateArgString;
8906 return;
8907 }
8908
Richard Smith9ca64612012-05-07 09:03:25 +00008909 // Format the SFINAE diagnostic into the argument string.
8910 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8911 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008912 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008913 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008914 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008915 SFINAEArgString = ": ";
8916 R = SourceRange(PDiag->first, PDiag->first);
8917 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8918 }
8919
Larisse Voufo98b20f12013-07-19 23:00:19 +00008920 S.Diag(Templated->getLocation(),
8921 diag::note_ovl_candidate_substitution_failure)
8922 << TemplateArgString << SFINAEArgString << R;
8923 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008924 return;
8925 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008926
Richard Smith8c6eeb92013-01-31 04:03:12 +00008927 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008928 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8929 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00008930 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008931 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00008932 return;
8933 }
8934
Richard Trieue3732352013-04-08 21:11:40 +00008935 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00008936 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008937 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8938 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00008939 if (FirstTA.getKind() == TemplateArgument::Template &&
8940 SecondTA.getKind() == TemplateArgument::Template) {
8941 TemplateName FirstTN = FirstTA.getAsTemplate();
8942 TemplateName SecondTN = SecondTA.getAsTemplate();
8943 if (FirstTN.getKind() == TemplateName::Template &&
8944 SecondTN.getKind() == TemplateName::Template) {
8945 if (FirstTN.getAsTemplateDecl()->getName() ==
8946 SecondTN.getAsTemplateDecl()->getName()) {
8947 // FIXME: This fixes a bad diagnostic where both templates are named
8948 // the same. This particular case is a bit difficult since:
8949 // 1) It is passed as a string to the diagnostic printer.
8950 // 2) The diagnostic printer only attempts to find a better
8951 // name for types, not decls.
8952 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008953 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00008954 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8955 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8956 return;
8957 }
8958 }
8959 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00008960 // FIXME: For generic lambda parameters, check if the function is a lambda
8961 // call operator, and if so, emit a prettier and more informative
8962 // diagnostic that mentions 'auto' and lambda in addition to
8963 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008964 S.Diag(Templated->getLocation(),
8965 diag::note_ovl_candidate_non_deduced_mismatch)
8966 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00008967 return;
Richard Trieue3732352013-04-08 21:11:40 +00008968 }
John McCall8b9ed552010-02-01 18:53:26 +00008969 // TODO: diagnose these individually, then kill off
8970 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00008971 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008972 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8973 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008974 return;
8975 }
8976}
8977
Larisse Voufo98b20f12013-07-19 23:00:19 +00008978/// Diagnose a failed template-argument deduction, for function calls.
8979void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8980 unsigned TDK = Cand->DeductionFailure.Result;
8981 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8982 if (CheckArityMismatch(S, Cand, NumArgs))
8983 return;
8984 }
8985 DiagnoseBadDeduction(S, Cand->Function, // pattern
8986 Cand->DeductionFailure, NumArgs);
8987}
8988
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008989/// CUDA: diagnose an invalid call across targets.
8990void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8991 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8992 FunctionDecl *Callee = Cand->Function;
8993
8994 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8995 CalleeTarget = S.IdentifyCUDATarget(Callee);
8996
8997 std::string FnDesc;
8998 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8999
9000 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
9001 << (unsigned) FnKind << CalleeTarget << CallerTarget;
9002}
9003
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009004void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9005 FunctionDecl *Callee = Cand->Function;
9006 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9007
9008 S.Diag(Callee->getLocation(),
9009 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9010 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9011}
9012
John McCall8b9ed552010-02-01 18:53:26 +00009013/// Generates a 'note' diagnostic for an overload candidate. We've
9014/// already generated a primary error at the call site.
9015///
9016/// It really does need to be a single diagnostic with its caret
9017/// pointed at the candidate declaration. Yes, this creates some
9018/// major challenges of technical writing. Yes, this makes pointing
9019/// out problems with specific arguments quite awkward. It's still
9020/// better than generating twenty screens of text for every failed
9021/// overload.
9022///
9023/// It would be great to be able to express per-candidate problems
9024/// more richly for those diagnostic clients that cared, but we'd
9025/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00009026void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009027 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009028 FunctionDecl *Fn = Cand->Function;
9029
John McCall12f97bc2010-01-08 04:41:39 +00009030 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009031 if (Cand->Viable && (Fn->isDeleted() ||
9032 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009033 std::string FnDesc;
9034 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009035
9036 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009037 << FnKind << FnDesc
9038 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009039 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009040 return;
John McCall12f97bc2010-01-08 04:41:39 +00009041 }
9042
John McCalle1ac8d12010-01-13 00:25:19 +00009043 // We don't really have anything else to say about viable candidates.
9044 if (Cand->Viable) {
9045 S.NoteOverloadCandidate(Fn);
9046 return;
9047 }
John McCall0d1da222010-01-12 00:44:57 +00009048
John McCall6a61b522010-01-13 09:16:55 +00009049 switch (Cand->FailureKind) {
9050 case ovl_fail_too_many_arguments:
9051 case ovl_fail_too_few_arguments:
9052 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009053
John McCall6a61b522010-01-13 09:16:55 +00009054 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009055 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009056
John McCallfe796dd2010-01-23 05:17:32 +00009057 case ovl_fail_trivial_conversion:
9058 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009059 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009060 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009061
John McCall65eb8792010-02-25 01:37:24 +00009062 case ovl_fail_bad_conversion: {
9063 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009064 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009065 if (Cand->Conversions[I].isBad())
9066 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009067
John McCall6a61b522010-01-13 09:16:55 +00009068 // FIXME: this currently happens when we're called from SemaInit
9069 // when user-conversion overload fails. Figure out how to handle
9070 // those conditions and diagnose them well.
9071 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009072 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009073
9074 case ovl_fail_bad_target:
9075 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009076
9077 case ovl_fail_enable_if:
9078 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009079 }
John McCalld3224162010-01-08 00:58:21 +00009080}
9081
9082void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9083 // Desugar the type of the surrogate down to a function type,
9084 // retaining as many typedefs as possible while still showing
9085 // the function type (and, therefore, its parameter types).
9086 QualType FnType = Cand->Surrogate->getConversionType();
9087 bool isLValueReference = false;
9088 bool isRValueReference = false;
9089 bool isPointer = false;
9090 if (const LValueReferenceType *FnTypeRef =
9091 FnType->getAs<LValueReferenceType>()) {
9092 FnType = FnTypeRef->getPointeeType();
9093 isLValueReference = true;
9094 } else if (const RValueReferenceType *FnTypeRef =
9095 FnType->getAs<RValueReferenceType>()) {
9096 FnType = FnTypeRef->getPointeeType();
9097 isRValueReference = true;
9098 }
9099 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9100 FnType = FnTypePtr->getPointeeType();
9101 isPointer = true;
9102 }
9103 // Desugar down to a function type.
9104 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9105 // Reconstruct the pointer/reference as appropriate.
9106 if (isPointer) FnType = S.Context.getPointerType(FnType);
9107 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9108 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9109
9110 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9111 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009112 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009113}
9114
9115void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009116 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009117 SourceLocation OpLoc,
9118 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009119 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009120 std::string TypeStr("operator");
9121 TypeStr += Opc;
9122 TypeStr += "(";
9123 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009124 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009125 TypeStr += ")";
9126 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9127 } else {
9128 TypeStr += ", ";
9129 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9130 TypeStr += ")";
9131 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9132 }
9133}
9134
9135void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9136 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009137 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009138 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9139 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009140 if (ICS.isBad()) break; // all meaningless after first invalid
9141 if (!ICS.isAmbiguous()) continue;
9142
John McCall5c32be02010-08-24 20:38:10 +00009143 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009144 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009145 }
9146}
9147
Larisse Voufo98b20f12013-07-19 23:00:19 +00009148static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009149 if (Cand->Function)
9150 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009151 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009152 return Cand->Surrogate->getLocation();
9153 return SourceLocation();
9154}
9155
Larisse Voufo98b20f12013-07-19 23:00:19 +00009156static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009157 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009158 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009159 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009160
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009161 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009162 case Sema::TDK_Incomplete:
9163 return 1;
9164
9165 case Sema::TDK_Underqualified:
9166 case Sema::TDK_Inconsistent:
9167 return 2;
9168
9169 case Sema::TDK_SubstitutionFailure:
9170 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009171 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009172 return 3;
9173
9174 case Sema::TDK_InstantiationDepth:
9175 case Sema::TDK_FailedOverloadResolution:
9176 return 4;
9177
9178 case Sema::TDK_InvalidExplicitArguments:
9179 return 5;
9180
9181 case Sema::TDK_TooManyArguments:
9182 case Sema::TDK_TooFewArguments:
9183 return 6;
9184 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009185 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009186}
9187
John McCallad2587a2010-01-12 00:48:53 +00009188struct CompareOverloadCandidatesForDisplay {
9189 Sema &S;
9190 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00009191
9192 bool operator()(const OverloadCandidate *L,
9193 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009194 // Fast-path this check.
9195 if (L == R) return false;
9196
John McCall12f97bc2010-01-08 04:41:39 +00009197 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009198 if (L->Viable) {
9199 if (!R->Viable) return true;
9200
9201 // TODO: introduce a tri-valued comparison for overload
9202 // candidates. Would be more worthwhile if we had a sort
9203 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009204 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9205 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009206 } else if (R->Viable)
9207 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009208
John McCall3712d9e2010-01-15 23:32:50 +00009209 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009210
John McCall3712d9e2010-01-15 23:32:50 +00009211 // Criteria by which we can sort non-viable candidates:
9212 if (!L->Viable) {
9213 // 1. Arity mismatches come after other candidates.
9214 if (L->FailureKind == ovl_fail_too_many_arguments ||
9215 L->FailureKind == ovl_fail_too_few_arguments)
9216 return false;
9217 if (R->FailureKind == ovl_fail_too_many_arguments ||
9218 R->FailureKind == ovl_fail_too_few_arguments)
9219 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009220
John McCallfe796dd2010-01-23 05:17:32 +00009221 // 2. Bad conversions come first and are ordered by the number
9222 // of bad conversions and quality of good conversions.
9223 if (L->FailureKind == ovl_fail_bad_conversion) {
9224 if (R->FailureKind != ovl_fail_bad_conversion)
9225 return true;
9226
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009227 // The conversion that can be fixed with a smaller number of changes,
9228 // comes first.
9229 unsigned numLFixes = L->Fix.NumConversionsFixed;
9230 unsigned numRFixes = R->Fix.NumConversionsFixed;
9231 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9232 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009233 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009234 if (numLFixes < numRFixes)
9235 return true;
9236 else
9237 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009238 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009239
John McCallfe796dd2010-01-23 05:17:32 +00009240 // If there's any ordering between the defined conversions...
9241 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009242 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009243
9244 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009245 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009246 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009247 switch (CompareImplicitConversionSequences(S,
9248 L->Conversions[I],
9249 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009250 case ImplicitConversionSequence::Better:
9251 leftBetter++;
9252 break;
9253
9254 case ImplicitConversionSequence::Worse:
9255 leftBetter--;
9256 break;
9257
9258 case ImplicitConversionSequence::Indistinguishable:
9259 break;
9260 }
9261 }
9262 if (leftBetter > 0) return true;
9263 if (leftBetter < 0) return false;
9264
9265 } else if (R->FailureKind == ovl_fail_bad_conversion)
9266 return false;
9267
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009268 if (L->FailureKind == ovl_fail_bad_deduction) {
9269 if (R->FailureKind != ovl_fail_bad_deduction)
9270 return true;
9271
9272 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9273 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009274 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009275 } else if (R->FailureKind == ovl_fail_bad_deduction)
9276 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009277
John McCall3712d9e2010-01-15 23:32:50 +00009278 // TODO: others?
9279 }
9280
9281 // Sort everything else by location.
9282 SourceLocation LLoc = GetLocationForCandidate(L);
9283 SourceLocation RLoc = GetLocationForCandidate(R);
9284
9285 // Put candidates without locations (e.g. builtins) at the end.
9286 if (LLoc.isInvalid()) return false;
9287 if (RLoc.isInvalid()) return true;
9288
9289 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009290 }
9291};
9292
John McCallfe796dd2010-01-23 05:17:32 +00009293/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009294/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009295void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009296 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009297 assert(!Cand->Viable);
9298
9299 // Don't do anything on failures other than bad conversion.
9300 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9301
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009302 // We only want the FixIts if all the arguments can be corrected.
9303 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009304 // Use a implicit copy initialization to check conversion fixes.
9305 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009306
John McCallfe796dd2010-01-23 05:17:32 +00009307 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009308 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009309 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009310 while (true) {
9311 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9312 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009313 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009314 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009315 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009316 }
John McCallfe796dd2010-01-23 05:17:32 +00009317 }
9318
9319 if (ConvIdx == ConvCount)
9320 return;
9321
John McCall65eb8792010-02-25 01:37:24 +00009322 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9323 "remaining conversion is initialized?");
9324
Douglas Gregoradc7a702010-04-16 17:45:54 +00009325 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009326 // operation somehow.
9327 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009328
9329 const FunctionProtoType* Proto;
9330 unsigned ArgIdx = ConvIdx;
9331
9332 if (Cand->IsSurrogate) {
9333 QualType ConvType
9334 = Cand->Surrogate->getConversionType().getNonReferenceType();
9335 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9336 ConvType = ConvPtrType->getPointeeType();
9337 Proto = ConvType->getAs<FunctionProtoType>();
9338 ArgIdx--;
9339 } else if (Cand->Function) {
9340 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9341 if (isa<CXXMethodDecl>(Cand->Function) &&
9342 !isa<CXXConstructorDecl>(Cand->Function))
9343 ArgIdx--;
9344 } else {
9345 // Builtin binary operator with a bad first conversion.
9346 assert(ConvCount <= 3);
9347 for (; ConvIdx != ConvCount; ++ConvIdx)
9348 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009349 = TryCopyInitialization(S, Args[ConvIdx],
9350 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009351 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009352 /*InOverloadResolution*/ true,
9353 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009354 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009355 return;
9356 }
9357
9358 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009359 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009360 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009361 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009362 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9363 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9364 /*InOverloadResolution=*/true,
9365 /*AllowObjCWritebackConversion=*/
9366 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009367 // Store the FixIt in the candidate if it exists.
9368 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009369 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009370 }
John McCallfe796dd2010-01-23 05:17:32 +00009371 else
9372 Cand->Conversions[ConvIdx].setEllipsis();
9373 }
9374}
9375
John McCalld3224162010-01-08 00:58:21 +00009376} // end anonymous namespace
9377
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009378/// PrintOverloadCandidates - When overload resolution fails, prints
9379/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009380/// set.
John McCall5c32be02010-08-24 20:38:10 +00009381void OverloadCandidateSet::NoteCandidates(Sema &S,
9382 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009383 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009384 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009385 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009386 // Sort the candidates by viability and position. Sorting directly would
9387 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009388 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009389 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9390 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009391 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009392 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009393 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009394 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009395 if (Cand->Function || Cand->IsSurrogate)
9396 Cands.push_back(Cand);
9397 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9398 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009399 }
9400 }
9401
John McCallad2587a2010-01-12 00:48:53 +00009402 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00009403 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009404
John McCall0d1da222010-01-12 00:44:57 +00009405 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009406
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009407 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009408 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009409 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009410 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9411 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009412
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009413 // Set an arbitrary limit on the number of candidate functions we'll spam
9414 // the user with. FIXME: This limit should depend on details of the
9415 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009416 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009417 break;
9418 }
9419 ++CandsShown;
9420
John McCalld3224162010-01-08 00:58:21 +00009421 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009422 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009423 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009424 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009425 else {
9426 assert(Cand->Viable &&
9427 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009428 // Generally we only see ambiguities including viable builtin
9429 // operators if overload resolution got screwed up by an
9430 // ambiguous user-defined conversion.
9431 //
9432 // FIXME: It's quite possible for different conversions to see
9433 // different ambiguities, though.
9434 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009435 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009436 ReportedAmbiguousConversions = true;
9437 }
John McCalld3224162010-01-08 00:58:21 +00009438
John McCall0d1da222010-01-12 00:44:57 +00009439 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009440 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009441 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009442 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009443
9444 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009445 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009446}
9447
Larisse Voufo98b20f12013-07-19 23:00:19 +00009448static SourceLocation
9449GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9450 return Cand->Specialization ? Cand->Specialization->getLocation()
9451 : SourceLocation();
9452}
9453
9454struct CompareTemplateSpecCandidatesForDisplay {
9455 Sema &S;
9456 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9457
9458 bool operator()(const TemplateSpecCandidate *L,
9459 const TemplateSpecCandidate *R) {
9460 // Fast-path this check.
9461 if (L == R)
9462 return false;
9463
9464 // Assuming that both candidates are not matches...
9465
9466 // Sort by the ranking of deduction failures.
9467 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9468 return RankDeductionFailure(L->DeductionFailure) <
9469 RankDeductionFailure(R->DeductionFailure);
9470
9471 // Sort everything else by location.
9472 SourceLocation LLoc = GetLocationForCandidate(L);
9473 SourceLocation RLoc = GetLocationForCandidate(R);
9474
9475 // Put candidates without locations (e.g. builtins) at the end.
9476 if (LLoc.isInvalid())
9477 return false;
9478 if (RLoc.isInvalid())
9479 return true;
9480
9481 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9482 }
9483};
9484
9485/// Diagnose a template argument deduction failure.
9486/// We are treating these failures as overload failures due to bad
9487/// deductions.
9488void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9489 DiagnoseBadDeduction(S, Specialization, // pattern
9490 DeductionFailure, /*NumArgs=*/0);
9491}
9492
9493void TemplateSpecCandidateSet::destroyCandidates() {
9494 for (iterator i = begin(), e = end(); i != e; ++i) {
9495 i->DeductionFailure.Destroy();
9496 }
9497}
9498
9499void TemplateSpecCandidateSet::clear() {
9500 destroyCandidates();
9501 Candidates.clear();
9502}
9503
9504/// NoteCandidates - When no template specialization match is found, prints
9505/// diagnostic messages containing the non-matching specializations that form
9506/// the candidate set.
9507/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9508/// OCD == OCD_AllCandidates and Cand->Viable == false.
9509void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9510 // Sort the candidates by position (assuming no candidate is a match).
9511 // Sorting directly would be prohibitive, so we make a set of pointers
9512 // and sort those.
9513 SmallVector<TemplateSpecCandidate *, 32> Cands;
9514 Cands.reserve(size());
9515 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9516 if (Cand->Specialization)
9517 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009518 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009519 // in general, want to list every possible builtin candidate.
9520 }
9521
9522 std::sort(Cands.begin(), Cands.end(),
9523 CompareTemplateSpecCandidatesForDisplay(S));
9524
9525 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9526 // for generalization purposes (?).
9527 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9528
9529 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9530 unsigned CandsShown = 0;
9531 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9532 TemplateSpecCandidate *Cand = *I;
9533
9534 // Set an arbitrary limit on the number of candidates we'll spam
9535 // the user with. FIXME: This limit should depend on details of the
9536 // candidate list.
9537 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9538 break;
9539 ++CandsShown;
9540
9541 assert(Cand->Specialization &&
9542 "Non-matching built-in candidates are not added to Cands.");
9543 Cand->NoteDeductionFailure(S);
9544 }
9545
9546 if (I != E)
9547 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9548}
9549
Douglas Gregorb491ed32011-02-19 21:32:49 +00009550// [PossiblyAFunctionType] --> [Return]
9551// NonFunctionType --> NonFunctionType
9552// R (A) --> R(A)
9553// R (*)(A) --> R (A)
9554// R (&)(A) --> R (A)
9555// R (S::*)(A) --> R (A)
9556QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9557 QualType Ret = PossiblyAFunctionType;
9558 if (const PointerType *ToTypePtr =
9559 PossiblyAFunctionType->getAs<PointerType>())
9560 Ret = ToTypePtr->getPointeeType();
9561 else if (const ReferenceType *ToTypeRef =
9562 PossiblyAFunctionType->getAs<ReferenceType>())
9563 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009564 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009565 PossiblyAFunctionType->getAs<MemberPointerType>())
9566 Ret = MemTypePtr->getPointeeType();
9567 Ret =
9568 Context.getCanonicalType(Ret).getUnqualifiedType();
9569 return Ret;
9570}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009571
Douglas Gregorb491ed32011-02-19 21:32:49 +00009572// A helper class to help with address of function resolution
9573// - allows us to avoid passing around all those ugly parameters
9574class AddressOfFunctionResolver
9575{
9576 Sema& S;
9577 Expr* SourceExpr;
9578 const QualType& TargetType;
9579 QualType TargetFunctionType; // Extracted function type from target type
9580
9581 bool Complain;
9582 //DeclAccessPair& ResultFunctionAccessPair;
9583 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009584
Douglas Gregorb491ed32011-02-19 21:32:49 +00009585 bool TargetTypeIsNonStaticMemberFunction;
9586 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009587 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009588
Douglas Gregorb491ed32011-02-19 21:32:49 +00009589 OverloadExpr::FindResult OvlExprInfo;
9590 OverloadExpr *OvlExpr;
9591 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009592 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009593 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009594
Douglas Gregorb491ed32011-02-19 21:32:49 +00009595public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009596 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9597 const QualType &TargetType, bool Complain)
9598 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9599 Complain(Complain), Context(S.getASTContext()),
9600 TargetTypeIsNonStaticMemberFunction(
9601 !!TargetType->getAs<MemberPointerType>()),
9602 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009603 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009604 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9605 OvlExpr(OvlExprInfo.Expression),
9606 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009607 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009608
David Majnemera4f7c7a2013-08-01 06:13:59 +00009609 if (TargetFunctionType->isFunctionType()) {
9610 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9611 if (!UME->isImplicitAccess() &&
9612 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9613 StaticMemberFunctionFromBoundPointer = true;
9614 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9615 DeclAccessPair dap;
9616 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9617 OvlExpr, false, &dap)) {
9618 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9619 if (!Method->isStatic()) {
9620 // If the target type is a non-function type and the function found
9621 // is a non-static member function, pretend as if that was the
9622 // target, it's the only possible type to end up with.
9623 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009624
David Majnemera4f7c7a2013-08-01 06:13:59 +00009625 // And skip adding the function if its not in the proper form.
9626 // We'll diagnose this due to an empty set of functions.
9627 if (!OvlExprInfo.HasFormOfMemberPointer)
9628 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009629 }
9630
David Majnemera4f7c7a2013-08-01 06:13:59 +00009631 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009632 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009633 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009634 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009635
9636 if (OvlExpr->hasExplicitTemplateArgs())
9637 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009638
Douglas Gregorb491ed32011-02-19 21:32:49 +00009639 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9640 // C++ [over.over]p4:
9641 // If more than one function is selected, [...]
9642 if (Matches.size() > 1) {
9643 if (FoundNonTemplateFunction)
9644 EliminateAllTemplateMatches();
9645 else
9646 EliminateAllExceptMostSpecializedTemplate();
9647 }
9648 }
9649 }
9650
9651private:
9652 bool isTargetTypeAFunction() const {
9653 return TargetFunctionType->isFunctionType();
9654 }
9655
9656 // [ToType] [Return]
9657
9658 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9659 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9660 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9661 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9662 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9663 }
9664
9665 // return true if any matching specializations were found
9666 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9667 const DeclAccessPair& CurAccessFunPair) {
9668 if (CXXMethodDecl *Method
9669 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9670 // Skip non-static function templates when converting to pointer, and
9671 // static when converting to member pointer.
9672 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9673 return false;
9674 }
9675 else if (TargetTypeIsNonStaticMemberFunction)
9676 return false;
9677
9678 // C++ [over.over]p2:
9679 // If the name is a function template, template argument deduction is
9680 // done (14.8.2.2), and if the argument deduction succeeds, the
9681 // resulting template argument list is used to generate a single
9682 // function template specialization, which is added to the set of
9683 // overloaded functions considered.
9684 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009685 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009686 if (Sema::TemplateDeductionResult Result
9687 = S.DeduceTemplateArguments(FunctionTemplate,
9688 &OvlExplicitTemplateArgs,
9689 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009690 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009691 // Make a note of the failed deduction for diagnostics.
9692 FailedCandidates.addCandidate()
9693 .set(FunctionTemplate->getTemplatedDecl(),
9694 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009695 return false;
9696 }
9697
Douglas Gregor19a41f12013-04-17 08:45:07 +00009698 // Template argument deduction ensures that we have an exact match or
9699 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009700 // This function template specicalization works.
9701 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009702 assert(S.isSameOrCompatibleFunctionType(
9703 Context.getCanonicalType(Specialization->getType()),
9704 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009705 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9706 return true;
9707 }
9708
9709 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9710 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009711 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009712 // Skip non-static functions when converting to pointer, and static
9713 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009714 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9715 return false;
9716 }
9717 else if (TargetTypeIsNonStaticMemberFunction)
9718 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009719
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009720 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009721 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009722 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9723 if (S.CheckCUDATarget(Caller, FunDecl))
9724 return false;
9725
Richard Smith2a7d4812013-05-04 07:00:32 +00009726 // If any candidate has a placeholder return type, trigger its deduction
9727 // now.
9728 if (S.getLangOpts().CPlusPlus1y &&
9729 FunDecl->getResultType()->isUndeducedType() &&
9730 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9731 return false;
9732
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009733 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009734 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9735 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009736 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9737 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009738 Matches.push_back(std::make_pair(CurAccessFunPair,
9739 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009740 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009741 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009742 }
Mike Stump11289f42009-09-09 15:08:12 +00009743 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009744
9745 return false;
9746 }
9747
9748 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9749 bool Ret = false;
9750
9751 // If the overload expression doesn't have the form of a pointer to
9752 // member, don't try to convert it to a pointer-to-member type.
9753 if (IsInvalidFormOfPointerToMemberFunction())
9754 return false;
9755
9756 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9757 E = OvlExpr->decls_end();
9758 I != E; ++I) {
9759 // Look through any using declarations to find the underlying function.
9760 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9761
9762 // C++ [over.over]p3:
9763 // Non-member functions and static member functions match
9764 // targets of type "pointer-to-function" or "reference-to-function."
9765 // Nonstatic member functions match targets of
9766 // type "pointer-to-member-function."
9767 // Note that according to DR 247, the containing class does not matter.
9768 if (FunctionTemplateDecl *FunctionTemplate
9769 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9770 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9771 Ret = true;
9772 }
9773 // If we have explicit template arguments supplied, skip non-templates.
9774 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9775 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9776 Ret = true;
9777 }
9778 assert(Ret || Matches.empty());
9779 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009780 }
9781
Douglas Gregorb491ed32011-02-19 21:32:49 +00009782 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009783 // [...] and any given function template specialization F1 is
9784 // eliminated if the set contains a second function template
9785 // specialization whose function template is more specialized
9786 // than the function template of F1 according to the partial
9787 // ordering rules of 14.5.5.2.
9788
9789 // The algorithm specified above is quadratic. We instead use a
9790 // two-pass algorithm (similar to the one used to identify the
9791 // best viable function in an overload set) that identifies the
9792 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009793
9794 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9795 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9796 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009797
Larisse Voufo98b20f12013-07-19 23:00:19 +00009798 // TODO: It looks like FailedCandidates does not serve much purpose
9799 // here, since the no_viable diagnostic has index 0.
9800 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009801 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009802 SourceExpr->getLocStart(), S.PDiag(),
9803 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9804 .second->getDeclName(),
9805 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9806 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009807
Douglas Gregorb491ed32011-02-19 21:32:49 +00009808 if (Result != MatchesCopy.end()) {
9809 // Make it the first and only element
9810 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9811 Matches[0].second = cast<FunctionDecl>(*Result);
9812 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009813 }
9814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009815
Douglas Gregorb491ed32011-02-19 21:32:49 +00009816 void EliminateAllTemplateMatches() {
9817 // [...] any function template specializations in the set are
9818 // eliminated if the set also contains a non-template function, [...]
9819 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9820 if (Matches[I].second->getPrimaryTemplate() == 0)
9821 ++I;
9822 else {
9823 Matches[I] = Matches[--N];
9824 Matches.set_size(N);
9825 }
9826 }
9827 }
9828
9829public:
9830 void ComplainNoMatchesFound() const {
9831 assert(Matches.empty());
9832 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9833 << OvlExpr->getName() << TargetFunctionType
9834 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009835 if (FailedCandidates.empty())
9836 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9837 else {
9838 // We have some deduction failure messages. Use them to diagnose
9839 // the function templates, and diagnose the non-template candidates
9840 // normally.
9841 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9842 IEnd = OvlExpr->decls_end();
9843 I != IEnd; ++I)
9844 if (FunctionDecl *Fun =
9845 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9846 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9847 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9848 }
9849 }
9850
Douglas Gregorb491ed32011-02-19 21:32:49 +00009851 bool IsInvalidFormOfPointerToMemberFunction() const {
9852 return TargetTypeIsNonStaticMemberFunction &&
9853 !OvlExprInfo.HasFormOfMemberPointer;
9854 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009855
Douglas Gregorb491ed32011-02-19 21:32:49 +00009856 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9857 // TODO: Should we condition this on whether any functions might
9858 // have matched, or is it more appropriate to do that in callers?
9859 // TODO: a fixit wouldn't hurt.
9860 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9861 << TargetType << OvlExpr->getSourceRange();
9862 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009863
9864 bool IsStaticMemberFunctionFromBoundPointer() const {
9865 return StaticMemberFunctionFromBoundPointer;
9866 }
9867
9868 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9869 S.Diag(OvlExpr->getLocStart(),
9870 diag::err_invalid_form_pointer_member_function)
9871 << OvlExpr->getSourceRange();
9872 }
9873
Douglas Gregorb491ed32011-02-19 21:32:49 +00009874 void ComplainOfInvalidConversion() const {
9875 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9876 << OvlExpr->getName() << TargetType;
9877 }
9878
9879 void ComplainMultipleMatchesFound() const {
9880 assert(Matches.size() > 1);
9881 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9882 << OvlExpr->getName()
9883 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009884 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009885 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009886
9887 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9888
Douglas Gregorb491ed32011-02-19 21:32:49 +00009889 int getNumMatches() const { return Matches.size(); }
9890
9891 FunctionDecl* getMatchingFunctionDecl() const {
9892 if (Matches.size() != 1) return 0;
9893 return Matches[0].second;
9894 }
9895
9896 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9897 if (Matches.size() != 1) return 0;
9898 return &Matches[0].first;
9899 }
9900};
9901
9902/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9903/// an overloaded function (C++ [over.over]), where @p From is an
9904/// expression with overloaded function type and @p ToType is the type
9905/// we're trying to resolve to. For example:
9906///
9907/// @code
9908/// int f(double);
9909/// int f(int);
9910///
9911/// int (*pfd)(double) = f; // selects f(double)
9912/// @endcode
9913///
9914/// This routine returns the resulting FunctionDecl if it could be
9915/// resolved, and NULL otherwise. When @p Complain is true, this
9916/// routine will emit diagnostics if there is an error.
9917FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009918Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9919 QualType TargetType,
9920 bool Complain,
9921 DeclAccessPair &FoundResult,
9922 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009923 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009924
9925 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9926 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009927 int NumMatches = Resolver.getNumMatches();
9928 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009929 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009930 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9931 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9932 else
9933 Resolver.ComplainNoMatchesFound();
9934 }
9935 else if (NumMatches > 1 && Complain)
9936 Resolver.ComplainMultipleMatchesFound();
9937 else if (NumMatches == 1) {
9938 Fn = Resolver.getMatchingFunctionDecl();
9939 assert(Fn);
9940 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +00009941 if (Complain) {
9942 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9943 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9944 else
9945 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9946 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009947 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009948
9949 if (pHadMultipleCandidates)
9950 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009951 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009952}
9953
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009954/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009955/// resolve that overloaded function expression down to a single function.
9956///
9957/// This routine can only resolve template-ids that refer to a single function
9958/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009959/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009960/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +00009961///
9962/// If no template-ids are found, no diagnostics are emitted and NULL is
9963/// returned.
John McCall0009fcc2011-04-26 20:42:42 +00009964FunctionDecl *
9965Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9966 bool Complain,
9967 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009968 // C++ [over.over]p1:
9969 // [...] [Note: any redundant set of parentheses surrounding the
9970 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009971 // C++ [over.over]p1:
9972 // [...] The overloaded function name can be preceded by the &
9973 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009974
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009975 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009976 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009977 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009978
9979 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009980 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009981 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009982
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009983 // Look through all of the overloaded functions, searching for one
9984 // whose type matches exactly.
9985 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009986 for (UnresolvedSetIterator I = ovl->decls_begin(),
9987 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009988 // C++0x [temp.arg.explicit]p3:
9989 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009990 // where deduction is not done, if a template argument list is
9991 // specified and it, along with any default template arguments,
9992 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009993 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009994 FunctionTemplateDecl *FunctionTemplate
9995 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009996
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009997 // C++ [over.over]p2:
9998 // If the name is a function template, template argument deduction is
9999 // done (14.8.2.2), and if the argument deduction succeeds, the
10000 // resulting template argument list is used to generate a single
10001 // function template specialization, which is added to the set of
10002 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010003 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010004 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010005 if (TemplateDeductionResult Result
10006 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010007 Specialization, Info,
10008 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010009 // Make a note of the failed deduction for diagnostics.
10010 // TODO: Actually use the failed-deduction info?
10011 FailedCandidates.addCandidate()
10012 .set(FunctionTemplate->getTemplatedDecl(),
10013 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010014 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010015 }
10016
John McCall0009fcc2011-04-26 20:42:42 +000010017 assert(Specialization && "no specialization and no error?");
10018
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010019 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010020 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010021 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010022 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10023 << ovl->getName();
10024 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010025 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010026 return 0;
John McCall0009fcc2011-04-26 20:42:42 +000010027 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010028
John McCall0009fcc2011-04-26 20:42:42 +000010029 Matched = Specialization;
10030 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010032
Richard Smith2a7d4812013-05-04 07:00:32 +000010033 if (Matched && getLangOpts().CPlusPlus1y &&
10034 Matched->getResultType()->isUndeducedType() &&
10035 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10036 return 0;
10037
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010038 return Matched;
10039}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010040
Douglas Gregor1beec452011-03-12 01:48:56 +000010041
10042
10043
John McCall50a2c2c2011-10-11 23:14:30 +000010044// Resolve and fix an overloaded expression that can be resolved
10045// because it identifies a single function template specialization.
10046//
Douglas Gregor1beec452011-03-12 01:48:56 +000010047// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010048//
10049// Return true if it was logically possible to so resolve the
10050// expression, regardless of whether or not it succeeded. Always
10051// returns true if 'complain' is set.
10052bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10053 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10054 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010055 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010056 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010057 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010058
John McCall50a2c2c2011-10-11 23:14:30 +000010059 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010060
John McCall0009fcc2011-04-26 20:42:42 +000010061 DeclAccessPair found;
10062 ExprResult SingleFunctionExpression;
10063 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10064 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010065 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010066 SrcExpr = ExprError();
10067 return true;
10068 }
John McCall0009fcc2011-04-26 20:42:42 +000010069
10070 // It is only correct to resolve to an instance method if we're
10071 // resolving a form that's permitted to be a pointer to member.
10072 // Otherwise we'll end up making a bound member expression, which
10073 // is illegal in all the contexts we resolve like this.
10074 if (!ovl.HasFormOfMemberPointer &&
10075 isa<CXXMethodDecl>(fn) &&
10076 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010077 if (!complain) return false;
10078
10079 Diag(ovl.Expression->getExprLoc(),
10080 diag::err_bound_member_function)
10081 << 0 << ovl.Expression->getSourceRange();
10082
10083 // TODO: I believe we only end up here if there's a mix of
10084 // static and non-static candidates (otherwise the expression
10085 // would have 'bound member' type, not 'overload' type).
10086 // Ideally we would note which candidate was chosen and why
10087 // the static candidates were rejected.
10088 SrcExpr = ExprError();
10089 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010090 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010091
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010092 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010093 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +000010094 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +000010095
10096 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010097 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010098 SingleFunctionExpression =
10099 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +000010100 if (SingleFunctionExpression.isInvalid()) {
10101 SrcExpr = ExprError();
10102 return true;
10103 }
10104 }
John McCall0009fcc2011-04-26 20:42:42 +000010105 }
10106
10107 if (!SingleFunctionExpression.isUsable()) {
10108 if (complain) {
10109 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10110 << ovl.Expression->getName()
10111 << DestTypeForComplaining
10112 << OpRangeForComplaining
10113 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010114 NoteAllOverloadCandidates(SrcExpr.get());
10115
10116 SrcExpr = ExprError();
10117 return true;
10118 }
10119
10120 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010121 }
10122
John McCall50a2c2c2011-10-11 23:14:30 +000010123 SrcExpr = SingleFunctionExpression;
10124 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010125}
10126
Douglas Gregorcabea402009-09-22 15:41:20 +000010127/// \brief Add a single candidate to the overload set.
10128static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010129 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010130 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010131 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010132 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010133 bool PartialOverloading,
10134 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010135 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010136 if (isa<UsingShadowDecl>(Callee))
10137 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10138
Douglas Gregorcabea402009-09-22 15:41:20 +000010139 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010140 if (ExplicitTemplateArgs) {
10141 assert(!KnownValid && "Explicit template arguments?");
10142 return;
10143 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010144 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10145 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010146 return;
John McCalld14a8642009-11-21 08:51:07 +000010147 }
10148
10149 if (FunctionTemplateDecl *FuncTemplate
10150 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010151 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010152 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010153 return;
10154 }
10155
Richard Smith95ce4f62011-06-26 22:19:54 +000010156 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010157}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010158
Douglas Gregorcabea402009-09-22 15:41:20 +000010159/// \brief Add the overload candidates named by callee and/or found by argument
10160/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010161void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010162 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010163 OverloadCandidateSet &CandidateSet,
10164 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010165
10166#ifndef NDEBUG
10167 // Verify that ArgumentDependentLookup is consistent with the rules
10168 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010169 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010170 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10171 // and let Y be the lookup set produced by argument dependent
10172 // lookup (defined as follows). If X contains
10173 //
10174 // -- a declaration of a class member, or
10175 //
10176 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010177 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010178 //
10179 // -- a declaration that is neither a function or a function
10180 // template
10181 //
10182 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010183
John McCall57500772009-12-16 12:17:52 +000010184 if (ULE->requiresADL()) {
10185 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10186 E = ULE->decls_end(); I != E; ++I) {
10187 assert(!(*I)->getDeclContext()->isRecord());
10188 assert(isa<UsingShadowDecl>(*I) ||
10189 !(*I)->getDeclContext()->isFunctionOrMethod());
10190 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010191 }
10192 }
10193#endif
10194
John McCall57500772009-12-16 12:17:52 +000010195 // It would be nice to avoid this copy.
10196 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +000010197 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010198 if (ULE->hasExplicitTemplateArgs()) {
10199 ULE->copyTemplateArgumentsInto(TABuffer);
10200 ExplicitTemplateArgs = &TABuffer;
10201 }
10202
10203 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10204 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010205 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10206 CandidateSet, PartialOverloading,
10207 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010208
John McCall57500772009-12-16 12:17:52 +000010209 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +000010210 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +000010211 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010212 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010213 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010214}
John McCalld681c392009-12-16 08:11:27 +000010215
Richard Smith0603bbb2013-06-12 22:56:54 +000010216/// Determine whether a declaration with the specified name could be moved into
10217/// a different namespace.
10218static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10219 switch (Name.getCXXOverloadedOperator()) {
10220 case OO_New: case OO_Array_New:
10221 case OO_Delete: case OO_Array_Delete:
10222 return false;
10223
10224 default:
10225 return true;
10226 }
10227}
10228
Richard Smith998a5912011-06-05 22:42:48 +000010229/// Attempt to recover from an ill-formed use of a non-dependent name in a
10230/// template, where the non-dependent name was declared after the template
10231/// was defined. This is common in code written for a compilers which do not
10232/// correctly implement two-stage name lookup.
10233///
10234/// Returns true if a viable candidate was found and a diagnostic was issued.
10235static bool
10236DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10237 const CXXScopeSpec &SS, LookupResult &R,
10238 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010239 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010240 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10241 return false;
10242
10243 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010244 if (DC->isTransparentContext())
10245 continue;
10246
Richard Smith998a5912011-06-05 22:42:48 +000010247 SemaRef.LookupQualifiedName(R, DC);
10248
10249 if (!R.empty()) {
10250 R.suppressDiagnostics();
10251
10252 if (isa<CXXRecordDecl>(DC)) {
10253 // Don't diagnose names we find in classes; we get much better
10254 // diagnostics for these from DiagnoseEmptyLookup.
10255 R.clear();
10256 return false;
10257 }
10258
10259 OverloadCandidateSet Candidates(FnLoc);
10260 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10261 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010262 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010263 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010264
10265 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010266 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010267 // No viable functions. Don't bother the user with notes for functions
10268 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010269 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010270 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010271 }
Richard Smith998a5912011-06-05 22:42:48 +000010272
10273 // Find the namespaces where ADL would have looked, and suggest
10274 // declaring the function there instead.
10275 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10276 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010277 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010278 AssociatedNamespaces,
10279 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010280 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010281 if (canBeDeclaredInNamespace(R.getLookupName())) {
10282 DeclContext *Std = SemaRef.getStdNamespace();
10283 for (Sema::AssociatedNamespaceSet::iterator
10284 it = AssociatedNamespaces.begin(),
10285 end = AssociatedNamespaces.end(); it != end; ++it) {
10286 // Never suggest declaring a function within namespace 'std'.
10287 if (Std && Std->Encloses(*it))
10288 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010289
Richard Smith0603bbb2013-06-12 22:56:54 +000010290 // Never suggest declaring a function within a namespace with a
10291 // reserved name, like __gnu_cxx.
10292 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10293 if (NS &&
10294 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10295 continue;
10296
10297 SuggestedNamespaces.insert(*it);
10298 }
Richard Smith998a5912011-06-05 22:42:48 +000010299 }
10300
10301 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10302 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010303 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010304 SemaRef.Diag(Best->Function->getLocation(),
10305 diag::note_not_found_by_two_phase_lookup)
10306 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010307 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010308 SemaRef.Diag(Best->Function->getLocation(),
10309 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010310 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010311 } else {
10312 // FIXME: It would be useful to list the associated namespaces here,
10313 // but the diagnostics infrastructure doesn't provide a way to produce
10314 // a localized representation of a list of items.
10315 SemaRef.Diag(Best->Function->getLocation(),
10316 diag::note_not_found_by_two_phase_lookup)
10317 << R.getLookupName() << 2;
10318 }
10319
10320 // Try to recover by calling this function.
10321 return true;
10322 }
10323
10324 R.clear();
10325 }
10326
10327 return false;
10328}
10329
10330/// Attempt to recover from ill-formed use of a non-dependent operator in a
10331/// template, where the non-dependent operator was declared after the template
10332/// was defined.
10333///
10334/// Returns true if a viable candidate was found and a diagnostic was issued.
10335static bool
10336DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10337 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010338 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010339 DeclarationName OpName =
10340 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10341 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10342 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010343 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010344}
10345
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010346namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010347class BuildRecoveryCallExprRAII {
10348 Sema &SemaRef;
10349public:
10350 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10351 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10352 SemaRef.IsBuildingRecoveryCallExpr = true;
10353 }
10354
10355 ~BuildRecoveryCallExprRAII() {
10356 SemaRef.IsBuildingRecoveryCallExpr = false;
10357 }
10358};
10359
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010360}
10361
John McCalld681c392009-12-16 08:11:27 +000010362/// Attempts to recover from a call where no functions were found.
10363///
10364/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010365static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010366BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010367 UnresolvedLookupExpr *ULE,
10368 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010369 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010370 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010371 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010372 // Do not try to recover if it is already building a recovery call.
10373 // This stops infinite loops for template instantiations like
10374 //
10375 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10376 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10377 //
10378 if (SemaRef.IsBuildingRecoveryCallExpr)
10379 return ExprError();
10380 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010381
10382 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010383 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010384 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010385
John McCall57500772009-12-16 12:17:52 +000010386 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +000010387 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010388 if (ULE->hasExplicitTemplateArgs()) {
10389 ULE->copyTemplateArgumentsInto(TABuffer);
10390 ExplicitTemplateArgs = &TABuffer;
10391 }
10392
John McCalld681c392009-12-16 08:11:27 +000010393 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10394 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010395 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10396 ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010397 NoTypoCorrectionCCC RejectAll;
10398 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10399 (CorrectionCandidateCallback*)&Validator :
10400 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010401 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010402 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010403 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010404 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010405 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010406 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010407
John McCall57500772009-12-16 12:17:52 +000010408 assert(!R.empty() && "lookup results empty despite recovery");
10409
10410 // Build an implicit member call if appropriate. Just drop the
10411 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010412 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010413 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010414 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10415 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010416 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010417 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010418 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010419 else
10420 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10421
10422 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010423 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010424
10425 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010426 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010427 // end up here.
John McCallb268a282010-08-23 23:25:46 +000010428 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010429 MultiExprArg(Args.data(), Args.size()),
10430 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010431}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010432
Sam Panzer0f384432012-08-21 00:52:01 +000010433/// \brief Constructs and populates an OverloadedCandidateSet from
10434/// the given function.
10435/// \returns true when an the ExprResult output parameter has been set.
10436bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10437 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010438 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010439 SourceLocation RParenLoc,
10440 OverloadCandidateSet *CandidateSet,
10441 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010442#ifndef NDEBUG
10443 if (ULE->requiresADL()) {
10444 // To do ADL, we must have found an unqualified name.
10445 assert(!ULE->getQualifier() && "qualified name with ADL");
10446
10447 // We don't perform ADL for implicit declarations of builtins.
10448 // Verify that this was correctly set up.
10449 FunctionDecl *F;
10450 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10451 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10452 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010453 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010454
John McCall57500772009-12-16 12:17:52 +000010455 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010456 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010457 }
John McCall57500772009-12-16 12:17:52 +000010458#endif
10459
John McCall4124c492011-10-17 18:40:02 +000010460 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010461 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010462 *Result = ExprError();
10463 return true;
10464 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010465
John McCall57500772009-12-16 12:17:52 +000010466 // Add the functions denoted by the callee to the set of candidate
10467 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010468 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010469
10470 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010471 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10472 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010473 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010474 // In Microsoft mode, if we are inside a template class member function then
10475 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010476 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010477 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010478 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010479 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010480 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010481 Context.DependentTy, VK_RValue,
10482 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010483 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +000010484 *Result = Owned(CE);
10485 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010486 }
Sam Panzer0f384432012-08-21 00:52:01 +000010487 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010488 }
John McCalld681c392009-12-16 08:11:27 +000010489
John McCall4124c492011-10-17 18:40:02 +000010490 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010491 return false;
10492}
John McCall4124c492011-10-17 18:40:02 +000010493
Sam Panzer0f384432012-08-21 00:52:01 +000010494/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10495/// the completed call expression. If overload resolution fails, emits
10496/// diagnostics and returns ExprError()
10497static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10498 UnresolvedLookupExpr *ULE,
10499 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010500 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010501 SourceLocation RParenLoc,
10502 Expr *ExecConfig,
10503 OverloadCandidateSet *CandidateSet,
10504 OverloadCandidateSet::iterator *Best,
10505 OverloadingResult OverloadResult,
10506 bool AllowTypoCorrection) {
10507 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010508 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010509 RParenLoc, /*EmptyLookup=*/true,
10510 AllowTypoCorrection);
10511
10512 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010513 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010514 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010515 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010516 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10517 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010518 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010519 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10520 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010521 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010522
Richard Smith998a5912011-06-05 22:42:48 +000010523 case OR_No_Viable_Function: {
10524 // Try to recover by looking for viable functions which the user might
10525 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010526 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010527 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010528 /*EmptyLookup=*/false,
10529 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010530 if (!Recovery.isInvalid())
10531 return Recovery;
10532
Sam Panzer0f384432012-08-21 00:52:01 +000010533 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010534 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010535 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010536 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010537 break;
Richard Smith998a5912011-06-05 22:42:48 +000010538 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010539
10540 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010541 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010542 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010543 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010544 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010545
Sam Panzer0f384432012-08-21 00:52:01 +000010546 case OR_Deleted: {
10547 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10548 << (*Best)->Function->isDeleted()
10549 << ULE->getName()
10550 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10551 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010552 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010553
Sam Panzer0f384432012-08-21 00:52:01 +000010554 // We emitted an error for the unvailable/deleted function call but keep
10555 // the call in the AST.
10556 FunctionDecl *FDecl = (*Best)->Function;
10557 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010558 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10559 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010560 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010561 }
10562
Douglas Gregorb412e172010-07-25 18:17:45 +000010563 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010564 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010565}
10566
Sam Panzer0f384432012-08-21 00:52:01 +000010567/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10568/// (which eventually refers to the declaration Func) and the call
10569/// arguments Args/NumArgs, attempt to resolve the function call down
10570/// to a specific function. If overload resolution succeeds, returns
10571/// the call expression produced by overload resolution.
10572/// Otherwise, emits diagnostics and returns ExprError.
10573ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10574 UnresolvedLookupExpr *ULE,
10575 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010576 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010577 SourceLocation RParenLoc,
10578 Expr *ExecConfig,
10579 bool AllowTypoCorrection) {
10580 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10581 ExprResult result;
10582
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010583 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10584 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010585 return result;
10586
10587 OverloadCandidateSet::iterator Best;
10588 OverloadingResult OverloadResult =
10589 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10590
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010591 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010592 RParenLoc, ExecConfig, &CandidateSet,
10593 &Best, OverloadResult,
10594 AllowTypoCorrection);
10595}
10596
John McCall4c4c1df2010-01-26 03:27:55 +000010597static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010598 return Functions.size() > 1 ||
10599 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10600}
10601
Douglas Gregor084d8552009-03-13 23:49:33 +000010602/// \brief Create a unary operation that may resolve to an overloaded
10603/// operator.
10604///
10605/// \param OpLoc The location of the operator itself (e.g., '*').
10606///
10607/// \param OpcIn The UnaryOperator::Opcode that describes this
10608/// operator.
10609///
James Dennett18348b62012-06-22 08:52:37 +000010610/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010611/// considered by overload resolution. The caller needs to build this
10612/// set based on the context using, e.g.,
10613/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10614/// set should not contain any member functions; those will be added
10615/// by CreateOverloadedUnaryOp().
10616///
James Dennett91738ff2012-06-22 10:32:46 +000010617/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010618ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010619Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10620 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010621 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010622 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010623
10624 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10625 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10626 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010627 // TODO: provide better source location info.
10628 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010629
John McCall4124c492011-10-17 18:40:02 +000010630 if (checkPlaceholderForOverload(*this, Input))
10631 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010632
Douglas Gregor084d8552009-03-13 23:49:33 +000010633 Expr *Args[2] = { Input, 0 };
10634 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010635
Douglas Gregor084d8552009-03-13 23:49:33 +000010636 // For post-increment and post-decrement, add the implicit '0' as
10637 // the second argument, so that we know this is a post-increment or
10638 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010639 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010640 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010641 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10642 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010643 NumArgs = 2;
10644 }
10645
Richard Smithe54c3072013-05-05 15:51:06 +000010646 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10647
Douglas Gregor084d8552009-03-13 23:49:33 +000010648 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010649 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +000010650 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010651 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +000010652 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010653 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +000010654 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010655
John McCall58cc69d2010-01-27 01:50:18 +000010656 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010657 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010658 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010659 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010660 /*ADL*/ true, IsOverloaded(Fns),
10661 Fns.begin(), Fns.end());
Richard Smithe54c3072013-05-05 15:51:06 +000010662 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregor084d8552009-03-13 23:49:33 +000010663 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010664 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010665 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010666 }
10667
10668 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010669 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010670
10671 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010672 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010673
10674 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010675 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010676
John McCall4c4c1df2010-01-26 03:27:55 +000010677 // Add candidates from ADL.
Richard Smithe54c3072013-05-05 15:51:06 +000010678 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10679 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall4c4c1df2010-01-26 03:27:55 +000010680 CandidateSet);
10681
Douglas Gregor084d8552009-03-13 23:49:33 +000010682 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010683 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010684
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010685 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10686
Douglas Gregor084d8552009-03-13 23:49:33 +000010687 // Perform overload resolution.
10688 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010689 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010690 case OR_Success: {
10691 // We found a built-in operator or an overloaded operator.
10692 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010693
Douglas Gregor084d8552009-03-13 23:49:33 +000010694 if (FnDecl) {
10695 // We matched an overloaded operator. Build a call to that
10696 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010697
Douglas Gregor084d8552009-03-13 23:49:33 +000010698 // Convert the arguments.
10699 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010700 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010701
John Wiegley01296292011-04-08 18:41:53 +000010702 ExprResult InputRes =
10703 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10704 Best->FoundDecl, Method);
10705 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010706 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010707 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010708 } else {
10709 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010710 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010711 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010712 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010713 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010714 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010715 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010716 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010717 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010718 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010719 }
10720
Douglas Gregor084d8552009-03-13 23:49:33 +000010721 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010722 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010723 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010724 if (FnExpr.isInvalid())
10725 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010726
Richard Smithc1564702013-11-15 02:58:23 +000010727 // Determine the result type.
10728 QualType ResultTy = FnDecl->getResultType();
10729 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10730 ResultTy = ResultTy.getNonLValueExprType(Context);
10731
Eli Friedman030eee42009-11-18 03:58:17 +000010732 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010733 CallExpr *TheCall =
Richard Smithe54c3072013-05-05 15:51:06 +000010734 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010735 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010736
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010737 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010738 FnDecl))
10739 return ExprError();
10740
John McCallb268a282010-08-23 23:25:46 +000010741 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010742 } else {
10743 // We matched a built-in operator. Convert the arguments, then
10744 // break out so that we will build the appropriate built-in
10745 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010746 ExprResult InputRes =
10747 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10748 Best->Conversions[0], AA_Passing);
10749 if (InputRes.isInvalid())
10750 return ExprError();
10751 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010752 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010753 }
John Wiegley01296292011-04-08 18:41:53 +000010754 }
10755
10756 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010757 // This is an erroneous use of an operator which can be overloaded by
10758 // a non-member function. Check for non-member operators which were
10759 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010760 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010761 // FIXME: Recover by calling the found function.
10762 return ExprError();
10763
John Wiegley01296292011-04-08 18:41:53 +000010764 // No viable function; fall through to handling this as a
10765 // built-in operator, which will produce an error message for us.
10766 break;
10767
10768 case OR_Ambiguous:
10769 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10770 << UnaryOperator::getOpcodeStr(Opc)
10771 << Input->getType()
10772 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010773 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010774 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10775 return ExprError();
10776
10777 case OR_Deleted:
10778 Diag(OpLoc, diag::err_ovl_deleted_oper)
10779 << Best->Function->isDeleted()
10780 << UnaryOperator::getOpcodeStr(Opc)
10781 << getDeletedOrUnavailableSuffix(Best->Function)
10782 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010783 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010784 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010785 return ExprError();
10786 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010787
10788 // Either we found no viable overloaded operator or we matched a
10789 // built-in operator. In either case, fall through to trying to
10790 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010791 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010792}
10793
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010794/// \brief Create a binary operation that may resolve to an overloaded
10795/// operator.
10796///
10797/// \param OpLoc The location of the operator itself (e.g., '+').
10798///
10799/// \param OpcIn The BinaryOperator::Opcode that describes this
10800/// operator.
10801///
James Dennett18348b62012-06-22 08:52:37 +000010802/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010803/// considered by overload resolution. The caller needs to build this
10804/// set based on the context using, e.g.,
10805/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10806/// set should not contain any member functions; those will be added
10807/// by CreateOverloadedBinOp().
10808///
10809/// \param LHS Left-hand argument.
10810/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010811ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010812Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010813 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010814 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010815 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010816 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010817 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010818
10819 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10820 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10821 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10822
10823 // If either side is type-dependent, create an appropriate dependent
10824 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010825 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010826 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010827 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010828 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010829 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010830 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010831 Context.DependentTy,
10832 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010833 OpLoc,
10834 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010835
Douglas Gregor5287f092009-11-05 00:51:44 +000010836 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10837 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010838 VK_LValue,
10839 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010840 Context.DependentTy,
10841 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010842 OpLoc,
10843 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010844 }
John McCall4c4c1df2010-01-26 03:27:55 +000010845
10846 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010847 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010848 // TODO: provide better source location info in DNLoc component.
10849 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010850 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010851 = UnresolvedLookupExpr::Create(Context, NamingClass,
10852 NestedNameSpecifierLoc(), OpNameInfo,
10853 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010854 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010855 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10856 Context.DependentTy, VK_RValue,
10857 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010858 }
10859
John McCall4124c492011-10-17 18:40:02 +000010860 // Always do placeholder-like conversions on the RHS.
10861 if (checkPlaceholderForOverload(*this, Args[1]))
10862 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010863
John McCall526ab472011-10-25 17:37:35 +000010864 // Do placeholder-like conversion on the LHS; note that we should
10865 // not get here with a PseudoObject LHS.
10866 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010867 if (checkPlaceholderForOverload(*this, Args[0]))
10868 return ExprError();
10869
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010870 // If this is the assignment operator, we only perform overload resolution
10871 // if the left-hand side is a class or enumeration type. This is actually
10872 // a hack. The standard requires that we do overload resolution between the
10873 // various built-in candidates, but as DR507 points out, this can lead to
10874 // problems. So we do it this way, which pretty much follows what GCC does.
10875 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010876 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010877 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010878
John McCalle26a8722010-12-04 08:14:53 +000010879 // If this is the .* operator, which is not overloadable, just
10880 // create a built-in binary operator.
10881 if (Opc == BO_PtrMemD)
10882 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10883
Douglas Gregor084d8552009-03-13 23:49:33 +000010884 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010885 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010886
10887 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010888 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010889
10890 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010891 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010892
John McCall4c4c1df2010-01-26 03:27:55 +000010893 // Add candidates from ADL.
10894 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010895 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010896 /*ExplicitTemplateArgs*/ 0,
10897 CandidateSet);
10898
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010899 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010900 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010901
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010902 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10903
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010904 // Perform overload resolution.
10905 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010906 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010907 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010908 // We found a built-in operator or an overloaded operator.
10909 FunctionDecl *FnDecl = Best->Function;
10910
10911 if (FnDecl) {
10912 // We matched an overloaded operator. Build a call to that
10913 // operator.
10914
10915 // Convert the arguments.
10916 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010917 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010918 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010919
Chandler Carruth8e543b32010-12-12 08:17:55 +000010920 ExprResult Arg1 =
10921 PerformCopyInitialization(
10922 InitializedEntity::InitializeParameter(Context,
10923 FnDecl->getParamDecl(0)),
10924 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010925 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010926 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010927
John Wiegley01296292011-04-08 18:41:53 +000010928 ExprResult Arg0 =
10929 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10930 Best->FoundDecl, Method);
10931 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010932 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010933 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010934 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010935 } else {
10936 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010937 ExprResult Arg0 = PerformCopyInitialization(
10938 InitializedEntity::InitializeParameter(Context,
10939 FnDecl->getParamDecl(0)),
10940 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010941 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010942 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010943
Chandler Carruth8e543b32010-12-12 08:17:55 +000010944 ExprResult Arg1 =
10945 PerformCopyInitialization(
10946 InitializedEntity::InitializeParameter(Context,
10947 FnDecl->getParamDecl(1)),
10948 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010949 if (Arg1.isInvalid())
10950 return ExprError();
10951 Args[0] = LHS = Arg0.takeAs<Expr>();
10952 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010953 }
10954
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010955 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010956 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000010957 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010958 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010959 if (FnExpr.isInvalid())
10960 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010961
Richard Smithc1564702013-11-15 02:58:23 +000010962 // Determine the result type.
10963 QualType ResultTy = FnDecl->getResultType();
10964 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10965 ResultTy = ResultTy.getNonLValueExprType(Context);
10966
John McCallb268a282010-08-23 23:25:46 +000010967 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010968 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010969 Args, ResultTy, VK, OpLoc,
10970 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010971
10972 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010973 FnDecl))
10974 return ExprError();
10975
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000010976 ArrayRef<const Expr *> ArgsArray(Args, 2);
10977 // Cut off the implicit 'this'.
10978 if (isa<CXXMethodDecl>(FnDecl))
10979 ArgsArray = ArgsArray.slice(1);
10980 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10981 TheCall->getSourceRange(), VariadicDoesNotApply);
10982
John McCallb268a282010-08-23 23:25:46 +000010983 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010984 } else {
10985 // We matched a built-in operator. Convert the arguments, then
10986 // break out so that we will build the appropriate built-in
10987 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010988 ExprResult ArgsRes0 =
10989 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10990 Best->Conversions[0], AA_Passing);
10991 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010992 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010993 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010994
John Wiegley01296292011-04-08 18:41:53 +000010995 ExprResult ArgsRes1 =
10996 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10997 Best->Conversions[1], AA_Passing);
10998 if (ArgsRes1.isInvalid())
10999 return ExprError();
11000 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011001 break;
11002 }
11003 }
11004
Douglas Gregor66950a32009-09-30 21:46:01 +000011005 case OR_No_Viable_Function: {
11006 // C++ [over.match.oper]p9:
11007 // If the operator is the operator , [...] and there are no
11008 // viable functions, then the operator is assumed to be the
11009 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011010 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011011 break;
11012
Chandler Carruth8e543b32010-12-12 08:17:55 +000011013 // For class as left operand for assignment or compound assigment
11014 // operator do not fall through to handling in built-in, but report that
11015 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011016 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011017 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011018 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011019 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11020 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011021 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011022 if (Args[0]->getType()->isIncompleteType()) {
11023 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11024 << Args[0]->getType()
11025 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11026 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011027 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011028 // This is an erroneous use of an operator which can be overloaded by
11029 // a non-member function. Check for non-member operators which were
11030 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011031 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011032 // FIXME: Recover by calling the found function.
11033 return ExprError();
11034
Douglas Gregor66950a32009-09-30 21:46:01 +000011035 // No viable function; try to create a built-in operation, which will
11036 // produce an error. Then, show the non-viable candidates.
11037 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011039 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011040 "C++ binary operator overloading is missing candidates!");
11041 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011042 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011043 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011044 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011045 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011046
11047 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011048 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011049 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011050 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011051 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011052 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011053 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011054 return ExprError();
11055
11056 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011057 if (isImplicitlyDeleted(Best->Function)) {
11058 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11059 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011060 << Context.getRecordType(Method->getParent())
11061 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011062
Richard Smithde1a4872012-12-28 12:23:24 +000011063 // The user probably meant to call this special member. Just
11064 // explain why it's deleted.
11065 NoteDeletedFunction(Method);
11066 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011067 } else {
11068 Diag(OpLoc, diag::err_ovl_deleted_oper)
11069 << Best->Function->isDeleted()
11070 << BinaryOperator::getOpcodeStr(Opc)
11071 << getDeletedOrUnavailableSuffix(Best->Function)
11072 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11073 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011074 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011075 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011076 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011077 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011078
Douglas Gregor66950a32009-09-30 21:46:01 +000011079 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011080 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011081}
11082
John McCalldadc5752010-08-24 06:29:42 +000011083ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011084Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11085 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011086 Expr *Base, Expr *Idx) {
11087 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011088 DeclarationName OpName =
11089 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11090
11091 // If either side is type-dependent, create an appropriate dependent
11092 // expression.
11093 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11094
John McCall58cc69d2010-01-27 01:50:18 +000011095 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011096 // CHECKME: no 'operator' keyword?
11097 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11098 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011099 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011100 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011101 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011102 /*ADL*/ true, /*Overloaded*/ false,
11103 UnresolvedSetIterator(),
11104 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011105 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011106
Sebastian Redladba46e2009-10-29 20:17:01 +000011107 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011108 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000011109 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000011110 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000011111 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000011112 }
11113
John McCall4124c492011-10-17 18:40:02 +000011114 // Handle placeholders on both operands.
11115 if (checkPlaceholderForOverload(*this, Args[0]))
11116 return ExprError();
11117 if (checkPlaceholderForOverload(*this, Args[1]))
11118 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011119
Sebastian Redladba46e2009-10-29 20:17:01 +000011120 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000011121 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011122
11123 // Subscript can only be overloaded as a member function.
11124
11125 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011126 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011127
11128 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011129 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011130
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011131 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11132
Sebastian Redladba46e2009-10-29 20:17:01 +000011133 // Perform overload resolution.
11134 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011135 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011136 case OR_Success: {
11137 // We found a built-in operator or an overloaded operator.
11138 FunctionDecl *FnDecl = Best->Function;
11139
11140 if (FnDecl) {
11141 // We matched an overloaded operator. Build a call to that
11142 // operator.
11143
John McCalla0296f72010-03-19 07:35:19 +000011144 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011145
Sebastian Redladba46e2009-10-29 20:17:01 +000011146 // Convert the arguments.
11147 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011148 ExprResult Arg0 =
11149 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
11150 Best->FoundDecl, Method);
11151 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011152 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011153 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011154
Anders Carlssona68e51e2010-01-29 18:37:50 +000011155 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011156 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011157 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011158 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011159 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011160 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000011161 Owned(Args[1]));
11162 if (InputInit.isInvalid())
11163 return ExprError();
11164
11165 Args[1] = InputInit.takeAs<Expr>();
11166
Sebastian Redladba46e2009-10-29 20:17:01 +000011167 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011168 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11169 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011170 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011171 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011172 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011173 OpLocInfo.getLoc(),
11174 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011175 if (FnExpr.isInvalid())
11176 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011177
Richard Smithc1564702013-11-15 02:58:23 +000011178 // Determine the result type
11179 QualType ResultTy = FnDecl->getResultType();
11180 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11181 ResultTy = ResultTy.getNonLValueExprType(Context);
11182
John McCallb268a282010-08-23 23:25:46 +000011183 CXXOperatorCallExpr *TheCall =
11184 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011185 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011186 ResultTy, VK, RLoc,
11187 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011188
John McCallb268a282010-08-23 23:25:46 +000011189 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000011190 FnDecl))
11191 return ExprError();
11192
John McCallb268a282010-08-23 23:25:46 +000011193 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011194 } else {
11195 // We matched a built-in operator. Convert the arguments, then
11196 // break out so that we will build the appropriate built-in
11197 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011198 ExprResult ArgsRes0 =
11199 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11200 Best->Conversions[0], AA_Passing);
11201 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011202 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011203 Args[0] = ArgsRes0.take();
11204
11205 ExprResult ArgsRes1 =
11206 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11207 Best->Conversions[1], AA_Passing);
11208 if (ArgsRes1.isInvalid())
11209 return ExprError();
11210 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011211
11212 break;
11213 }
11214 }
11215
11216 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011217 if (CandidateSet.empty())
11218 Diag(LLoc, diag::err_ovl_no_oper)
11219 << Args[0]->getType() << /*subscript*/ 0
11220 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11221 else
11222 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11223 << Args[0]->getType()
11224 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011225 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011226 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011227 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011228 }
11229
11230 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011231 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011232 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011233 << Args[0]->getType() << Args[1]->getType()
11234 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011235 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011236 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011237 return ExprError();
11238
11239 case OR_Deleted:
11240 Diag(LLoc, diag::err_ovl_deleted_oper)
11241 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011242 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011243 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011244 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011245 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011246 return ExprError();
11247 }
11248
11249 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011250 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011251}
11252
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011253/// BuildCallToMemberFunction - Build a call to a member
11254/// function. MemExpr is the expression that refers to the member
11255/// function (and includes the object parameter), Args/NumArgs are the
11256/// arguments to the function call (not including the object
11257/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011258/// expression refers to a non-static member function or an overloaded
11259/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011260ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011261Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011262 SourceLocation LParenLoc,
11263 MultiExprArg Args,
11264 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011265 assert(MemExprE->getType() == Context.BoundMemberTy ||
11266 MemExprE->getType() == Context.OverloadTy);
11267
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011268 // Dig out the member expression. This holds both the object
11269 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011270 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011271
John McCall0009fcc2011-04-26 20:42:42 +000011272 // Determine whether this is a call to a pointer-to-member function.
11273 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11274 assert(op->getType() == Context.BoundMemberTy);
11275 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11276
11277 QualType fnType =
11278 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11279
11280 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11281 QualType resultType = proto->getCallResultType(Context);
11282 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
11283
11284 // Check that the object type isn't more qualified than the
11285 // member function we're calling.
11286 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11287
11288 QualType objectType = op->getLHS()->getType();
11289 if (op->getOpcode() == BO_PtrMemI)
11290 objectType = objectType->castAs<PointerType>()->getPointeeType();
11291 Qualifiers objectQuals = objectType.getQualifiers();
11292
11293 Qualifiers difference = objectQuals - funcQuals;
11294 difference.removeObjCGCAttr();
11295 difference.removeAddressSpace();
11296 if (difference) {
11297 std::string qualsString = difference.getAsString();
11298 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11299 << fnType.getUnqualifiedType()
11300 << qualsString
11301 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11302 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011303
John McCall0009fcc2011-04-26 20:42:42 +000011304 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011305 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011306 resultType, valueKind, RParenLoc);
11307
11308 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011309 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000011310 call, 0))
11311 return ExprError();
11312
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011313 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011314 return ExprError();
11315
Richard Trieu9be9c682013-06-22 02:30:38 +000011316 if (CheckOtherCall(call, proto))
11317 return ExprError();
11318
John McCall0009fcc2011-04-26 20:42:42 +000011319 return MaybeBindToTemporary(call);
11320 }
11321
John McCall4124c492011-10-17 18:40:02 +000011322 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011323 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011324 return ExprError();
11325
John McCall10eae182009-11-30 22:42:35 +000011326 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011327 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000011328 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011329 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000011330 if (isa<MemberExpr>(NakedMemExpr)) {
11331 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011332 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011333 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011334 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011335 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011336 } else {
11337 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011338 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011339
John McCall6e9f8f62009-12-03 04:06:58 +000011340 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011341 Expr::Classification ObjectClassification
11342 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11343 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011344
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011345 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000011346 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000011347
John McCall2d74de92009-12-01 22:10:20 +000011348 // FIXME: avoid copy.
11349 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11350 if (UnresExpr->hasExplicitTemplateArgs()) {
11351 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11352 TemplateArgs = &TemplateArgsBuffer;
11353 }
11354
John McCall10eae182009-11-30 22:42:35 +000011355 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11356 E = UnresExpr->decls_end(); I != E; ++I) {
11357
John McCall6e9f8f62009-12-03 04:06:58 +000011358 NamedDecl *Func = *I;
11359 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11360 if (isa<UsingShadowDecl>(Func))
11361 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11362
Douglas Gregor02824322011-01-26 19:30:28 +000011363
Francois Pichet64225792011-01-18 05:04:39 +000011364 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011365 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011366 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011367 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011368 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011369 // If explicit template arguments were provided, we can't call a
11370 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011371 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011372 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011373
John McCalla0296f72010-03-19 07:35:19 +000011374 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011375 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011376 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011377 } else {
John McCall10eae182009-11-30 22:42:35 +000011378 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011379 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011380 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011381 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011382 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011383 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011384 }
Mike Stump11289f42009-09-09 15:08:12 +000011385
John McCall10eae182009-11-30 22:42:35 +000011386 DeclarationName DeclName = UnresExpr->getMemberName();
11387
John McCall4124c492011-10-17 18:40:02 +000011388 UnbridgedCasts.restore();
11389
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011390 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011391 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011392 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011393 case OR_Success:
11394 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011395 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011396 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011397 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11398 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011399 // If FoundDecl is different from Method (such as if one is a template
11400 // and the other a specialization), make sure DiagnoseUseOfDecl is
11401 // called on both.
11402 // FIXME: This would be more comprehensively addressed by modifying
11403 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11404 // being used.
11405 if (Method != FoundDecl.getDecl() &&
11406 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11407 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011408 break;
11409
11410 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011411 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011412 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011413 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011414 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011415 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011416 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011417
11418 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011419 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011420 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011421 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011422 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011423 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011424
11425 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011426 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011427 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011428 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011429 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011430 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011431 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011432 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011433 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011434 }
11435
John McCall16df1e52010-03-30 21:47:33 +000011436 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011437
John McCall2d74de92009-12-01 22:10:20 +000011438 // If overload resolution picked a static member, build a
11439 // non-member call based on that function.
11440 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011441 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11442 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011443 }
11444
John McCall10eae182009-11-30 22:42:35 +000011445 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011446 }
11447
John McCall7decc9e2010-11-18 06:31:45 +000011448 QualType ResultType = Method->getResultType();
11449 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11450 ResultType = ResultType.getNonLValueExprType(Context);
11451
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011452 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011453 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011454 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011455 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011456
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011457 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011458 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011459 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011460 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011461
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011462 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011463 // We only need to do this if there was actually an overload; otherwise
11464 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011465 if (!Method->isStatic()) {
11466 ExprResult ObjectArg =
11467 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11468 FoundDecl, Method);
11469 if (ObjectArg.isInvalid())
11470 return ExprError();
11471 MemExpr->setBase(ObjectArg.take());
11472 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011473
11474 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011475 const FunctionProtoType *Proto =
11476 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011477 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011478 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011479 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011480
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011481 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011482
Richard Smith55ce3522012-06-25 20:30:08 +000011483 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011484 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011485
Anders Carlsson47061ee2011-05-06 14:25:31 +000011486 if ((isa<CXXConstructorDecl>(CurContext) ||
11487 isa<CXXDestructorDecl>(CurContext)) &&
11488 TheCall->getMethodDecl()->isPure()) {
11489 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11490
Chandler Carruth59259262011-06-27 08:31:58 +000011491 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011492 Diag(MemExpr->getLocStart(),
11493 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11494 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11495 << MD->getParent()->getDeclName();
11496
11497 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011498 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011499 }
John McCallb268a282010-08-23 23:25:46 +000011500 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011501}
11502
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011503/// BuildCallToObjectOfClassType - Build a call to an object of class
11504/// type (C++ [over.call.object]), which can end up invoking an
11505/// overloaded function call operator (@c operator()) or performing a
11506/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011507ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011508Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011509 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011510 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011511 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011512 if (checkPlaceholderForOverload(*this, Obj))
11513 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011514 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000011515
11516 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011517 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011518 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011519
John Wiegley01296292011-04-08 18:41:53 +000011520 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11521 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011522
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011523 // C++ [over.call.object]p1:
11524 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011525 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011526 // candidate functions includes at least the function call
11527 // operators of T. The function call operators of T are obtained by
11528 // ordinary lookup of the name operator() in the context of
11529 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000011530 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000011531 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011532
John Wiegley01296292011-04-08 18:41:53 +000011533 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011534 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011535 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011536
John McCall27b18f82009-11-17 02:14:36 +000011537 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11538 LookupQualifiedName(R, Record->getDecl());
11539 R.suppressDiagnostics();
11540
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011541 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011542 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011543 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011544 Object.get()->Classify(Context),
11545 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011546 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011547 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011548
Douglas Gregorab7897a2008-11-19 22:57:39 +000011549 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011550 // In addition, for each (non-explicit in C++0x) conversion function
11551 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011552 //
11553 // operator conversion-type-id () cv-qualifier;
11554 //
11555 // where cv-qualifier is the same cv-qualification as, or a
11556 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011557 // denotes the type "pointer to function of (P1,...,Pn) returning
11558 // R", or the type "reference to pointer to function of
11559 // (P1,...,Pn) returning R", or the type "reference to function
11560 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011561 // is also considered as a candidate function. Similarly,
11562 // surrogate call functions are added to the set of candidate
11563 // functions for each conversion function declared in an
11564 // accessible base class provided the function is not hidden
11565 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011566 std::pair<CXXRecordDecl::conversion_iterator,
11567 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011568 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011569 for (CXXRecordDecl::conversion_iterator
11570 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011571 NamedDecl *D = *I;
11572 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11573 if (isa<UsingShadowDecl>(D))
11574 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011575
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011576 // Skip over templated conversion functions; they aren't
11577 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011578 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011579 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011580
John McCall6e9f8f62009-12-03 04:06:58 +000011581 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011582 if (!Conv->isExplicit()) {
11583 // Strip the reference type (if any) and then the pointer type (if
11584 // any) to get down to what might be a function type.
11585 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11586 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11587 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011588
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011589 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11590 {
11591 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011592 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011593 }
11594 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011595 }
Mike Stump11289f42009-09-09 15:08:12 +000011596
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011597 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11598
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011599 // Perform overload resolution.
11600 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011601 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011602 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011603 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011604 // Overload resolution succeeded; we'll build the appropriate call
11605 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011606 break;
11607
11608 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011609 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011610 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011611 << Object.get()->getType() << /*call*/ 1
11612 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011613 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011614 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011615 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011616 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011617 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011618 break;
11619
11620 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011621 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011622 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011623 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011624 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011625 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011626
11627 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011628 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011629 diag::err_ovl_deleted_object_call)
11630 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011631 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011632 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011633 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011634 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011635 break;
Mike Stump11289f42009-09-09 15:08:12 +000011636 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011637
Douglas Gregorb412e172010-07-25 18:17:45 +000011638 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011639 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011640
John McCall4124c492011-10-17 18:40:02 +000011641 UnbridgedCasts.restore();
11642
Douglas Gregorab7897a2008-11-19 22:57:39 +000011643 if (Best->Function == 0) {
11644 // Since there is no function declaration, this is one of the
11645 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011646 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011647 = cast<CXXConversionDecl>(
11648 Best->Conversions[0].UserDefined.ConversionFunction);
11649
John Wiegley01296292011-04-08 18:41:53 +000011650 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011651 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11652 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011653 assert(Conv == Best->FoundDecl.getDecl() &&
11654 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011655 // We selected one of the surrogate functions that converts the
11656 // object parameter to a function pointer. Perform the conversion
11657 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011658
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011659 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011660 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011661 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11662 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011663 if (Call.isInvalid())
11664 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011665 // Record usage of conversion in an implicit cast.
11666 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11667 CK_UserDefinedConversion,
11668 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011669
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011670 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011671 }
11672
John Wiegley01296292011-04-08 18:41:53 +000011673 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011674
Douglas Gregorab7897a2008-11-19 22:57:39 +000011675 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11676 // that calls this method, using Object for the implicit object
11677 // parameter and passing along the remaining arguments.
11678 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011679
11680 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011681 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011682 return ExprError();
11683
Chandler Carruth8e543b32010-12-12 08:17:55 +000011684 const FunctionProtoType *Proto =
11685 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011686
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011687 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011688
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011689 DeclarationNameInfo OpLocInfo(
11690 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11691 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011692 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011693 HadMultipleCandidates,
11694 OpLocInfo.getLoc(),
11695 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011696 if (NewFn.isInvalid())
11697 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011698
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011699 // Build the full argument list for the method call (the implicit object
11700 // parameter is placed at the beginning of the list).
11701 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11702 MethodArgs[0] = Object.get();
11703 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11704
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011705 // Once we've built TheCall, all of the expressions are properly
11706 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011707 QualType ResultTy = Method->getResultType();
11708 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11709 ResultTy = ResultTy.getNonLValueExprType(Context);
11710
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011711 CXXOperatorCallExpr *TheCall = new (Context)
11712 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11713 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11714 ResultTy, VK, RParenLoc, false);
11715 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011716
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011717 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011718 Method))
11719 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011720
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011721 // We may have default arguments. If so, we need to allocate more
11722 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011723 if (Args.size() < NumParams)
11724 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011725
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011726 bool IsError = false;
11727
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011728 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011729 ExprResult ObjRes =
11730 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11731 Best->FoundDecl, Method);
11732 if (ObjRes.isInvalid())
11733 IsError = true;
11734 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011735 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011736 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011737
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011738 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011739 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011740 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011741 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011742 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011743
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011744 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011745
John McCalldadc5752010-08-24 06:29:42 +000011746 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011747 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011748 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011749 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011750 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011751
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011752 IsError |= InputInit.isInvalid();
11753 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011754 } else {
John McCalldadc5752010-08-24 06:29:42 +000011755 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011756 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11757 if (DefArg.isInvalid()) {
11758 IsError = true;
11759 break;
11760 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011761
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011762 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011763 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011764
11765 TheCall->setArg(i + 1, Arg);
11766 }
11767
11768 // If this is a variadic call, handle args passed through "...".
11769 if (Proto->isVariadic()) {
11770 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011771 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011772 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11773 IsError |= Arg.isInvalid();
11774 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011775 }
11776 }
11777
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011778 if (IsError) return true;
11779
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011780 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011781
Richard Smith55ce3522012-06-25 20:30:08 +000011782 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011783 return true;
11784
John McCalle172be52010-08-24 06:09:16 +000011785 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011786}
11787
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011788/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011789/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011790/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011791ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011792Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11793 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011794 assert(Base->getType()->isRecordType() &&
11795 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011796
John McCall4124c492011-10-17 18:40:02 +000011797 if (checkPlaceholderForOverload(*this, Base))
11798 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011799
John McCallbc077cf2010-02-08 23:07:23 +000011800 SourceLocation Loc = Base->getExprLoc();
11801
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011802 // C++ [over.ref]p1:
11803 //
11804 // [...] An expression x->m is interpreted as (x.operator->())->m
11805 // for a class object x of type T if T::operator->() exists and if
11806 // the operator is selected as the best match function by the
11807 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011808 DeclarationName OpName =
11809 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011810 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011811 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011812
John McCallbc077cf2010-02-08 23:07:23 +000011813 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011814 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011815 return ExprError();
11816
John McCall27b18f82009-11-17 02:14:36 +000011817 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11818 LookupQualifiedName(R, BaseRecord->getDecl());
11819 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011820
11821 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011822 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011823 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011824 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011825 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011826
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011827 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11828
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011829 // Perform overload resolution.
11830 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011831 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011832 case OR_Success:
11833 // Overload resolution succeeded; we'll build the call below.
11834 break;
11835
11836 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011837 if (CandidateSet.empty()) {
11838 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011839 if (NoArrowOperatorFound) {
11840 // Report this specific error to the caller instead of emitting a
11841 // diagnostic, as requested.
11842 *NoArrowOperatorFound = true;
11843 return ExprError();
11844 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011845 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11846 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011847 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011848 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011849 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011850 }
11851 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011852 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011853 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011854 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011855 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011856
11857 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011858 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11859 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011860 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011861 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011862
11863 case OR_Deleted:
11864 Diag(OpLoc, diag::err_ovl_deleted_oper)
11865 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011866 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011867 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011868 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011869 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011870 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011871 }
11872
John McCalla0296f72010-03-19 07:35:19 +000011873 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11874
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011875 // Convert the object parameter.
11876 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011877 ExprResult BaseResult =
11878 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11879 Best->FoundDecl, Method);
11880 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011881 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011882 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011883
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011884 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000011885 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011886 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011887 if (FnExpr.isInvalid())
11888 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011889
John McCall7decc9e2010-11-18 06:31:45 +000011890 QualType ResultTy = Method->getResultType();
11891 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11892 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011893 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011894 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011895 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011897 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011898 Method))
11899 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011900
11901 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011902}
11903
Richard Smithbcc22fc2012-03-09 08:00:36 +000011904/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11905/// a literal operator described by the provided lookup results.
11906ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11907 DeclarationNameInfo &SuffixInfo,
11908 ArrayRef<Expr*> Args,
11909 SourceLocation LitEndLoc,
11910 TemplateArgumentListInfo *TemplateArgs) {
11911 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011912
Richard Smithbcc22fc2012-03-09 08:00:36 +000011913 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11914 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11915 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011916
Richard Smithbcc22fc2012-03-09 08:00:36 +000011917 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11918
Richard Smithbcc22fc2012-03-09 08:00:36 +000011919 // Perform overload resolution. This will usually be trivial, but might need
11920 // to perform substitutions for a literal operator template.
11921 OverloadCandidateSet::iterator Best;
11922 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11923 case OR_Success:
11924 case OR_Deleted:
11925 break;
11926
11927 case OR_No_Viable_Function:
11928 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11929 << R.getLookupName();
11930 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11931 return ExprError();
11932
11933 case OR_Ambiguous:
11934 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11935 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11936 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011937 }
11938
Richard Smithbcc22fc2012-03-09 08:00:36 +000011939 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000011940 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11941 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000011942 SuffixInfo.getLoc(),
11943 SuffixInfo.getInfo());
11944 if (Fn.isInvalid())
11945 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011946
11947 // Check the argument types. This should almost always be a no-op, except
11948 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011949 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000011950 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000011951 ExprResult InputInit = PerformCopyInitialization(
11952 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11953 SourceLocation(), Args[ArgIdx]);
11954 if (InputInit.isInvalid())
11955 return true;
11956 ConvArgs[ArgIdx] = InputInit.take();
11957 }
11958
Richard Smithc67fdd42012-03-07 08:35:16 +000011959 QualType ResultTy = FD->getResultType();
11960 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11961 ResultTy = ResultTy.getNonLValueExprType(Context);
11962
Richard Smithc67fdd42012-03-07 08:35:16 +000011963 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011964 new (Context) UserDefinedLiteral(Context, Fn.take(),
11965 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011966 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11967
11968 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11969 return ExprError();
11970
Richard Smith55ce3522012-06-25 20:30:08 +000011971 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011972 return ExprError();
11973
11974 return MaybeBindToTemporary(UDL);
11975}
11976
Sam Panzer0f384432012-08-21 00:52:01 +000011977/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11978/// given LookupResult is non-empty, it is assumed to describe a member which
11979/// will be invoked. Otherwise, the function will be found via argument
11980/// dependent lookup.
11981/// CallExpr is set to a valid expression and FRS_Success returned on success,
11982/// otherwise CallExpr is set to ExprError() and some non-success value
11983/// is returned.
11984Sema::ForRangeStatus
11985Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11986 SourceLocation RangeLoc, VarDecl *Decl,
11987 BeginEndFunction BEF,
11988 const DeclarationNameInfo &NameInfo,
11989 LookupResult &MemberLookup,
11990 OverloadCandidateSet *CandidateSet,
11991 Expr *Range, ExprResult *CallExpr) {
11992 CandidateSet->clear();
11993 if (!MemberLookup.empty()) {
11994 ExprResult MemberRef =
11995 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11996 /*IsPtr=*/false, CXXScopeSpec(),
11997 /*TemplateKWLoc=*/SourceLocation(),
11998 /*FirstQualifierInScope=*/0,
11999 MemberLookup,
12000 /*TemplateArgs=*/0);
12001 if (MemberRef.isInvalid()) {
12002 *CallExpr = ExprError();
12003 Diag(Range->getLocStart(), diag::note_in_for_range)
12004 << RangeLoc << BEF << Range->getType();
12005 return FRS_DiagnosticIssued;
12006 }
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012007 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzer0f384432012-08-21 00:52:01 +000012008 if (CallExpr->isInvalid()) {
12009 *CallExpr = ExprError();
12010 Diag(Range->getLocStart(), diag::note_in_for_range)
12011 << RangeLoc << BEF << Range->getType();
12012 return FRS_DiagnosticIssued;
12013 }
12014 } else {
12015 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012016 UnresolvedLookupExpr *Fn =
12017 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
12018 NestedNameSpecifierLoc(), NameInfo,
12019 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012020 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012021
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012022 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012023 CandidateSet, CallExpr);
12024 if (CandidateSet->empty() || CandidateSetError) {
12025 *CallExpr = ExprError();
12026 return FRS_NoViableFunction;
12027 }
12028 OverloadCandidateSet::iterator Best;
12029 OverloadingResult OverloadResult =
12030 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12031
12032 if (OverloadResult == OR_No_Viable_Function) {
12033 *CallExpr = ExprError();
12034 return FRS_NoViableFunction;
12035 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012036 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzer0f384432012-08-21 00:52:01 +000012037 Loc, 0, CandidateSet, &Best,
12038 OverloadResult,
12039 /*AllowTypoCorrection=*/false);
12040 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12041 *CallExpr = ExprError();
12042 Diag(Range->getLocStart(), diag::note_in_for_range)
12043 << RangeLoc << BEF << Range->getType();
12044 return FRS_DiagnosticIssued;
12045 }
12046 }
12047 return FRS_Success;
12048}
12049
12050
Douglas Gregorcd695e52008-11-10 20:40:00 +000012051/// FixOverloadedFunctionReference - E is an expression that refers to
12052/// a C++ overloaded function (possibly with some parentheses and
12053/// perhaps a '&' around it). We have resolved the overloaded function
12054/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012055/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012056Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012057 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012058 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012059 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12060 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012061 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012062 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012063
Douglas Gregor51c538b2009-11-20 19:42:02 +000012064 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012065 }
12066
Douglas Gregor51c538b2009-11-20 19:42:02 +000012067 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012068 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12069 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012070 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012071 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012072 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012073 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012074 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012075 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012076
12077 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012078 ICE->getCastKind(),
12079 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000012080 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012081 }
12082
Douglas Gregor51c538b2009-11-20 19:42:02 +000012083 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012084 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012085 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012086 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12087 if (Method->isStatic()) {
12088 // Do nothing: static member functions aren't any different
12089 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012090 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012091 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012092 // UnresolvedLookupExpr holding an overloaded member function
12093 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012094 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12095 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012096 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012097 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012098
John McCalld14a8642009-11-21 08:51:07 +000012099 assert(isa<DeclRefExpr>(SubExpr)
12100 && "fixed to something other than a decl ref");
12101 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12102 && "fixed to a member ref with no nested name qualifier");
12103
12104 // We have taken the address of a pointer to member
12105 // function. Perform the computation here so that we get the
12106 // appropriate pointer to member type.
12107 QualType ClassType
12108 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12109 QualType MemPtrType
12110 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12111
John McCall7decc9e2010-11-18 06:31:45 +000012112 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12113 VK_RValue, OK_Ordinary,
12114 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012115 }
12116 }
John McCall16df1e52010-03-30 21:47:33 +000012117 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12118 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012119 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012120 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012121
John McCalle3027922010-08-25 11:45:40 +000012122 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012123 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012124 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012125 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012126 }
John McCalld14a8642009-11-21 08:51:07 +000012127
12128 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012129 // FIXME: avoid copy.
12130 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000012131 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012132 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12133 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012134 }
12135
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012136 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12137 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012138 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012139 Fn,
John McCall113bee02012-03-10 09:33:50 +000012140 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012141 ULE->getNameLoc(),
12142 Fn->getType(),
12143 VK_LValue,
12144 Found.getDecl(),
12145 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012146 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012147 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12148 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012149 }
12150
John McCall10eae182009-11-30 22:42:35 +000012151 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012152 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000012153 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
12154 if (MemExpr->hasExplicitTemplateArgs()) {
12155 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12156 TemplateArgs = &TemplateArgsBuffer;
12157 }
John McCall6b51f282009-11-23 01:53:49 +000012158
John McCall2d74de92009-12-01 22:10:20 +000012159 Expr *Base;
12160
John McCall7decc9e2010-11-18 06:31:45 +000012161 // If we're filling in a static method where we used to have an
12162 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012163 if (MemExpr->isImplicitAccess()) {
12164 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012165 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12166 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012167 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012168 Fn,
John McCall113bee02012-03-10 09:33:50 +000012169 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012170 MemExpr->getMemberLoc(),
12171 Fn->getType(),
12172 VK_LValue,
12173 Found.getDecl(),
12174 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012175 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012176 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12177 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012178 } else {
12179 SourceLocation Loc = MemExpr->getMemberLoc();
12180 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012181 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012182 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012183 Base = new (Context) CXXThisExpr(Loc,
12184 MemExpr->getBaseType(),
12185 /*isImplicit=*/true);
12186 }
John McCall2d74de92009-12-01 22:10:20 +000012187 } else
John McCallc3007a22010-10-26 07:05:15 +000012188 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012189
John McCall4adb38c2011-04-27 00:36:17 +000012190 ExprValueKind valueKind;
12191 QualType type;
12192 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12193 valueKind = VK_LValue;
12194 type = Fn->getType();
12195 } else {
12196 valueKind = VK_RValue;
12197 type = Context.BoundMemberTy;
12198 }
12199
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012200 MemberExpr *ME = MemberExpr::Create(Context, Base,
12201 MemExpr->isArrow(),
12202 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012203 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012204 Fn,
12205 Found,
12206 MemExpr->getMemberNameInfo(),
12207 TemplateArgs,
12208 type, valueKind, OK_Ordinary);
12209 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012210 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012211 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012212 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012213
John McCallc3007a22010-10-26 07:05:15 +000012214 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012215}
12216
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012217ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012218 DeclAccessPair Found,
12219 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000012220 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012221}
12222
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012223} // end namespace clang