blob: d5c13dd1120e4c0ae5df99dd5316561c81ce0c84 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
36
37namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000039
Nick Lewycky134af912013-02-07 05:08:22 +000040/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000041static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000044 SourceLocation Loc = SourceLocation(),
45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000046 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000047 return ExprError();
48 // If FoundDecl is different from Fn (such as if one is a template
49 // and the other a specialization), make sure DiagnoseUseOfDecl is
50 // called on both.
51 // FIXME: This would be more comprehensively addressed by modifying
52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53 // being used.
54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000055 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000056 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000057 VK_LValue, Loc, LocInfo);
58 if (HadMultipleCandidates)
59 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000060
61 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000062
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000064 E = S.DefaultFunctionArrayConversion(E.take());
65 if (E.isInvalid())
66 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000067 return E;
John McCall7decc9e2010-11-18 06:31:45 +000068}
69
John McCall5c32be02010-08-24 20:38:10 +000070static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
71 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000072 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000073 bool CStyle,
74 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000075
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000076static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
77 QualType &ToType,
78 bool InOverloadResolution,
79 StandardConversionSequence &SCS,
80 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000081static OverloadingResult
82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
83 UserDefinedConversionSequence& User,
84 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000085 bool AllowExplicit,
86 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000087
88
89static ImplicitConversionSequence::CompareKind
90CompareStandardConversionSequences(Sema &S,
91 const StandardConversionSequence& SCS1,
92 const StandardConversionSequence& SCS2);
93
94static ImplicitConversionSequence::CompareKind
95CompareQualificationConversions(Sema &S,
96 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareDerivedToBaseConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionCategory - Retrieve the implicit conversion
107/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +0000108ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109GetConversionCategory(ImplicitConversionKind Kind) {
110 static const ImplicitConversionCategory
111 Category[(int)ICK_Num_Conversion_Kinds] = {
112 ICC_Identity,
113 ICC_Lvalue_Transformation,
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICC_Qualification_Adjustment,
118 ICC_Promotion,
119 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000120 ICC_Promotion,
121 ICC_Conversion,
122 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
127 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000128 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000129 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000130 ICC_Conversion,
131 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 ICC_Conversion
134 };
135 return Category[(int)Kind];
136}
137
138/// GetConversionRank - Retrieve the implicit conversion rank
139/// corresponding to the given implicit conversion kind.
140ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
141 static const ImplicitConversionRank
142 Rank[(int)ICK_Num_Conversion_Kinds] = {
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
147 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000148 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 ICR_Promotion,
150 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000151 ICR_Promotion,
152 ICR_Conversion,
153 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000159 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000160 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000161 ICR_Conversion,
162 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000163 ICR_Complex_Real_Conversion,
164 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000165 ICR_Conversion,
166 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 };
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
173const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000179 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000183 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 "Integral conversion",
185 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000186 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000190 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000191 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000192 "Derived-to-base conversion",
193 "Vector conversion",
194 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000195 "Complex-real conversion",
196 "Block Pointer conversion",
197 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000198 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000199 };
200 return Name[Kind];
201}
202
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000203/// StandardConversionSequence - Set the standard conversion
204/// sequence to the identity conversion.
205void StandardConversionSequence::setAsIdentityConversion() {
206 First = ICK_Identity;
207 Second = ICK_Identity;
208 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000209 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000210 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000211 ReferenceBinding = false;
212 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000213 IsLvalueReference = true;
214 BindsToFunctionLvalue = false;
215 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000216 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000217 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000218 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000219}
220
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// getRank - Retrieve the rank of this standard conversion sequence
222/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
223/// implicit conversions.
224ImplicitConversionRank StandardConversionSequence::getRank() const {
225 ImplicitConversionRank Rank = ICR_Exact_Match;
226 if (GetConversionRank(First) > Rank)
227 Rank = GetConversionRank(First);
228 if (GetConversionRank(Second) > Rank)
229 Rank = GetConversionRank(Second);
230 if (GetConversionRank(Third) > Rank)
231 Rank = GetConversionRank(Third);
232 return Rank;
233}
234
235/// isPointerConversionToBool - Determines whether this conversion is
236/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000237/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 // Note that FromType has not necessarily been transformed by the
241 // array-to-pointer or function-to-pointer implicit conversions, so
242 // check for their presence as well as checking whether FromType is
243 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000244 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000245 (getFromType()->isPointerType() ||
246 getFromType()->isObjCObjectPointerType() ||
247 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000248 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
250 return true;
251
252 return false;
253}
254
Douglas Gregor5c407d92008-10-23 00:40:37 +0000255/// isPointerConversionToVoidPointer - Determines whether this
256/// conversion is a conversion of a pointer to a void pointer. This is
257/// used as part of the ranking of standard conversion sequences (C++
258/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000259bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000260StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000261isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000262 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000263 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000264
265 // Note that FromType has not necessarily been transformed by the
266 // array-to-pointer implicit conversion, so check for its presence
267 // and redo the conversion to get a pointer.
268 if (First == ICK_Array_To_Pointer)
269 FromType = Context.getArrayDecayedType(FromType);
270
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000273 return ToPtrType->getPointeeType()->isVoidType();
274
275 return false;
276}
277
Richard Smith66e05fe2012-01-18 05:21:49 +0000278/// Skip any implicit casts which could be either part of a narrowing conversion
279/// or after one in an implicit conversion.
280static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
282 switch (ICE->getCastKind()) {
283 case CK_NoOp:
284 case CK_IntegralCast:
285 case CK_IntegralToBoolean:
286 case CK_IntegralToFloating:
287 case CK_FloatingToIntegral:
288 case CK_FloatingToBoolean:
289 case CK_FloatingCast:
290 Converted = ICE->getSubExpr();
291 continue;
292
293 default:
294 return Converted;
295 }
296 }
297
298 return Converted;
299}
300
301/// Check if this standard conversion sequence represents a narrowing
302/// conversion, according to C++11 [dcl.init.list]p7.
303///
304/// \param Ctx The AST context.
305/// \param Converted The result of applying this standard conversion sequence.
306/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
307/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000308/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
309/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000310NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000311StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
312 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000313 APValue &ConstantValue,
314 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000316
317 // C++11 [dcl.init.list]p7:
318 // A narrowing conversion is an implicit conversion ...
319 QualType FromType = getToType(0);
320 QualType ToType = getToType(1);
321 switch (Second) {
322 // -- from a floating-point type to an integer type, or
323 //
324 // -- from an integer type or unscoped enumeration type to a floating-point
325 // type, except where the source is a constant expression and the actual
326 // value after conversion will fit into the target type and will produce
327 // the original value when converted back to the original type, or
328 case ICK_Floating_Integral:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
332 llvm::APSInt IntConstantValue;
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer &&
335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
336 // Convert the integer to the floating type.
337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
339 llvm::APFloat::rmNearestTiesToEven);
340 // And back.
341 llvm::APSInt ConvertedValue = IntConstantValue;
342 bool ignored;
343 Result.convertToInteger(ConvertedValue,
344 llvm::APFloat::rmTowardZero, &ignored);
345 // If the resulting value is different, this was a narrowing conversion.
346 if (IntConstantValue != ConvertedValue) {
347 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000348 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000349 return NK_Constant_Narrowing;
350 }
351 } else {
352 // Variables are always narrowings.
353 return NK_Variable_Narrowing;
354 }
355 }
356 return NK_Not_Narrowing;
357
358 // -- from long double to double or float, or from double to float, except
359 // where the source is a constant expression and the actual value after
360 // conversion is within the range of values that can be represented (even
361 // if it cannot be represented exactly), or
362 case ICK_Floating_Conversion:
363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
365 // FromType is larger than ToType.
366 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
368 // Constant!
369 assert(ConstantValue.isFloat());
370 llvm::APFloat FloatVal = ConstantValue.getFloat();
371 // Convert the source value into the target type.
372 bool ignored;
373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
374 Ctx.getFloatTypeSemantics(ToType),
375 llvm::APFloat::rmNearestTiesToEven, &ignored);
376 // If there was no overflow, the source value is within the range of
377 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000378 if (ConvertStatus & llvm::APFloat::opOverflow) {
379 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000381 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000382 } else {
383 return NK_Variable_Narrowing;
384 }
385 }
386 return NK_Not_Narrowing;
387
388 // -- from an integer type or unscoped enumeration type to an integer type
389 // that cannot represent all the values of the original type, except where
390 // the source is a constant expression and the actual value after
391 // conversion will fit into the target type and will produce the original
392 // value when converted back to the original type.
393 case ICK_Boolean_Conversion: // Bools are integers too.
394 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
395 // Boolean conversions can be from pointers and pointers to members
396 // [conv.bool], and those aren't considered narrowing conversions.
397 return NK_Not_Narrowing;
398 } // Otherwise, fall through to the integral case.
399 case ICK_Integral_Conversion: {
400 assert(FromType->isIntegralOrUnscopedEnumerationType());
401 assert(ToType->isIntegralOrUnscopedEnumerationType());
402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
403 const unsigned FromWidth = Ctx.getIntWidth(FromType);
404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
405 const unsigned ToWidth = Ctx.getIntWidth(ToType);
406
407 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000408 (FromWidth == ToWidth && FromSigned != ToSigned) ||
409 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000410 // Not all values of FromType can be represented in ToType.
411 llvm::APSInt InitializerValue;
412 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
414 // Such conversions on variables are always narrowing.
415 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000416 }
417 bool Narrowing = false;
418 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000419 // Negative -> unsigned is narrowing. Otherwise, more bits is never
420 // narrowing.
421 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000422 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000423 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000424 // Add a bit to the InitializerValue so we don't have to worry about
425 // signed vs. unsigned comparisons.
426 InitializerValue = InitializerValue.extend(
427 InitializerValue.getBitWidth() + 1);
428 // Convert the initializer to and from the target width and signed-ness.
429 llvm::APSInt ConvertedValue = InitializerValue;
430 ConvertedValue = ConvertedValue.trunc(ToWidth);
431 ConvertedValue.setIsSigned(ToSigned);
432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
433 ConvertedValue.setIsSigned(InitializerValue.isSigned());
434 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000435 if (ConvertedValue != InitializerValue)
436 Narrowing = true;
437 }
438 if (Narrowing) {
439 ConstantType = Initializer->getType();
440 ConstantValue = APValue(InitializerValue);
441 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000442 }
443 }
444 return NK_Not_Narrowing;
445 }
446
447 default:
448 // Other kinds of conversions are not narrowings.
449 return NK_Not_Narrowing;
450 }
451}
452
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000453/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000454/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000455void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 bool PrintedSomething = false;
458 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000459 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Second != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000468
469 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000470 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000471 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000473 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000475 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 PrintedSomething = true;
477 }
478
479 if (Third != ICK_Identity) {
480 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000488 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 }
490}
491
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000494void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000497 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000500 if (ConversionFunction)
501 OS << '\'' << *ConversionFunction << '\'';
502 else
503 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 }
508}
509
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000512void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000513 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000514 if (isStdInitializerListElement())
515 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 switch (ConversionKind) {
517 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 break;
521 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000522 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000523 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 break;
525 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000526 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000527 break;
John McCall0d1da222010-01-12 00:44:57 +0000528 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000529 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000530 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000531 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000532 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 }
535
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000536 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537}
538
John McCall0d1da222010-01-12 00:44:57 +0000539void AmbiguousConversionSequence::construct() {
540 new (&conversions()) ConversionSet();
541}
542
543void AmbiguousConversionSequence::destruct() {
544 conversions().~ConversionSet();
545}
546
547void
548AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
549 FromTypePtr = O.FromTypePtr;
550 ToTypePtr = O.ToTypePtr;
551 new (&conversions()) ConversionSet(O.conversions());
552}
553
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000555 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000556 // template argument information.
557 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000558 TemplateArgument FirstArg;
559 TemplateArgument SecondArg;
560 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000561 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000562 // template parameter and template argument information.
563 struct DFIParamWithArguments : DFIArguments {
564 TemplateParameter Param;
565 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568/// \brief Convert from Sema's representation of template deduction information
569/// to the form used in overload-candidate information.
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
571 Sema::TemplateDeductionResult TDK,
572 TemplateDeductionInfo &Info) {
573 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000575 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 Result.Data = 0;
577 switch (TDK) {
578 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000579 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000581 case Sema::TDK_TooManyArguments:
582 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000586 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000587 Result.Data = Info.Param.getOpaqueValue();
588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
623
Richard Smith44ecdbd2013-01-31 05:19:49 +0000624 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 return Result;
629}
John McCall0d1da222010-01-12 00:44:57 +0000630
Larisse Voufo98b20f12013-07-19 23:00:19 +0000631void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
633 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000634 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 case Sema::TDK_InstantiationDepth:
636 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000637 case Sema::TDK_TooManyArguments:
638 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000639 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000640 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000644 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000645 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000646 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000647 Data = 0;
648 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000649
650 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000651 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
654 Diag->~PartialDiagnosticAt();
655 HasDiagnostic = false;
656 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor461761d2010-05-08 18:20:53 +0000659 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 break;
662 }
663}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Larisse Voufo98b20f12013-07-19 23:00:19 +0000665PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000666 if (HasDiagnostic)
667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
668 return 0;
669}
670
Larisse Voufo98b20f12013-07-19 23:00:19 +0000671TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
673 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000674 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000675 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000676 case Sema::TDK_TooManyArguments:
677 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000678 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000679 case Sema::TDK_NonDeducedMismatch:
680 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000681 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000683 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000686
687 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000688 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000689 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000691 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000692 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693 break;
694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 return TemplateParameter();
697}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregord09efd42010-05-08 20:07:26 +0000713
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Richard Smith44ecdbd2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
753 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000754 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 case Sema::TDK_InstantiationDepth:
756 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000757 case Sema::TDK_TooManyArguments:
758 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000759 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000760 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000761 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000762 return 0;
763
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000764 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000765 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000766 case Sema::TDK_NonDeducedMismatch:
767 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768
Douglas Gregor461761d2010-05-08 18:20:53 +0000769 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000770 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000771 break;
772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774 return 0;
775}
776
Larisse Voufo98b20f12013-07-19 23:00:19 +0000777Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000778 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
779 Sema::TDK_FailedOverloadResolution)
780 return static_cast<Expr*>(Data);
781
782 return 0;
783}
784
Benjamin Kramer97e59492012-10-09 15:52:25 +0000785void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000786 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
788 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
790 i->DeductionFailure.Destroy();
791 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000792}
793
794void OverloadCandidateSet::clear() {
795 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000796 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000797 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000798 Functions.clear();
799}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
John McCall4124c492011-10-17 18:40:02 +0000801namespace {
802 class UnbridgedCastsSet {
803 struct Entry {
804 Expr **Addr;
805 Expr *Saved;
806 };
807 SmallVector<Entry, 2> Entries;
808
809 public:
810 void save(Sema &S, Expr *&E) {
811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
812 Entry entry = { &E, E };
813 Entries.push_back(entry);
814 E = S.stripARCUnbridgedCast(E);
815 }
816
817 void restore() {
818 for (SmallVectorImpl<Entry>::iterator
819 i = Entries.begin(), e = Entries.end(); i != e; ++i)
820 *i->Addr = i->Saved;
821 }
822 };
823}
824
825/// checkPlaceholderForOverload - Do any interesting placeholder-like
826/// preprocessing on the given expression.
827///
828/// \param unbridgedCasts a collection to which to add unbridged casts;
829/// without this, they will be immediately diagnosed as errors
830///
831/// Return true on unrecoverable error.
832static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
833 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
835 // We can't handle overloaded expressions here because overload
836 // resolution might reasonably tweak them.
837 if (placeholder->getKind() == BuiltinType::Overload) return false;
838
839 // If the context potentially accepts unbridged ARC casts, strip
840 // the unbridged cast and add it to the collection for later restoration.
841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
842 unbridgedCasts) {
843 unbridgedCasts->save(S, E);
844 return false;
845 }
846
847 // Go ahead and check everything else.
848 ExprResult result = S.CheckPlaceholderExpr(E);
849 if (result.isInvalid())
850 return true;
851
852 E = result.take();
853 return false;
854 }
855
856 // Nothing to do.
857 return false;
858}
859
860/// checkArgPlaceholdersForOverload - Check a set of call operands for
861/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000862static bool checkArgPlaceholdersForOverload(Sema &S,
863 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000864 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000865 for (unsigned i = 0, e = Args.size(); i != e; ++i)
866 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000867 return true;
868
869 return false;
870}
871
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000873// overload of the declarations in Old. This routine returns false if
874// New and Old cannot be overloaded, e.g., if New has the same
875// signature as some function in Old (C++ 1.3.10) or if the Old
876// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000877// it does return false, MatchedDecl will point to the decl that New
878// cannot be overloaded with. This decl may be a UsingShadowDecl on
879// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880//
881// Example: Given the following input:
882//
883// void f(int, float); // #1
884// void f(int, int); // #2
885// int f(int, int); // #3
886//
887// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000888// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889//
John McCall3d988d92009-12-02 08:47:38 +0000890// When we process #2, Old contains only the FunctionDecl for #1. By
891// comparing the parameter types, we see that #1 and #2 are overloaded
892// (since they have different signatures), so this routine returns
893// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000894//
John McCall3d988d92009-12-02 08:47:38 +0000895// When we process #3, Old is an overload set containing #1 and #2. We
896// compare the signatures of #3 to #1 (they're overloaded, so we do
897// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
898// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899// signature), IsOverload returns false and MatchedDecl will be set to
900// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000901//
902// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
903// into a class by a using declaration. The rules for whether to hide
904// shadow declarations ignore some properties which otherwise figure
905// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000906Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000907Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
908 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000909 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000910 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000911 NamedDecl *OldD = *I;
912
913 bool OldIsUsingDecl = false;
914 if (isa<UsingShadowDecl>(OldD)) {
915 OldIsUsingDecl = true;
916
917 // We can always introduce two using declarations into the same
918 // context, even if they have identical signatures.
919 if (NewIsUsingDecl) continue;
920
921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
922 }
923
924 // If either declaration was introduced by a using declaration,
925 // we'll need to use slightly different rules for matching.
926 // Essentially, these rules are the normal rules, except that
927 // function templates hide function templates with different
928 // return types or template parameter lists.
929 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
931 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000932
Alp Tokera2794f92014-01-22 07:29:52 +0000933 if (FunctionDecl *OldF = OldD->getAsFunction()) {
John McCalle9cccd82010-06-16 08:42:20 +0000934 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
935 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
937 continue;
938 }
939
Alp Tokera2794f92014-01-22 07:29:52 +0000940 if (!isa<FunctionTemplateDecl>(OldD) &&
941 !shouldLinkPossiblyHiddenDecl(*I, New))
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000942 continue;
943
John McCalldaa3d6b2009-12-09 03:35:25 +0000944 Match = *I;
945 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000946 }
John McCalla8987a2942010-11-10 03:01:53 +0000947 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000948 // We can overload with these, which can show up when doing
949 // redeclaration checks for UsingDecls.
950 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000951 } else if (isa<TagDecl>(OldD)) {
952 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000953 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
954 // Optimistically assume that an unresolved using decl will
955 // overload; if it doesn't, we'll have to diagnose during
956 // template instantiation.
957 } else {
John McCall1f82f242009-11-18 22:49:29 +0000958 // (C++ 13p1):
959 // Only function declarations can be overloaded; object and type
960 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000961 Match = *I;
962 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000963 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000964 }
John McCall1f82f242009-11-18 22:49:29 +0000965
John McCalldaa3d6b2009-12-09 03:35:25 +0000966 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000967}
968
Richard Smithac974a32013-06-30 09:48:50 +0000969bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
970 bool UseUsingDeclRules) {
971 // C++ [basic.start.main]p2: This function shall not be overloaded.
972 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000973 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000974
David Majnemerc729b0b2013-09-16 22:44:20 +0000975 // MSVCRT user defined entry points cannot be overloaded.
976 if (New->isMSVCRTEntryPoint())
977 return false;
978
John McCall1f82f242009-11-18 22:49:29 +0000979 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
980 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
981
982 // C++ [temp.fct]p2:
983 // A function template can be overloaded with other function templates
984 // and with normal (non-template) functions.
985 if ((OldTemplate == 0) != (NewTemplate == 0))
986 return true;
987
988 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000989 QualType OldQType = Context.getCanonicalType(Old->getType());
990 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +0000991
992 // Compare the signatures (C++ 1.3.10) of the two functions to
993 // determine whether they are overloads. If we find any mismatch
994 // in the signature, they are overloads.
995
996 // If either of these functions is a K&R-style function (no
997 // prototype), then we consider them to have matching signatures.
998 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
999 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1000 return false;
1001
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001002 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1003 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001004
1005 // The signature of a function includes the types of its
1006 // parameters (C++ 1.3.10), which includes the presence or absence
1007 // of the ellipsis; see C++ DR 357).
1008 if (OldQType != NewQType &&
Alp Toker9cacbab2014-01-20 20:26:09 +00001009 (OldType->getNumParams() != NewType->getNumParams() ||
John McCall1f82f242009-11-18 22:49:29 +00001010 OldType->isVariadic() != NewType->isVariadic() ||
Alp Toker9cacbab2014-01-20 20:26:09 +00001011 !FunctionParamTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001012 return true;
1013
1014 // C++ [temp.over.link]p4:
1015 // The signature of a function template consists of its function
1016 // signature, its return type and its template parameter list. The names
1017 // of the template parameters are significant only for establishing the
1018 // relationship between the template parameters and the rest of the
1019 // signature.
1020 //
1021 // We check the return type and template parameter lists for function
1022 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001023 //
1024 // However, we don't consider either of these when deciding whether
1025 // a member introduced by a shadow declaration is hidden.
1026 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001027 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1028 OldTemplate->getTemplateParameters(),
1029 false, TPL_TemplateMatch) ||
John McCall1f82f242009-11-18 22:49:29 +00001030 OldType->getResultType() != NewType->getResultType()))
1031 return true;
1032
1033 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001034 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001035 //
1036 // As part of this, also check whether one of the member functions
1037 // is static, in which case they are not overloads (C++
1038 // 13.1p2). While not part of the definition of the signature,
1039 // this check is important to determine whether these functions
1040 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001041 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1042 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001043 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001044 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1045 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1046 if (!UseUsingDeclRules &&
1047 (OldMethod->getRefQualifier() == RQ_None ||
1048 NewMethod->getRefQualifier() == RQ_None)) {
1049 // C++0x [over.load]p2:
1050 // - Member function declarations with the same name and the same
1051 // parameter-type-list as well as member function template
1052 // declarations with the same name, the same parameter-type-list, and
1053 // the same template parameter lists cannot be overloaded if any of
1054 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001055 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001056 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001057 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001058 }
1059 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061
Richard Smith574f4f62013-01-14 05:37:29 +00001062 // We may not have applied the implicit const for a constexpr member
1063 // function yet (because we haven't yet resolved whether this is a static
1064 // or non-static member function). Add it now, on the assumption that this
1065 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001066 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001067 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithac974a32013-06-30 09:48:50 +00001068 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001069 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001070 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001071
1072 // We do not allow overloading based off of '__restrict'.
1073 OldQuals &= ~Qualifiers::Restrict;
1074 NewQuals &= ~Qualifiers::Restrict;
1075 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001076 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001077 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001078
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001079 // enable_if attributes are an order-sensitive part of the signature.
1080 for (specific_attr_iterator<EnableIfAttr>
1081 NewI = New->specific_attr_begin<EnableIfAttr>(),
1082 NewE = New->specific_attr_end<EnableIfAttr>(),
1083 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1084 OldE = Old->specific_attr_end<EnableIfAttr>();
1085 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1086 if (NewI == NewE || OldI == OldE)
1087 return true;
1088 llvm::FoldingSetNodeID NewID, OldID;
1089 NewI->getCond()->Profile(NewID, Context, true);
1090 OldI->getCond()->Profile(OldID, Context, true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00001091 if (NewID != OldID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001092 return true;
1093 }
1094
John McCall1f82f242009-11-18 22:49:29 +00001095 // The signatures match; this is not an overload.
1096 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001097}
1098
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001099/// \brief Checks availability of the function depending on the current
1100/// function context. Inside an unavailable function, unavailability is ignored.
1101///
1102/// \returns true if \arg FD is unavailable and current context is inside
1103/// an available function, false otherwise.
1104bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1105 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1106}
1107
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001108/// \brief Tries a user-defined conversion from From to ToType.
1109///
1110/// Produces an implicit conversion sequence for when a standard conversion
1111/// is not an option. See TryImplicitConversion for more information.
1112static ImplicitConversionSequence
1113TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1114 bool SuppressUserConversions,
1115 bool AllowExplicit,
1116 bool InOverloadResolution,
1117 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001118 bool AllowObjCWritebackConversion,
1119 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001120 ImplicitConversionSequence ICS;
1121
1122 if (SuppressUserConversions) {
1123 // We're not in the case above, so there is no conversion that
1124 // we can perform.
1125 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1126 return ICS;
1127 }
1128
1129 // Attempt user-defined conversion.
1130 OverloadCandidateSet Conversions(From->getExprLoc());
1131 OverloadingResult UserDefResult
1132 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001133 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001134
1135 if (UserDefResult == OR_Success) {
1136 ICS.setUserDefined();
1137 // C++ [over.ics.user]p4:
1138 // A conversion of an expression of class type to the same class
1139 // type is given Exact Match rank, and a conversion of an
1140 // expression of class type to a base class of that type is
1141 // given Conversion rank, in spite of the fact that a copy
1142 // constructor (i.e., a user-defined conversion function) is
1143 // called for those cases.
1144 if (CXXConstructorDecl *Constructor
1145 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1146 QualType FromCanon
1147 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1148 QualType ToCanon
1149 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1150 if (Constructor->isCopyConstructor() &&
1151 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1152 // Turn this into a "standard" conversion sequence, so that it
1153 // gets ranked with standard conversion sequences.
1154 ICS.setStandard();
1155 ICS.Standard.setAsIdentityConversion();
1156 ICS.Standard.setFromType(From->getType());
1157 ICS.Standard.setAllToTypes(ToType);
1158 ICS.Standard.CopyConstructor = Constructor;
1159 if (ToCanon != FromCanon)
1160 ICS.Standard.Second = ICK_Derived_To_Base;
1161 }
1162 }
1163
1164 // C++ [over.best.ics]p4:
1165 // However, when considering the argument of a user-defined
1166 // conversion function that is a candidate by 13.3.1.3 when
1167 // invoked for the copying of the temporary in the second step
1168 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1169 // 13.3.1.6 in all cases, only standard conversion sequences and
1170 // ellipsis conversion sequences are allowed.
1171 if (SuppressUserConversions && ICS.isUserDefined()) {
1172 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1173 }
1174 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1175 ICS.setAmbiguous();
1176 ICS.Ambiguous.setFromType(From->getType());
1177 ICS.Ambiguous.setToType(ToType);
1178 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1179 Cand != Conversions.end(); ++Cand)
1180 if (Cand->Viable)
1181 ICS.Ambiguous.addConversion(Cand->Function);
1182 } else {
1183 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1184 }
1185
1186 return ICS;
1187}
1188
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001189/// TryImplicitConversion - Attempt to perform an implicit conversion
1190/// from the given expression (Expr) to the given type (ToType). This
1191/// function returns an implicit conversion sequence that can be used
1192/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001193///
1194/// void f(float f);
1195/// void g(int i) { f(i); }
1196///
1197/// this routine would produce an implicit conversion sequence to
1198/// describe the initialization of f from i, which will be a standard
1199/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1200/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1201//
1202/// Note that this routine only determines how the conversion can be
1203/// performed; it does not actually perform the conversion. As such,
1204/// it will not produce any diagnostics if no conversion is available,
1205/// but will instead return an implicit conversion sequence of kind
1206/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001207///
1208/// If @p SuppressUserConversions, then user-defined conversions are
1209/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001210/// If @p AllowExplicit, then explicit user-defined conversions are
1211/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001212///
1213/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1214/// writeback conversion, which allows __autoreleasing id* parameters to
1215/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001216static ImplicitConversionSequence
1217TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1218 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001219 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001220 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001221 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001222 bool AllowObjCWritebackConversion,
1223 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001224 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001225 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001226 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001227 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001228 return ICS;
1229 }
1230
David Blaikiebbafb8a2012-03-11 07:00:24 +00001231 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001232 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001233 return ICS;
1234 }
1235
Douglas Gregor836a7e82010-08-11 02:15:33 +00001236 // C++ [over.ics.user]p4:
1237 // A conversion of an expression of class type to the same class
1238 // type is given Exact Match rank, and a conversion of an
1239 // expression of class type to a base class of that type is
1240 // given Conversion rank, in spite of the fact that a copy/move
1241 // constructor (i.e., a user-defined conversion function) is
1242 // called for those cases.
1243 QualType FromType = From->getType();
1244 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001245 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1246 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001247 ICS.setStandard();
1248 ICS.Standard.setAsIdentityConversion();
1249 ICS.Standard.setFromType(FromType);
1250 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001251
Douglas Gregor5ab11652010-04-17 22:01:05 +00001252 // We don't actually check at this point whether there is a valid
1253 // copy/move constructor, since overloading just assumes that it
1254 // exists. When we actually perform initialization, we'll find the
1255 // appropriate constructor to copy the returned object, if needed.
1256 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001257
Douglas Gregor5ab11652010-04-17 22:01:05 +00001258 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001259 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001260 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001261
Douglas Gregor836a7e82010-08-11 02:15:33 +00001262 return ICS;
1263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001264
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001265 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1266 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001267 AllowObjCWritebackConversion,
1268 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001269}
1270
John McCall31168b02011-06-15 23:02:42 +00001271ImplicitConversionSequence
1272Sema::TryImplicitConversion(Expr *From, QualType ToType,
1273 bool SuppressUserConversions,
1274 bool AllowExplicit,
1275 bool InOverloadResolution,
1276 bool CStyle,
1277 bool AllowObjCWritebackConversion) {
1278 return clang::TryImplicitConversion(*this, From, ToType,
1279 SuppressUserConversions, AllowExplicit,
1280 InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001281 AllowObjCWritebackConversion,
1282 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001283}
1284
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001285/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001286/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001287/// converted expression. Flavor is the kind of conversion we're
1288/// performing, used in the error message. If @p AllowExplicit,
1289/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001290ExprResult
1291Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001292 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001293 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001294 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001295}
1296
John Wiegley01296292011-04-08 18:41:53 +00001297ExprResult
1298Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001299 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001300 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001301 if (checkPlaceholderForOverload(*this, From))
1302 return ExprError();
1303
John McCall31168b02011-06-15 23:02:42 +00001304 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1305 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001306 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001307 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001308 if (getLangOpts().ObjC1)
1309 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1310 ToType, From->getType(), From);
John McCall5c32be02010-08-24 20:38:10 +00001311 ICS = clang::TryImplicitConversion(*this, From, ToType,
1312 /*SuppressUserConversions=*/false,
1313 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001314 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001315 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001316 AllowObjCWritebackConversion,
1317 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001318 return PerformImplicitConversion(From, ToType, ICS, Action);
1319}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320
1321/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001322/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001323bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1324 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001325 if (Context.hasSameUnqualifiedType(FromType, ToType))
1326 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001327
John McCall991eb4b2010-12-21 00:44:39 +00001328 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1329 // where F adds one of the following at most once:
1330 // - a pointer
1331 // - a member pointer
1332 // - a block pointer
1333 CanQualType CanTo = Context.getCanonicalType(ToType);
1334 CanQualType CanFrom = Context.getCanonicalType(FromType);
1335 Type::TypeClass TyClass = CanTo->getTypeClass();
1336 if (TyClass != CanFrom->getTypeClass()) return false;
1337 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1338 if (TyClass == Type::Pointer) {
1339 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1340 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1341 } else if (TyClass == Type::BlockPointer) {
1342 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1343 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1344 } else if (TyClass == Type::MemberPointer) {
1345 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1346 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1347 } else {
1348 return false;
1349 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001350
John McCall991eb4b2010-12-21 00:44:39 +00001351 TyClass = CanTo->getTypeClass();
1352 if (TyClass != CanFrom->getTypeClass()) return false;
1353 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1354 return false;
1355 }
1356
1357 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1358 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1359 if (!EInfo.getNoReturn()) return false;
1360
1361 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1362 assert(QualType(FromFn, 0).isCanonical());
1363 if (QualType(FromFn, 0) != CanTo) return false;
1364
1365 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001366 return true;
1367}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368
Douglas Gregor46188682010-05-18 22:42:18 +00001369/// \brief Determine whether the conversion from FromType to ToType is a valid
1370/// vector conversion.
1371///
1372/// \param ICK Will be set to the vector conversion kind, if this is a vector
1373/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001374static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1375 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001376 // We need at least one of these types to be a vector type to have a vector
1377 // conversion.
1378 if (!ToType->isVectorType() && !FromType->isVectorType())
1379 return false;
1380
1381 // Identical types require no conversions.
1382 if (Context.hasSameUnqualifiedType(FromType, ToType))
1383 return false;
1384
1385 // There are no conversions between extended vector types, only identity.
1386 if (ToType->isExtVectorType()) {
1387 // There are no conversions between extended vector types other than the
1388 // identity conversion.
1389 if (FromType->isExtVectorType())
1390 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391
Douglas Gregor46188682010-05-18 22:42:18 +00001392 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001393 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001394 ICK = ICK_Vector_Splat;
1395 return true;
1396 }
1397 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001398
1399 // We can perform the conversion between vector types in the following cases:
1400 // 1)vector types are equivalent AltiVec and GCC vector types
1401 // 2)lax vector conversions are permitted and the vector types are of the
1402 // same size
1403 if (ToType->isVectorType() && FromType->isVectorType()) {
1404 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001405 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001406 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001407 ICK = ICK_Vector_Conversion;
1408 return true;
1409 }
Douglas Gregor46188682010-05-18 22:42:18 +00001410 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001411
Douglas Gregor46188682010-05-18 22:42:18 +00001412 return false;
1413}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001414
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001415static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1416 bool InOverloadResolution,
1417 StandardConversionSequence &SCS,
1418 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001419
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001420/// IsStandardConversion - Determines whether there is a standard
1421/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1422/// expression From to the type ToType. Standard conversion sequences
1423/// only consider non-class types; for conversions that involve class
1424/// types, use TryImplicitConversion. If a conversion exists, SCS will
1425/// contain the standard conversion sequence required to perform this
1426/// conversion and this routine will return true. Otherwise, this
1427/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001428static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1429 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001430 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001431 bool CStyle,
1432 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001433 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001434
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001435 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001436 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001437 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001438 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001439 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001440
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001441 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001442 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001443 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001444 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001445 return false;
1446
Mike Stump11289f42009-09-09 15:08:12 +00001447 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001448 }
1449
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001450 // The first conversion can be an lvalue-to-rvalue conversion,
1451 // array-to-pointer conversion, or function-to-pointer conversion
1452 // (C++ 4p1).
1453
John McCall5c32be02010-08-24 20:38:10 +00001454 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001455 DeclAccessPair AccessPair;
1456 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001457 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001458 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001459 // We were able to resolve the address of the overloaded function,
1460 // so we can convert to the type of that function.
1461 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001462
1463 // we can sometimes resolve &foo<int> regardless of ToType, so check
1464 // if the type matches (identity) or we are converting to bool
1465 if (!S.Context.hasSameUnqualifiedType(
1466 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1467 QualType resultTy;
1468 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001469 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001470 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1471 // otherwise, only a boolean conversion is standard
1472 if (!ToType->isBooleanType())
1473 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475
Chandler Carruthffce2452011-03-29 08:08:18 +00001476 // Check if the "from" expression is taking the address of an overloaded
1477 // function and recompute the FromType accordingly. Take advantage of the
1478 // fact that non-static member functions *must* have such an address-of
1479 // expression.
1480 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1481 if (Method && !Method->isStatic()) {
1482 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1483 "Non-unary operator on non-static member address");
1484 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1485 == UO_AddrOf &&
1486 "Non-address-of operator on non-static member address");
1487 const Type *ClassType
1488 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1489 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001490 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1491 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1492 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001493 "Non-address-of operator for overloaded function expression");
1494 FromType = S.Context.getPointerType(FromType);
1495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001496
Douglas Gregor980fb162010-04-29 18:24:40 +00001497 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001498 assert(S.Context.hasSameType(
1499 FromType,
1500 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001501 } else {
1502 return false;
1503 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001504 }
John McCall154a2fd2011-08-30 00:57:29 +00001505 // Lvalue-to-rvalue conversion (C++11 4.1):
1506 // A glvalue (3.10) of a non-function, non-array type T can
1507 // be converted to a prvalue.
1508 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001509 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001510 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001511 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001512 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001513
Douglas Gregorc79862f2012-04-12 17:51:55 +00001514 // C11 6.3.2.1p2:
1515 // ... if the lvalue has atomic type, the value has the non-atomic version
1516 // of the type of the lvalue ...
1517 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1518 FromType = Atomic->getValueType();
1519
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001520 // If T is a non-class type, the type of the rvalue is the
1521 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001522 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1523 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001524 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001525 } else if (FromType->isArrayType()) {
1526 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001528
1529 // An lvalue or rvalue of type "array of N T" or "array of unknown
1530 // bound of T" can be converted to an rvalue of type "pointer to
1531 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001532 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533
John McCall5c32be02010-08-24 20:38:10 +00001534 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001535 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001536 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537
1538 // For the purpose of ranking in overload resolution
1539 // (13.3.3.1.1), this conversion is considered an
1540 // array-to-pointer conversion followed by a qualification
1541 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001542 SCS.Second = ICK_Identity;
1543 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001544 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001545 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547 }
John McCall086a4642010-11-24 05:12:34 +00001548 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001549 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001550 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551
1552 // An lvalue of function type T can be converted to an rvalue of
1553 // type "pointer to T." The result is a pointer to the
1554 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001555 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001556 } else {
1557 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001558 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001559 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001560 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561
1562 // The second conversion can be an integral promotion, floating
1563 // point promotion, integral conversion, floating point conversion,
1564 // floating-integral conversion, pointer conversion,
1565 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001566 // For overloading in C, this can also be a "compatible-type"
1567 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001568 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001569 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001570 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571 // The unqualified versions of the types are the same: there's no
1572 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001573 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001574 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001575 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001576 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001577 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001578 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001579 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001580 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001582 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001583 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001584 SCS.Second = ICK_Complex_Promotion;
1585 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001586 } else if (ToType->isBooleanType() &&
1587 (FromType->isArithmeticType() ||
1588 FromType->isAnyPointerType() ||
1589 FromType->isBlockPointerType() ||
1590 FromType->isMemberPointerType() ||
1591 FromType->isNullPtrType())) {
1592 // Boolean conversions (C++ 4.12).
1593 SCS.Second = ICK_Boolean_Conversion;
1594 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001595 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001596 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001597 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001598 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001599 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001600 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001601 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001602 SCS.Second = ICK_Complex_Conversion;
1603 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001604 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1605 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001606 // Complex-real conversions (C99 6.3.1.7)
1607 SCS.Second = ICK_Complex_Real;
1608 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001609 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001610 // Floating point conversions (C++ 4.8).
1611 SCS.Second = ICK_Floating_Conversion;
1612 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001613 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001614 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001615 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001616 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001617 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001618 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001620 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001621 SCS.Second = ICK_Block_Pointer_Conversion;
1622 } else if (AllowObjCWritebackConversion &&
1623 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1624 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001625 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1626 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001627 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001628 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001629 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001630 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001631 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001632 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001633 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001634 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001635 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001636 SCS.Second = SecondICK;
1637 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001638 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001639 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001640 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001641 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001642 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001643 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001644 // Treat a conversion that strips "noreturn" as an identity conversion.
1645 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001646 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1647 InOverloadResolution,
1648 SCS, CStyle)) {
1649 SCS.Second = ICK_TransparentUnionConversion;
1650 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001651 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1652 CStyle)) {
1653 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001654 // appropriately.
1655 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001656 } else if (ToType->isEventT() &&
1657 From->isIntegerConstantExpr(S.getASTContext()) &&
1658 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1659 SCS.Second = ICK_Zero_Event_Conversion;
1660 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001661 } else {
1662 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001663 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001665 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001666
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001667 QualType CanonFrom;
1668 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001670 bool ObjCLifetimeConversion;
1671 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1672 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001674 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001676 CanonFrom = S.Context.getCanonicalType(FromType);
1677 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 } else {
1679 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001680 SCS.Third = ICK_Identity;
1681
Mike Stump11289f42009-09-09 15:08:12 +00001682 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683 // [...] Any difference in top-level cv-qualification is
1684 // subsumed by the initialization itself and does not constitute
1685 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001686 CanonFrom = S.Context.getCanonicalType(FromType);
1687 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001688 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001689 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001690 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001691 FromType = ToType;
1692 CanonFrom = CanonTo;
1693 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001694 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001695 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001696
1697 // If we have not converted the argument type to the parameter type,
1698 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001699 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001700 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001701
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001702 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001703}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001704
1705static bool
1706IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1707 QualType &ToType,
1708 bool InOverloadResolution,
1709 StandardConversionSequence &SCS,
1710 bool CStyle) {
1711
1712 const RecordType *UT = ToType->getAsUnionType();
1713 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1714 return false;
1715 // The field to initialize within the transparent union.
1716 RecordDecl *UD = UT->getDecl();
1717 // It's compatible if the expression matches any of the fields.
1718 for (RecordDecl::field_iterator it = UD->field_begin(),
1719 itend = UD->field_end();
1720 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001721 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1722 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001723 ToType = it->getType();
1724 return true;
1725 }
1726 }
1727 return false;
1728}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001729
1730/// IsIntegralPromotion - Determines whether the conversion from the
1731/// expression From (whose potentially-adjusted type is FromType) to
1732/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1733/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001734bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001735 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001736 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001737 if (!To) {
1738 return false;
1739 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001740
1741 // An rvalue of type char, signed char, unsigned char, short int, or
1742 // unsigned short int can be converted to an rvalue of type int if
1743 // int can represent all the values of the source type; otherwise,
1744 // the source rvalue can be converted to an rvalue of type unsigned
1745 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001746 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1747 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 if (// We can promote any signed, promotable integer type to an int
1749 (FromType->isSignedIntegerType() ||
1750 // We can promote any unsigned integer type whose size is
1751 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001752 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001753 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001754 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001755 }
1756
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 return To->getKind() == BuiltinType::UInt;
1758 }
1759
Richard Smithb9c5a602012-09-13 21:18:54 +00001760 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001761 // A prvalue of an unscoped enumeration type whose underlying type is not
1762 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1763 // following types that can represent all the values of the enumeration
1764 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1765 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001766 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001767 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001768 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001769 // with lowest integer conversion rank (4.13) greater than the rank of long
1770 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001771 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001772 // C++11 [conv.prom]p4:
1773 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1774 // can be converted to a prvalue of its underlying type. Moreover, if
1775 // integral promotion can be applied to its underlying type, a prvalue of an
1776 // unscoped enumeration type whose underlying type is fixed can also be
1777 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001778 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1779 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1780 // provided for a scoped enumeration.
1781 if (FromEnumType->getDecl()->isScoped())
1782 return false;
1783
Richard Smithb9c5a602012-09-13 21:18:54 +00001784 // We can perform an integral promotion to the underlying type of the enum,
1785 // even if that's not the promoted type.
1786 if (FromEnumType->getDecl()->isFixed()) {
1787 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1788 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1789 IsIntegralPromotion(From, Underlying, ToType);
1790 }
1791
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001792 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001793 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001794 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001795 return Context.hasSameUnqualifiedType(ToType,
1796 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001797 }
John McCall56774992009-12-09 09:09:27 +00001798
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001799 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001800 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1801 // to an rvalue a prvalue of the first of the following types that can
1802 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001803 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001804 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001805 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001806 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001807 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001808 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001809 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001810 // Determine whether the type we're converting from is signed or
1811 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001812 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001813 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001815 // The types we'll try to promote to, in the appropriate
1816 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001817 QualType PromoteTypes[6] = {
1818 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001819 Context.LongTy, Context.UnsignedLongTy ,
1820 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001821 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001822 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001823 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1824 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001825 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001826 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1827 // We found the type that we can promote to. If this is the
1828 // type we wanted, we have a promotion. Otherwise, no
1829 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001830 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001831 }
1832 }
1833 }
1834
1835 // An rvalue for an integral bit-field (9.6) can be converted to an
1836 // rvalue of type int if int can represent all the values of the
1837 // bit-field; otherwise, it can be converted to unsigned int if
1838 // unsigned int can represent all the values of the bit-field. If
1839 // the bit-field is larger yet, no integral promotion applies to
1840 // it. If the bit-field has an enumerated type, it is treated as any
1841 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001842 // FIXME: We should delay checking of bit-fields until we actually perform the
1843 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001844 using llvm::APSInt;
1845 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001846 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001847 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001848 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001849 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1850 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1851 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001852
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001853 // Are we promoting to an int from a bitfield that fits in an int?
1854 if (BitWidth < ToSize ||
1855 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1856 return To->getKind() == BuiltinType::Int;
1857 }
Mike Stump11289f42009-09-09 15:08:12 +00001858
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001859 // Are we promoting to an unsigned int from an unsigned bitfield
1860 // that fits into an unsigned int?
1861 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1862 return To->getKind() == BuiltinType::UInt;
1863 }
Mike Stump11289f42009-09-09 15:08:12 +00001864
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001865 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001866 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001867 }
Mike Stump11289f42009-09-09 15:08:12 +00001868
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001869 // An rvalue of type bool can be converted to an rvalue of type int,
1870 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001871 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001872 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001873 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001874
1875 return false;
1876}
1877
1878/// IsFloatingPointPromotion - Determines whether the conversion from
1879/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1880/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001881bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001882 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1883 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001884 /// An rvalue of type float can be converted to an rvalue of type
1885 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001886 if (FromBuiltin->getKind() == BuiltinType::Float &&
1887 ToBuiltin->getKind() == BuiltinType::Double)
1888 return true;
1889
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001890 // C99 6.3.1.5p1:
1891 // When a float is promoted to double or long double, or a
1892 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001893 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001894 (FromBuiltin->getKind() == BuiltinType::Float ||
1895 FromBuiltin->getKind() == BuiltinType::Double) &&
1896 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1897 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001898
1899 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001900 if (!getLangOpts().NativeHalfType &&
1901 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001902 ToBuiltin->getKind() == BuiltinType::Float)
1903 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001904 }
1905
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001906 return false;
1907}
1908
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001909/// \brief Determine if a conversion is a complex promotion.
1910///
1911/// A complex promotion is defined as a complex -> complex conversion
1912/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001913/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001914bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001915 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001916 if (!FromComplex)
1917 return false;
1918
John McCall9dd450b2009-09-21 23:43:11 +00001919 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001920 if (!ToComplex)
1921 return false;
1922
1923 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001924 ToComplex->getElementType()) ||
1925 IsIntegralPromotion(0, FromComplex->getElementType(),
1926 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001927}
1928
Douglas Gregor237f96c2008-11-26 23:31:11 +00001929/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1930/// the pointer type FromPtr to a pointer to type ToPointee, with the
1931/// same type qualifiers as FromPtr has on its pointee type. ToType,
1932/// if non-empty, will be a pointer to ToType that may or may not have
1933/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001934///
Mike Stump11289f42009-09-09 15:08:12 +00001935static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001936BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001937 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001938 ASTContext &Context,
1939 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001940 assert((FromPtr->getTypeClass() == Type::Pointer ||
1941 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1942 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001943
John McCall31168b02011-06-15 23:02:42 +00001944 /// Conversions to 'id' subsume cv-qualifier conversions.
1945 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001946 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
1948 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001949 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001950 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001951 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001952
John McCall31168b02011-06-15 23:02:42 +00001953 if (StripObjCLifetime)
1954 Quals.removeObjCLifetime();
1955
Mike Stump11289f42009-09-09 15:08:12 +00001956 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001957 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001958 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001959 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001960 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001961
1962 // Build a pointer to ToPointee. It has the right qualifiers
1963 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001964 if (isa<ObjCObjectPointerType>(ToType))
1965 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001966 return Context.getPointerType(ToPointee);
1967 }
1968
1969 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001970 QualType QualifiedCanonToPointee
1971 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001973 if (isa<ObjCObjectPointerType>(ToType))
1974 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1975 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001976}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001977
Mike Stump11289f42009-09-09 15:08:12 +00001978static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001979 bool InOverloadResolution,
1980 ASTContext &Context) {
1981 // Handle value-dependent integral null pointer constants correctly.
1982 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1983 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001984 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001985 return !InOverloadResolution;
1986
Douglas Gregor56751b52009-09-25 04:25:58 +00001987 return Expr->isNullPointerConstant(Context,
1988 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1989 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001990}
Mike Stump11289f42009-09-09 15:08:12 +00001991
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001992/// IsPointerConversion - Determines whether the conversion of the
1993/// expression From, which has the (possibly adjusted) type FromType,
1994/// can be converted to the type ToType via a pointer conversion (C++
1995/// 4.10). If so, returns true and places the converted type (that
1996/// might differ from ToType in its cv-qualifiers at some level) into
1997/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001998///
Douglas Gregora29dc052008-11-27 01:19:21 +00001999/// This routine also supports conversions to and from block pointers
2000/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2001/// pointers to interfaces. FIXME: Once we've determined the
2002/// appropriate overloading rules for Objective-C, we may want to
2003/// split the Objective-C checks into a different routine; however,
2004/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002005/// conversions, so for now they live here. IncompatibleObjC will be
2006/// set if the conversion is an allowed Objective-C conversion that
2007/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002008bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002009 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002010 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002011 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002012 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002013 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2014 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002015 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002016
Mike Stump11289f42009-09-09 15:08:12 +00002017 // Conversion from a null pointer constant to any Objective-C pointer type.
2018 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002019 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002020 ConvertedType = ToType;
2021 return true;
2022 }
2023
Douglas Gregor231d1c62008-11-27 00:15:41 +00002024 // Blocks: Block pointers can be converted to void*.
2025 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002026 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002027 ConvertedType = ToType;
2028 return true;
2029 }
2030 // Blocks: A null pointer constant can be converted to a block
2031 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002032 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002033 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002034 ConvertedType = ToType;
2035 return true;
2036 }
2037
Sebastian Redl576fd422009-05-10 18:38:11 +00002038 // If the left-hand-side is nullptr_t, the right side can be a null
2039 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002040 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002041 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002042 ConvertedType = ToType;
2043 return true;
2044 }
2045
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002046 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047 if (!ToTypePtr)
2048 return false;
2049
2050 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002051 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002052 ConvertedType = ToType;
2053 return true;
2054 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002055
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002056 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002057 // , including objective-c pointers.
2058 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002059 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002060 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002061 ConvertedType = BuildSimilarlyQualifiedPointerType(
2062 FromType->getAs<ObjCObjectPointerType>(),
2063 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002064 ToType, Context);
2065 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002066 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002067 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002068 if (!FromTypePtr)
2069 return false;
2070
2071 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002072
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002073 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002074 // pointer conversion, so don't do all of the work below.
2075 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2076 return false;
2077
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002078 // An rvalue of type "pointer to cv T," where T is an object type,
2079 // can be converted to an rvalue of type "pointer to cv void" (C++
2080 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002081 if (FromPointeeType->isIncompleteOrObjectType() &&
2082 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002083 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002084 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002085 ToType, Context,
2086 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002087 return true;
2088 }
2089
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002090 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002091 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002092 ToPointeeType->isVoidType()) {
2093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2094 ToPointeeType,
2095 ToType, Context);
2096 return true;
2097 }
2098
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002099 // When we're overloading in C, we allow a special kind of pointer
2100 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002101 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002102 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002104 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002105 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002106 return true;
2107 }
2108
Douglas Gregor5c407d92008-10-23 00:40:37 +00002109 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002110 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002111 // An rvalue of type "pointer to cv D," where D is a class type,
2112 // can be converted to an rvalue of type "pointer to cv B," where
2113 // B is a base class (clause 10) of D. If B is an inaccessible
2114 // (clause 11) or ambiguous (10.2) base class of D, a program that
2115 // necessitates this conversion is ill-formed. The result of the
2116 // conversion is a pointer to the base class sub-object of the
2117 // derived class object. The null pointer value is converted to
2118 // the null pointer value of the destination type.
2119 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002120 // Note that we do not check for ambiguity or inaccessibility
2121 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002122 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002123 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002124 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002125 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002126 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002127 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002128 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002129 ToType, Context);
2130 return true;
2131 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002132
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002133 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2134 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2135 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2136 ToPointeeType,
2137 ToType, Context);
2138 return true;
2139 }
2140
Douglas Gregora119f102008-12-19 19:13:09 +00002141 return false;
2142}
Douglas Gregoraec25842011-04-26 23:16:46 +00002143
2144/// \brief Adopt the given qualifiers for the given type.
2145static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2146 Qualifiers TQs = T.getQualifiers();
2147
2148 // Check whether qualifiers already match.
2149 if (TQs == Qs)
2150 return T;
2151
2152 if (Qs.compatiblyIncludes(TQs))
2153 return Context.getQualifiedType(T, Qs);
2154
2155 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2156}
Douglas Gregora119f102008-12-19 19:13:09 +00002157
2158/// isObjCPointerConversion - Determines whether this is an
2159/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2160/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002161bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002162 QualType& ConvertedType,
2163 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002164 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002165 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002166
Douglas Gregoraec25842011-04-26 23:16:46 +00002167 // The set of qualifiers on the type we're converting from.
2168 Qualifiers FromQualifiers = FromType.getQualifiers();
2169
Steve Naroff7cae42b2009-07-10 23:34:53 +00002170 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002171 const ObjCObjectPointerType* ToObjCPtr =
2172 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002173 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002174 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002175
Steve Naroff7cae42b2009-07-10 23:34:53 +00002176 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002177 // If the pointee types are the same (ignoring qualifications),
2178 // then this is not a pointer conversion.
2179 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2180 FromObjCPtr->getPointeeType()))
2181 return false;
2182
Douglas Gregoraec25842011-04-26 23:16:46 +00002183 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002184 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002185 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002186 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002187 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002188 return true;
2189 }
2190 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002191 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002192 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002193 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002194 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002195 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002196 return true;
2197 }
2198 // Objective C++: We're able to convert from a pointer to an
2199 // interface to a pointer to a different interface.
2200 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002201 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2202 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002203 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002204 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2205 FromObjCPtr->getPointeeType()))
2206 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002207 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002208 ToObjCPtr->getPointeeType(),
2209 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002210 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002211 return true;
2212 }
2213
2214 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2215 // Okay: this is some kind of implicit downcast of Objective-C
2216 // interfaces, which is permitted. However, we're going to
2217 // complain about it.
2218 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002219 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002220 ToObjCPtr->getPointeeType(),
2221 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002222 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002223 return true;
2224 }
Mike Stump11289f42009-09-09 15:08:12 +00002225 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002226 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002227 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002228 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002229 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002230 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002231 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002232 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002233 // to a block pointer type.
2234 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002235 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002236 return true;
2237 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002238 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002239 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002241 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002243 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002245 return true;
2246 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002247 else
Douglas Gregora119f102008-12-19 19:13:09 +00002248 return false;
2249
Douglas Gregor033f56d2008-12-23 00:53:59 +00002250 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002251 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002252 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002253 else if (const BlockPointerType *FromBlockPtr =
2254 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002255 FromPointeeType = FromBlockPtr->getPointeeType();
2256 else
Douglas Gregora119f102008-12-19 19:13:09 +00002257 return false;
2258
Douglas Gregora119f102008-12-19 19:13:09 +00002259 // If we have pointers to pointers, recursively check whether this
2260 // is an Objective-C conversion.
2261 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2262 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2263 IncompatibleObjC)) {
2264 // We always complain about this conversion.
2265 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002266 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002267 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002268 return true;
2269 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002270 // Allow conversion of pointee being objective-c pointer to another one;
2271 // as in I* to id.
2272 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2273 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2274 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2275 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002276
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002277 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002278 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002279 return true;
2280 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002281
Douglas Gregor033f56d2008-12-23 00:53:59 +00002282 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002283 // differences in the argument and result types are in Objective-C
2284 // pointer conversions. If so, we permit the conversion (but
2285 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002286 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002287 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002288 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002289 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002290 if (FromFunctionType && ToFunctionType) {
2291 // If the function types are exactly the same, this isn't an
2292 // Objective-C pointer conversion.
2293 if (Context.getCanonicalType(FromPointeeType)
2294 == Context.getCanonicalType(ToPointeeType))
2295 return false;
2296
2297 // Perform the quick checks that will tell us whether these
2298 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002299 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Douglas Gregora119f102008-12-19 19:13:09 +00002300 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2301 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2302 return false;
2303
2304 bool HasObjCConversion = false;
2305 if (Context.getCanonicalType(FromFunctionType->getResultType())
2306 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2307 // Okay, the types match exactly. Nothing to do.
2308 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2309 ToFunctionType->getResultType(),
2310 ConvertedType, IncompatibleObjC)) {
2311 // Okay, we have an Objective-C pointer conversion.
2312 HasObjCConversion = true;
2313 } else {
2314 // Function types are too different. Abort.
2315 return false;
2316 }
Mike Stump11289f42009-09-09 15:08:12 +00002317
Douglas Gregora119f102008-12-19 19:13:09 +00002318 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002319 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Douglas Gregora119f102008-12-19 19:13:09 +00002320 ArgIdx != NumArgs; ++ArgIdx) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002321 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2322 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Douglas Gregora119f102008-12-19 19:13:09 +00002323 if (Context.getCanonicalType(FromArgType)
2324 == Context.getCanonicalType(ToArgType)) {
2325 // Okay, the types match exactly. Nothing to do.
2326 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2327 ConvertedType, IncompatibleObjC)) {
2328 // Okay, we have an Objective-C pointer conversion.
2329 HasObjCConversion = true;
2330 } else {
2331 // Argument types are too different. Abort.
2332 return false;
2333 }
2334 }
2335
2336 if (HasObjCConversion) {
2337 // We had an Objective-C conversion. Allow this pointer
2338 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002339 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002340 IncompatibleObjC = true;
2341 return true;
2342 }
2343 }
2344
Sebastian Redl72b597d2009-01-25 19:43:20 +00002345 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002346}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347
John McCall31168b02011-06-15 23:02:42 +00002348/// \brief Determine whether this is an Objective-C writeback conversion,
2349/// used for parameter passing when performing automatic reference counting.
2350///
2351/// \param FromType The type we're converting form.
2352///
2353/// \param ToType The type we're converting to.
2354///
2355/// \param ConvertedType The type that will be produced after applying
2356/// this conversion.
2357bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2358 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002359 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002360 Context.hasSameUnqualifiedType(FromType, ToType))
2361 return false;
2362
2363 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2364 QualType ToPointee;
2365 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2366 ToPointee = ToPointer->getPointeeType();
2367 else
2368 return false;
2369
2370 Qualifiers ToQuals = ToPointee.getQualifiers();
2371 if (!ToPointee->isObjCLifetimeType() ||
2372 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002373 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002374 return false;
2375
2376 // Argument must be a pointer to __strong to __weak.
2377 QualType FromPointee;
2378 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2379 FromPointee = FromPointer->getPointeeType();
2380 else
2381 return false;
2382
2383 Qualifiers FromQuals = FromPointee.getQualifiers();
2384 if (!FromPointee->isObjCLifetimeType() ||
2385 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2386 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2387 return false;
2388
2389 // Make sure that we have compatible qualifiers.
2390 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2391 if (!ToQuals.compatiblyIncludes(FromQuals))
2392 return false;
2393
2394 // Remove qualifiers from the pointee type we're converting from; they
2395 // aren't used in the compatibility check belong, and we'll be adding back
2396 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2397 FromPointee = FromPointee.getUnqualifiedType();
2398
2399 // The unqualified form of the pointee types must be compatible.
2400 ToPointee = ToPointee.getUnqualifiedType();
2401 bool IncompatibleObjC;
2402 if (Context.typesAreCompatible(FromPointee, ToPointee))
2403 FromPointee = ToPointee;
2404 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2405 IncompatibleObjC))
2406 return false;
2407
2408 /// \brief Construct the type we're converting to, which is a pointer to
2409 /// __autoreleasing pointee.
2410 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2411 ConvertedType = Context.getPointerType(FromPointee);
2412 return true;
2413}
2414
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002415bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2416 QualType& ConvertedType) {
2417 QualType ToPointeeType;
2418 if (const BlockPointerType *ToBlockPtr =
2419 ToType->getAs<BlockPointerType>())
2420 ToPointeeType = ToBlockPtr->getPointeeType();
2421 else
2422 return false;
2423
2424 QualType FromPointeeType;
2425 if (const BlockPointerType *FromBlockPtr =
2426 FromType->getAs<BlockPointerType>())
2427 FromPointeeType = FromBlockPtr->getPointeeType();
2428 else
2429 return false;
2430 // We have pointer to blocks, check whether the only
2431 // differences in the argument and result types are in Objective-C
2432 // pointer conversions. If so, we permit the conversion.
2433
2434 const FunctionProtoType *FromFunctionType
2435 = FromPointeeType->getAs<FunctionProtoType>();
2436 const FunctionProtoType *ToFunctionType
2437 = ToPointeeType->getAs<FunctionProtoType>();
2438
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002439 if (!FromFunctionType || !ToFunctionType)
2440 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002441
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002442 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002443 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002444
2445 // Perform the quick checks that will tell us whether these
2446 // function types are obviously different.
Alp Toker9cacbab2014-01-20 20:26:09 +00002447 if (FromFunctionType->getNumParams() != ToFunctionType->getNumParams() ||
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002448 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2449 return false;
2450
2451 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2452 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2453 if (FromEInfo != ToEInfo)
2454 return false;
2455
2456 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002457 if (Context.hasSameType(FromFunctionType->getResultType(),
2458 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002459 // Okay, the types match exactly. Nothing to do.
2460 } else {
2461 QualType RHS = FromFunctionType->getResultType();
2462 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002463 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002464 !RHS.hasQualifiers() && LHS.hasQualifiers())
2465 LHS = LHS.getUnqualifiedType();
2466
2467 if (Context.hasSameType(RHS,LHS)) {
2468 // OK exact match.
2469 } else if (isObjCPointerConversion(RHS, LHS,
2470 ConvertedType, IncompatibleObjC)) {
2471 if (IncompatibleObjC)
2472 return false;
2473 // Okay, we have an Objective-C pointer conversion.
2474 }
2475 else
2476 return false;
2477 }
2478
2479 // Check argument types.
Alp Toker9cacbab2014-01-20 20:26:09 +00002480 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumParams();
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002481 ArgIdx != NumArgs; ++ArgIdx) {
2482 IncompatibleObjC = false;
Alp Toker9cacbab2014-01-20 20:26:09 +00002483 QualType FromArgType = FromFunctionType->getParamType(ArgIdx);
2484 QualType ToArgType = ToFunctionType->getParamType(ArgIdx);
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002485 if (Context.hasSameType(FromArgType, ToArgType)) {
2486 // Okay, the types match exactly. Nothing to do.
2487 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2488 ConvertedType, IncompatibleObjC)) {
2489 if (IncompatibleObjC)
2490 return false;
2491 // Okay, we have an Objective-C pointer conversion.
2492 } else
2493 // Argument types are too different. Abort.
2494 return false;
2495 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002496 if (LangOpts.ObjCAutoRefCount &&
2497 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2498 ToFunctionType))
2499 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002500
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002501 ConvertedType = ToType;
2502 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002503}
2504
Richard Trieucaff2472011-11-23 22:32:32 +00002505enum {
2506 ft_default,
2507 ft_different_class,
2508 ft_parameter_arity,
2509 ft_parameter_mismatch,
2510 ft_return_type,
2511 ft_qualifer_mismatch
2512};
2513
2514/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2515/// function types. Catches different number of parameter, mismatch in
2516/// parameter types, and different return types.
2517void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2518 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002519 // If either type is not valid, include no extra info.
2520 if (FromType.isNull() || ToType.isNull()) {
2521 PDiag << ft_default;
2522 return;
2523 }
2524
Richard Trieucaff2472011-11-23 22:32:32 +00002525 // Get the function type from the pointers.
2526 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2527 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2528 *ToMember = ToType->getAs<MemberPointerType>();
2529 if (FromMember->getClass() != ToMember->getClass()) {
2530 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2531 << QualType(FromMember->getClass(), 0);
2532 return;
2533 }
2534 FromType = FromMember->getPointeeType();
2535 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002536 }
2537
Richard Trieu96ed5b62011-12-13 23:19:45 +00002538 if (FromType->isPointerType())
2539 FromType = FromType->getPointeeType();
2540 if (ToType->isPointerType())
2541 ToType = ToType->getPointeeType();
2542
2543 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002544 FromType = FromType.getNonReferenceType();
2545 ToType = ToType.getNonReferenceType();
2546
Richard Trieucaff2472011-11-23 22:32:32 +00002547 // Don't print extra info for non-specialized template functions.
2548 if (FromType->isInstantiationDependentType() &&
2549 !FromType->getAs<TemplateSpecializationType>()) {
2550 PDiag << ft_default;
2551 return;
2552 }
2553
Richard Trieu96ed5b62011-12-13 23:19:45 +00002554 // No extra info for same types.
2555 if (Context.hasSameType(FromType, ToType)) {
2556 PDiag << ft_default;
2557 return;
2558 }
2559
Richard Trieucaff2472011-11-23 22:32:32 +00002560 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2561 *ToFunction = ToType->getAs<FunctionProtoType>();
2562
2563 // Both types need to be function types.
2564 if (!FromFunction || !ToFunction) {
2565 PDiag << ft_default;
2566 return;
2567 }
2568
Alp Toker9cacbab2014-01-20 20:26:09 +00002569 if (FromFunction->getNumParams() != ToFunction->getNumParams()) {
2570 PDiag << ft_parameter_arity << ToFunction->getNumParams()
2571 << FromFunction->getNumParams();
Richard Trieucaff2472011-11-23 22:32:32 +00002572 return;
2573 }
2574
2575 // Handle different parameter types.
2576 unsigned ArgPos;
Alp Toker9cacbab2014-01-20 20:26:09 +00002577 if (!FunctionParamTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
Richard Trieucaff2472011-11-23 22:32:32 +00002578 PDiag << ft_parameter_mismatch << ArgPos + 1
Alp Toker9cacbab2014-01-20 20:26:09 +00002579 << ToFunction->getParamType(ArgPos)
2580 << FromFunction->getParamType(ArgPos);
Richard Trieucaff2472011-11-23 22:32:32 +00002581 return;
2582 }
2583
2584 // Handle different return type.
2585 if (!Context.hasSameType(FromFunction->getResultType(),
2586 ToFunction->getResultType())) {
2587 PDiag << ft_return_type << ToFunction->getResultType()
2588 << FromFunction->getResultType();
2589 return;
2590 }
2591
2592 unsigned FromQuals = FromFunction->getTypeQuals(),
2593 ToQuals = ToFunction->getTypeQuals();
2594 if (FromQuals != ToQuals) {
2595 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2596 return;
2597 }
2598
2599 // Unable to find a difference, so add no extra info.
2600 PDiag << ft_default;
2601}
2602
Alp Toker9cacbab2014-01-20 20:26:09 +00002603/// FunctionParamTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002604/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002605/// they have same number of arguments. If the parameters are different,
2606/// ArgPos will have the parameter index of the first different parameter.
Alp Toker9cacbab2014-01-20 20:26:09 +00002607bool Sema::FunctionParamTypesAreEqual(const FunctionProtoType *OldType,
2608 const FunctionProtoType *NewType,
2609 unsigned *ArgPos) {
2610 for (FunctionProtoType::param_type_iterator O = OldType->param_type_begin(),
2611 N = NewType->param_type_begin(),
2612 E = OldType->param_type_end();
2613 O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002614 if (!Context.hasSameType(O->getUnqualifiedType(),
2615 N->getUnqualifiedType())) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002616 if (ArgPos)
2617 *ArgPos = O - OldType->param_type_begin();
Larisse Voufo4154f462013-08-06 03:57:41 +00002618 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002619 }
2620 }
2621 return true;
2622}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002623
Douglas Gregor39c16d42008-10-24 04:54:22 +00002624/// CheckPointerConversion - Check the pointer conversion from the
2625/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002626/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002627/// conversions for which IsPointerConversion has already returned
2628/// true. It returns true and produces a diagnostic if there was an
2629/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002630bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002631 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002632 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002633 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002634 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002635 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002636
John McCall8cb679e2010-11-15 09:13:47 +00002637 Kind = CK_BitCast;
2638
David Blaikie1c7c8f72012-08-08 17:33:31 +00002639 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2640 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2641 Expr::NPCK_ZeroExpression) {
2642 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2643 DiagRuntimeBehavior(From->getExprLoc(), From,
2644 PDiag(diag::warn_impcast_bool_to_null_pointer)
2645 << ToType << From->getSourceRange());
2646 else if (!isUnevaluatedContext())
2647 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2648 << ToType << From->getSourceRange();
2649 }
John McCall9320b872011-09-09 05:25:32 +00002650 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2651 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002652 QualType FromPointeeType = FromPtrType->getPointeeType(),
2653 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002654
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002655 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2656 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002657 // We must have a derived-to-base conversion. Check an
2658 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002659 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2660 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002661 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002662 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002663 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002665 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002666 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002667 }
2668 }
John McCall9320b872011-09-09 05:25:32 +00002669 } else if (const ObjCObjectPointerType *ToPtrType =
2670 ToType->getAs<ObjCObjectPointerType>()) {
2671 if (const ObjCObjectPointerType *FromPtrType =
2672 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002673 // Objective-C++ conversions are always okay.
2674 // FIXME: We should have a different class of conversions for the
2675 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002676 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002677 return false;
John McCall9320b872011-09-09 05:25:32 +00002678 } else if (FromType->isBlockPointerType()) {
2679 Kind = CK_BlockPointerToObjCPointerCast;
2680 } else {
2681 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002682 }
John McCall9320b872011-09-09 05:25:32 +00002683 } else if (ToType->isBlockPointerType()) {
2684 if (!FromType->isBlockPointerType())
2685 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002686 }
John McCall8cb679e2010-11-15 09:13:47 +00002687
2688 // We shouldn't fall into this case unless it's valid for other
2689 // reasons.
2690 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2691 Kind = CK_NullToPointer;
2692
Douglas Gregor39c16d42008-10-24 04:54:22 +00002693 return false;
2694}
2695
Sebastian Redl72b597d2009-01-25 19:43:20 +00002696/// IsMemberPointerConversion - Determines whether the conversion of the
2697/// expression From, which has the (possibly adjusted) type FromType, can be
2698/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2699/// If so, returns true and places the converted type (that might differ from
2700/// ToType in its cv-qualifiers at some level) into ConvertedType.
2701bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002703 bool InOverloadResolution,
2704 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002705 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002706 if (!ToTypePtr)
2707 return false;
2708
2709 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002710 if (From->isNullPointerConstant(Context,
2711 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2712 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002713 ConvertedType = ToType;
2714 return true;
2715 }
2716
2717 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002718 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002719 if (!FromTypePtr)
2720 return false;
2721
2722 // A pointer to member of B can be converted to a pointer to member of D,
2723 // where D is derived from B (C++ 4.11p2).
2724 QualType FromClass(FromTypePtr->getClass(), 0);
2725 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002726
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002727 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002728 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002729 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002730 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2731 ToClass.getTypePtr());
2732 return true;
2733 }
2734
2735 return false;
2736}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002737
Sebastian Redl72b597d2009-01-25 19:43:20 +00002738/// CheckMemberPointerConversion - Check the member pointer conversion from the
2739/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002740/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002741/// for which IsMemberPointerConversion has already returned true. It returns
2742/// true and produces a diagnostic if there was an error, or returns false
2743/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002744bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002745 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002746 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002747 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002748 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002749 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002750 if (!FromPtrType) {
2751 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002752 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002753 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002754 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002755 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002756 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002757 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002758
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002759 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002760 assert(ToPtrType && "No member pointer cast has a target type "
2761 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002762
Sebastian Redled8f2002009-01-28 18:33:18 +00002763 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2764 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002765
Sebastian Redled8f2002009-01-28 18:33:18 +00002766 // FIXME: What about dependent types?
2767 assert(FromClass->isRecordType() && "Pointer into non-class.");
2768 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002769
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002770 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002771 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002772 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2773 assert(DerivationOkay &&
2774 "Should not have been called if derivation isn't OK.");
2775 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002776
Sebastian Redled8f2002009-01-28 18:33:18 +00002777 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2778 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002779 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2780 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2781 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2782 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002783 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002784
Douglas Gregor89ee6822009-02-28 01:32:25 +00002785 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002786 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2787 << FromClass << ToClass << QualType(VBase, 0)
2788 << From->getSourceRange();
2789 return true;
2790 }
2791
John McCall5b0829a2010-02-10 09:31:12 +00002792 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002793 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2794 Paths.front(),
2795 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002796
Anders Carlssond7923c62009-08-22 23:33:40 +00002797 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002798 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002799 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002800 return false;
2801}
2802
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002803/// Determine whether the lifetime conversion between the two given
2804/// qualifiers sets is nontrivial.
2805static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2806 Qualifiers ToQuals) {
2807 // Converting anything to const __unsafe_unretained is trivial.
2808 if (ToQuals.hasConst() &&
2809 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2810 return false;
2811
2812 return true;
2813}
2814
Douglas Gregor9a657932008-10-21 23:43:52 +00002815/// IsQualificationConversion - Determines whether the conversion from
2816/// an rvalue of type FromType to ToType is a qualification conversion
2817/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002818///
2819/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2820/// when the qualification conversion involves a change in the Objective-C
2821/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002822bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002823Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002824 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002825 FromType = Context.getCanonicalType(FromType);
2826 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002827 ObjCLifetimeConversion = false;
2828
Douglas Gregor9a657932008-10-21 23:43:52 +00002829 // If FromType and ToType are the same type, this is not a
2830 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002831 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002832 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002833
Douglas Gregor9a657932008-10-21 23:43:52 +00002834 // (C++ 4.4p4):
2835 // A conversion can add cv-qualifiers at levels other than the first
2836 // in multi-level pointers, subject to the following rules: [...]
2837 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002838 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002839 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002840 // Within each iteration of the loop, we check the qualifiers to
2841 // determine if this still looks like a qualification
2842 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002843 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002844 // until there are no more pointers or pointers-to-members left to
2845 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002846 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002847
Douglas Gregor90609aa2011-04-25 18:40:17 +00002848 Qualifiers FromQuals = FromType.getQualifiers();
2849 Qualifiers ToQuals = ToType.getQualifiers();
2850
John McCall31168b02011-06-15 23:02:42 +00002851 // Objective-C ARC:
2852 // Check Objective-C lifetime conversions.
2853 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2854 UnwrappedAnyPointer) {
2855 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002856 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2857 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002858 FromQuals.removeObjCLifetime();
2859 ToQuals.removeObjCLifetime();
2860 } else {
2861 // Qualification conversions cannot cast between different
2862 // Objective-C lifetime qualifiers.
2863 return false;
2864 }
2865 }
2866
Douglas Gregorf30053d2011-05-08 06:09:53 +00002867 // Allow addition/removal of GC attributes but not changing GC attributes.
2868 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2869 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2870 FromQuals.removeObjCGCAttr();
2871 ToQuals.removeObjCGCAttr();
2872 }
2873
Douglas Gregor9a657932008-10-21 23:43:52 +00002874 // -- for every j > 0, if const is in cv 1,j then const is in cv
2875 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002876 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002877 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002878
Douglas Gregor9a657932008-10-21 23:43:52 +00002879 // -- if the cv 1,j and cv 2,j are different, then const is in
2880 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002881 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002882 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002883 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002884
Douglas Gregor9a657932008-10-21 23:43:52 +00002885 // Keep track of whether all prior cv-qualifiers in the "to" type
2886 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002887 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002888 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002889 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002890
2891 // We are left with FromType and ToType being the pointee types
2892 // after unwrapping the original FromType and ToType the same number
2893 // of types. If we unwrapped any pointers, and if FromType and
2894 // ToType have the same unqualified type (since we checked
2895 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002896 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002897}
2898
Douglas Gregorc79862f2012-04-12 17:51:55 +00002899/// \brief - Determine whether this is a conversion from a scalar type to an
2900/// atomic type.
2901///
2902/// If successful, updates \c SCS's second and third steps in the conversion
2903/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002904static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2905 bool InOverloadResolution,
2906 StandardConversionSequence &SCS,
2907 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002908 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2909 if (!ToAtomic)
2910 return false;
2911
2912 StandardConversionSequence InnerSCS;
2913 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2914 InOverloadResolution, InnerSCS,
2915 CStyle, /*AllowObjCWritebackConversion=*/false))
2916 return false;
2917
2918 SCS.Second = InnerSCS.Second;
2919 SCS.setToType(1, InnerSCS.getToType(1));
2920 SCS.Third = InnerSCS.Third;
2921 SCS.QualificationIncludesObjCLifetime
2922 = InnerSCS.QualificationIncludesObjCLifetime;
2923 SCS.setToType(2, InnerSCS.getToType(2));
2924 return true;
2925}
2926
Sebastian Redle5417162012-03-27 18:33:03 +00002927static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2928 CXXConstructorDecl *Constructor,
2929 QualType Type) {
2930 const FunctionProtoType *CtorType =
2931 Constructor->getType()->getAs<FunctionProtoType>();
Alp Toker9cacbab2014-01-20 20:26:09 +00002932 if (CtorType->getNumParams() > 0) {
2933 QualType FirstArg = CtorType->getParamType(0);
Sebastian Redle5417162012-03-27 18:33:03 +00002934 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2935 return true;
2936 }
2937 return false;
2938}
2939
Sebastian Redl82ace982012-02-11 23:51:08 +00002940static OverloadingResult
2941IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2942 CXXRecordDecl *To,
2943 UserDefinedConversionSequence &User,
2944 OverloadCandidateSet &CandidateSet,
2945 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002946 DeclContext::lookup_result R = S.LookupConstructors(To);
2947 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002948 Con != ConEnd; ++Con) {
2949 NamedDecl *D = *Con;
2950 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2951
2952 // Find the constructor (which may be a template).
2953 CXXConstructorDecl *Constructor = 0;
2954 FunctionTemplateDecl *ConstructorTmpl
2955 = dyn_cast<FunctionTemplateDecl>(D);
2956 if (ConstructorTmpl)
2957 Constructor
2958 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2959 else
2960 Constructor = cast<CXXConstructorDecl>(D);
2961
2962 bool Usable = !Constructor->isInvalidDecl() &&
2963 S.isInitListConstructor(Constructor) &&
2964 (AllowExplicit || !Constructor->isExplicit());
2965 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002966 // If the first argument is (a reference to) the target type,
2967 // suppress conversions.
2968 bool SuppressUserConversions =
2969 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002970 if (ConstructorTmpl)
2971 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2972 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002973 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002974 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002975 else
2976 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002977 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002978 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002979 }
2980 }
2981
2982 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2983
2984 OverloadCandidateSet::iterator Best;
2985 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2986 case OR_Success: {
2987 // Record the standard conversion we used and the conversion function.
2988 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002989 QualType ThisType = Constructor->getThisType(S.Context);
2990 // Initializer lists don't have conversions as such.
2991 User.Before.setAsIdentityConversion();
2992 User.HadMultipleCandidates = HadMultipleCandidates;
2993 User.ConversionFunction = Constructor;
2994 User.FoundConversionFunction = Best->FoundDecl;
2995 User.After.setAsIdentityConversion();
2996 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2997 User.After.setAllToTypes(ToType);
2998 return OR_Success;
2999 }
3000
3001 case OR_No_Viable_Function:
3002 return OR_No_Viable_Function;
3003 case OR_Deleted:
3004 return OR_Deleted;
3005 case OR_Ambiguous:
3006 return OR_Ambiguous;
3007 }
3008
3009 llvm_unreachable("Invalid OverloadResult!");
3010}
3011
Douglas Gregor576e98c2009-01-30 23:27:23 +00003012/// Determines whether there is a user-defined conversion sequence
3013/// (C++ [over.ics.user]) that converts expression From to the type
3014/// ToType. If such a conversion exists, User will contain the
3015/// user-defined conversion sequence that performs such a conversion
3016/// and this routine will return true. Otherwise, this routine returns
3017/// false and User is unspecified.
3018///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003019/// \param AllowExplicit true if the conversion should consider C++0x
3020/// "explicit" conversion functions as well as non-explicit conversion
3021/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003022///
3023/// \param AllowObjCConversionOnExplicit true if the conversion should
3024/// allow an extra Objective-C pointer conversion on uses of explicit
3025/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003026static OverloadingResult
3027IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003028 UserDefinedConversionSequence &User,
3029 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003030 bool AllowExplicit,
3031 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003032 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003033
Douglas Gregor5ab11652010-04-17 22:01:05 +00003034 // Whether we will only visit constructors.
3035 bool ConstructorsOnly = false;
3036
3037 // If the type we are conversion to is a class type, enumerate its
3038 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003039 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003040 // C++ [over.match.ctor]p1:
3041 // When objects of class type are direct-initialized (8.5), or
3042 // copy-initialized from an expression of the same or a
3043 // derived class type (8.5), overload resolution selects the
3044 // constructor. [...] For copy-initialization, the candidate
3045 // functions are all the converting constructors (12.3.1) of
3046 // that class. The argument list is the expression-list within
3047 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003048 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003049 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003050 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003051 ConstructorsOnly = true;
3052
Benjamin Kramer90633e32012-11-23 17:04:52 +00003053 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003054 // RequireCompleteType may have returned true due to some invalid decl
3055 // during template instantiation, but ToType may be complete enough now
3056 // to try to recover.
3057 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003058 // We're not going to find any constructors.
3059 } else if (CXXRecordDecl *ToRecordDecl
3060 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003061
3062 Expr **Args = &From;
3063 unsigned NumArgs = 1;
3064 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003065 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003066 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003067 OverloadingResult Result = IsInitializerListConstructorConversion(
3068 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3069 if (Result != OR_No_Viable_Function)
3070 return Result;
3071 // Never mind.
3072 CandidateSet.clear();
3073
3074 // If we're list-initializing, we pass the individual elements as
3075 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003076 Args = InitList->getInits();
3077 NumArgs = InitList->getNumInits();
3078 ListInitializing = true;
3079 }
3080
David Blaikieff7d47a2012-12-19 00:45:41 +00003081 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3082 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003083 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003084 NamedDecl *D = *Con;
3085 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3086
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003087 // Find the constructor (which may be a template).
3088 CXXConstructorDecl *Constructor = 0;
3089 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003090 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003091 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003092 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003093 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3094 else
John McCalla0296f72010-03-19 07:35:19 +00003095 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003097 bool Usable = !Constructor->isInvalidDecl();
3098 if (ListInitializing)
3099 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3100 else
3101 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3102 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003103 bool SuppressUserConversions = !ConstructorsOnly;
3104 if (SuppressUserConversions && ListInitializing) {
3105 SuppressUserConversions = false;
3106 if (NumArgs == 1) {
3107 // If the first argument is (a reference to) the target type,
3108 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003109 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3110 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003111 }
3112 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003113 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003114 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3115 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003116 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003117 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003118 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003119 // Allow one user-defined conversion when user specifies a
3120 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003121 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003122 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003123 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003124 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003125 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003126 }
3127 }
3128
Douglas Gregor5ab11652010-04-17 22:01:05 +00003129 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003130 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003131 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003132 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003133 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003134 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003135 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003136 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3137 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003138 std::pair<CXXRecordDecl::conversion_iterator,
3139 CXXRecordDecl::conversion_iterator>
3140 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3141 for (CXXRecordDecl::conversion_iterator
3142 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003143 DeclAccessPair FoundDecl = I.getPair();
3144 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003145 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3146 if (isa<UsingShadowDecl>(D))
3147 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3148
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003149 CXXConversionDecl *Conv;
3150 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003151 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3152 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003153 else
John McCallda4458e2010-03-31 01:36:47 +00003154 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003155
3156 if (AllowExplicit || !Conv->isExplicit()) {
3157 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003158 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3159 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003160 CandidateSet,
3161 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003162 else
John McCall5c32be02010-08-24 20:38:10 +00003163 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003164 From, ToType, CandidateSet,
3165 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003166 }
3167 }
3168 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003169 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003170
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003171 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3172
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003173 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003174 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003175 case OR_Success:
3176 // Record the standard conversion we used and the conversion function.
3177 if (CXXConstructorDecl *Constructor
3178 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3179 // C++ [over.ics.user]p1:
3180 // If the user-defined conversion is specified by a
3181 // constructor (12.3.1), the initial standard conversion
3182 // sequence converts the source type to the type required by
3183 // the argument of the constructor.
3184 //
3185 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003186 if (isa<InitListExpr>(From)) {
3187 // Initializer lists don't have conversions as such.
3188 User.Before.setAsIdentityConversion();
3189 } else {
3190 if (Best->Conversions[0].isEllipsis())
3191 User.EllipsisConversion = true;
3192 else {
3193 User.Before = Best->Conversions[0].Standard;
3194 User.EllipsisConversion = false;
3195 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003196 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003197 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003198 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003199 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003200 User.After.setAsIdentityConversion();
3201 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3202 User.After.setAllToTypes(ToType);
3203 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003204 }
3205 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003206 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3207 // C++ [over.ics.user]p1:
3208 //
3209 // [...] If the user-defined conversion is specified by a
3210 // conversion function (12.3.2), the initial standard
3211 // conversion sequence converts the source type to the
3212 // implicit object parameter of the conversion function.
3213 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003214 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003215 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003216 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003217 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003218
John McCall5c32be02010-08-24 20:38:10 +00003219 // C++ [over.ics.user]p2:
3220 // The second standard conversion sequence converts the
3221 // result of the user-defined conversion to the target type
3222 // for the sequence. Since an implicit conversion sequence
3223 // is an initialization, the special rules for
3224 // initialization by user-defined conversion apply when
3225 // selecting the best user-defined conversion for a
3226 // user-defined conversion sequence (see 13.3.3 and
3227 // 13.3.3.1).
3228 User.After = Best->FinalConversion;
3229 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003230 }
David Blaikie8a40f702012-01-17 06:56:22 +00003231 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003232
John McCall5c32be02010-08-24 20:38:10 +00003233 case OR_No_Viable_Function:
3234 return OR_No_Viable_Function;
3235 case OR_Deleted:
3236 // No conversion here! We're done.
3237 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238
John McCall5c32be02010-08-24 20:38:10 +00003239 case OR_Ambiguous:
3240 return OR_Ambiguous;
3241 }
3242
David Blaikie8a40f702012-01-17 06:56:22 +00003243 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003244}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003246bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003247Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003248 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003249 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003251 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003252 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003253 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003254 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3255 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003256 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003257 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003258 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003259 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003260 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3261 << From->getType() << From->getSourceRange() << ToType;
3262 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003263 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003264 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003266}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003267
Douglas Gregor2837aa22012-02-22 17:32:19 +00003268/// \brief Compare the user-defined conversion functions or constructors
3269/// of two user-defined conversion sequences to determine whether any ordering
3270/// is possible.
3271static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003272compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003273 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003274 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003275 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003276
Douglas Gregor2837aa22012-02-22 17:32:19 +00003277 // Objective-C++:
3278 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003279 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003280 // respectively, always prefer the conversion to a function pointer,
3281 // because the function pointer is more lightweight and is more likely
3282 // to keep code working.
3283 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3284 if (!Conv1)
3285 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003286
Douglas Gregor2837aa22012-02-22 17:32:19 +00003287 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3288 if (!Conv2)
3289 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003290
Douglas Gregor2837aa22012-02-22 17:32:19 +00003291 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3292 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3293 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3294 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003295 return Block1 ? ImplicitConversionSequence::Worse
3296 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003297 }
3298
3299 return ImplicitConversionSequence::Indistinguishable;
3300}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003301
3302static bool hasDeprecatedStringLiteralToCharPtrConversion(
3303 const ImplicitConversionSequence &ICS) {
3304 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3305 (ICS.isUserDefined() &&
3306 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3307}
3308
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003309/// CompareImplicitConversionSequences - Compare two implicit
3310/// conversion sequences to determine whether one is better than the
3311/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003312static ImplicitConversionSequence::CompareKind
3313CompareImplicitConversionSequences(Sema &S,
3314 const ImplicitConversionSequence& ICS1,
3315 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003316{
3317 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3318 // conversion sequences (as defined in 13.3.3.1)
3319 // -- a standard conversion sequence (13.3.3.1.1) is a better
3320 // conversion sequence than a user-defined conversion sequence or
3321 // an ellipsis conversion sequence, and
3322 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3323 // conversion sequence than an ellipsis conversion sequence
3324 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003325 //
John McCall0d1da222010-01-12 00:44:57 +00003326 // C++0x [over.best.ics]p10:
3327 // For the purpose of ranking implicit conversion sequences as
3328 // described in 13.3.3.2, the ambiguous conversion sequence is
3329 // treated as a user-defined sequence that is indistinguishable
3330 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003331
3332 // String literal to 'char *' conversion has been deprecated in C++03. It has
3333 // been removed from C++11. We still accept this conversion, if it happens at
3334 // the best viable function. Otherwise, this conversion is considered worse
3335 // than ellipsis conversion. Consider this as an extension; this is not in the
3336 // standard. For example:
3337 //
3338 // int &f(...); // #1
3339 // void f(char*); // #2
3340 // void g() { int &r = f("foo"); }
3341 //
3342 // In C++03, we pick #2 as the best viable function.
3343 // In C++11, we pick #1 as the best viable function, because ellipsis
3344 // conversion is better than string-literal to char* conversion (since there
3345 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3346 // convert arguments, #2 would be the best viable function in C++11.
3347 // If the best viable function has this conversion, a warning will be issued
3348 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3349
3350 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3351 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3352 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3353 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3354 ? ImplicitConversionSequence::Worse
3355 : ImplicitConversionSequence::Better;
3356
Douglas Gregor5ab11652010-04-17 22:01:05 +00003357 if (ICS1.getKindRank() < ICS2.getKindRank())
3358 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003359 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003360 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003361
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003362 // The following checks require both conversion sequences to be of
3363 // the same kind.
3364 if (ICS1.getKind() != ICS2.getKind())
3365 return ImplicitConversionSequence::Indistinguishable;
3366
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003367 ImplicitConversionSequence::CompareKind Result =
3368 ImplicitConversionSequence::Indistinguishable;
3369
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003370 // Two implicit conversion sequences of the same form are
3371 // indistinguishable conversion sequences unless one of the
3372 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003373 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003374 Result = CompareStandardConversionSequences(S,
3375 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003376 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003377 // User-defined conversion sequence U1 is a better conversion
3378 // sequence than another user-defined conversion sequence U2 if
3379 // they contain the same user-defined conversion function or
3380 // constructor and if the second standard conversion sequence of
3381 // U1 is better than the second standard conversion sequence of
3382 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003383 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003384 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003385 Result = CompareStandardConversionSequences(S,
3386 ICS1.UserDefined.After,
3387 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003388 else
3389 Result = compareConversionFunctions(S,
3390 ICS1.UserDefined.ConversionFunction,
3391 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003392 }
3393
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003394 // List-initialization sequence L1 is a better conversion sequence than
3395 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3396 // for some X and L2 does not.
3397 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003398 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003399 if (ICS1.isStdInitializerListElement() &&
3400 !ICS2.isStdInitializerListElement())
3401 return ImplicitConversionSequence::Better;
3402 if (!ICS1.isStdInitializerListElement() &&
3403 ICS2.isStdInitializerListElement())
3404 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003405 }
3406
3407 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003408}
3409
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003410static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3411 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3412 Qualifiers Quals;
3413 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003415 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003416
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003417 return Context.hasSameUnqualifiedType(T1, T2);
3418}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003420// Per 13.3.3.2p3, compare the given standard conversion sequences to
3421// determine if one is a proper subset of the other.
3422static ImplicitConversionSequence::CompareKind
3423compareStandardConversionSubsets(ASTContext &Context,
3424 const StandardConversionSequence& SCS1,
3425 const StandardConversionSequence& SCS2) {
3426 ImplicitConversionSequence::CompareKind Result
3427 = ImplicitConversionSequence::Indistinguishable;
3428
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003429 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003430 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003431 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3432 return ImplicitConversionSequence::Better;
3433 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3434 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003435
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003436 if (SCS1.Second != SCS2.Second) {
3437 if (SCS1.Second == ICK_Identity)
3438 Result = ImplicitConversionSequence::Better;
3439 else if (SCS2.Second == ICK_Identity)
3440 Result = ImplicitConversionSequence::Worse;
3441 else
3442 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003443 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003444 return ImplicitConversionSequence::Indistinguishable;
3445
3446 if (SCS1.Third == SCS2.Third) {
3447 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3448 : ImplicitConversionSequence::Indistinguishable;
3449 }
3450
3451 if (SCS1.Third == ICK_Identity)
3452 return Result == ImplicitConversionSequence::Worse
3453 ? ImplicitConversionSequence::Indistinguishable
3454 : ImplicitConversionSequence::Better;
3455
3456 if (SCS2.Third == ICK_Identity)
3457 return Result == ImplicitConversionSequence::Better
3458 ? ImplicitConversionSequence::Indistinguishable
3459 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003460
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003461 return ImplicitConversionSequence::Indistinguishable;
3462}
3463
Douglas Gregore696ebb2011-01-26 14:52:12 +00003464/// \brief Determine whether one of the given reference bindings is better
3465/// than the other based on what kind of bindings they are.
3466static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3467 const StandardConversionSequence &SCS2) {
3468 // C++0x [over.ics.rank]p3b4:
3469 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3470 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003471 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003472 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003473 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003474 // reference*.
3475 //
3476 // FIXME: Rvalue references. We're going rogue with the above edits,
3477 // because the semantics in the current C++0x working paper (N3225 at the
3478 // time of this writing) break the standard definition of std::forward
3479 // and std::reference_wrapper when dealing with references to functions.
3480 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003481 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3482 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3483 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484
Douglas Gregore696ebb2011-01-26 14:52:12 +00003485 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3486 SCS2.IsLvalueReference) ||
3487 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3488 !SCS2.IsLvalueReference);
3489}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003490
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003491/// CompareStandardConversionSequences - Compare two standard
3492/// conversion sequences to determine whether one is better than the
3493/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003494static ImplicitConversionSequence::CompareKind
3495CompareStandardConversionSequences(Sema &S,
3496 const StandardConversionSequence& SCS1,
3497 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003498{
3499 // Standard conversion sequence S1 is a better conversion sequence
3500 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3501
3502 // -- S1 is a proper subsequence of S2 (comparing the conversion
3503 // sequences in the canonical form defined by 13.3.3.1.1,
3504 // excluding any Lvalue Transformation; the identity conversion
3505 // sequence is considered to be a subsequence of any
3506 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003507 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003508 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003509 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003510
3511 // -- the rank of S1 is better than the rank of S2 (by the rules
3512 // defined below), or, if not that,
3513 ImplicitConversionRank Rank1 = SCS1.getRank();
3514 ImplicitConversionRank Rank2 = SCS2.getRank();
3515 if (Rank1 < Rank2)
3516 return ImplicitConversionSequence::Better;
3517 else if (Rank2 < Rank1)
3518 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003519
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003520 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3521 // are indistinguishable unless one of the following rules
3522 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003523
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003524 // A conversion that is not a conversion of a pointer, or
3525 // pointer to member, to bool is better than another conversion
3526 // that is such a conversion.
3527 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3528 return SCS2.isPointerConversionToBool()
3529 ? ImplicitConversionSequence::Better
3530 : ImplicitConversionSequence::Worse;
3531
Douglas Gregor5c407d92008-10-23 00:40:37 +00003532 // C++ [over.ics.rank]p4b2:
3533 //
3534 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003535 // conversion of B* to A* is better than conversion of B* to
3536 // void*, and conversion of A* to void* is better than conversion
3537 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003538 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003539 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003540 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003541 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003542 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3543 // Exactly one of the conversion sequences is a conversion to
3544 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003545 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3546 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003547 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3548 // Neither conversion sequence converts to a void pointer; compare
3549 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003550 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003551 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003552 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003553 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3554 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003555 // Both conversion sequences are conversions to void
3556 // pointers. Compare the source types to determine if there's an
3557 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003558 QualType FromType1 = SCS1.getFromType();
3559 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003560
3561 // Adjust the types we're converting from via the array-to-pointer
3562 // conversion, if we need to.
3563 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003564 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003565 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003566 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003567
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003568 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3569 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003570
John McCall5c32be02010-08-24 20:38:10 +00003571 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003572 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003573 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003574 return ImplicitConversionSequence::Worse;
3575
3576 // Objective-C++: If one interface is more specific than the
3577 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003578 const ObjCObjectPointerType* FromObjCPtr1
3579 = FromType1->getAs<ObjCObjectPointerType>();
3580 const ObjCObjectPointerType* FromObjCPtr2
3581 = FromType2->getAs<ObjCObjectPointerType>();
3582 if (FromObjCPtr1 && FromObjCPtr2) {
3583 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3584 FromObjCPtr2);
3585 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3586 FromObjCPtr1);
3587 if (AssignLeft != AssignRight) {
3588 return AssignLeft? ImplicitConversionSequence::Better
3589 : ImplicitConversionSequence::Worse;
3590 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003591 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003592 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003593
3594 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3595 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003596 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003597 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003598 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003599
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003600 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003601 // Check for a better reference binding based on the kind of bindings.
3602 if (isBetterReferenceBindingKind(SCS1, SCS2))
3603 return ImplicitConversionSequence::Better;
3604 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3605 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003606
Sebastian Redlb28b4072009-03-22 23:49:27 +00003607 // C++ [over.ics.rank]p3b4:
3608 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3609 // which the references refer are the same type except for
3610 // top-level cv-qualifiers, and the type to which the reference
3611 // initialized by S2 refers is more cv-qualified than the type
3612 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003613 QualType T1 = SCS1.getToType(2);
3614 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003615 T1 = S.Context.getCanonicalType(T1);
3616 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003617 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003618 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3619 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003620 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003621 // Objective-C++ ARC: If the references refer to objects with different
3622 // lifetimes, prefer bindings that don't change lifetime.
3623 if (SCS1.ObjCLifetimeConversionBinding !=
3624 SCS2.ObjCLifetimeConversionBinding) {
3625 return SCS1.ObjCLifetimeConversionBinding
3626 ? ImplicitConversionSequence::Worse
3627 : ImplicitConversionSequence::Better;
3628 }
3629
Chandler Carruth8e543b32010-12-12 08:17:55 +00003630 // If the type is an array type, promote the element qualifiers to the
3631 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003632 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003633 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003634 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003635 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003636 if (T2.isMoreQualifiedThan(T1))
3637 return ImplicitConversionSequence::Better;
3638 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003639 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003640 }
3641 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003642
Francois Pichet08d2fa02011-09-18 21:37:37 +00003643 // In Microsoft mode, prefer an integral conversion to a
3644 // floating-to-integral conversion if the integral conversion
3645 // is between types of the same size.
3646 // For example:
3647 // void f(float);
3648 // void f(int);
3649 // int main {
3650 // long a;
3651 // f(a);
3652 // }
3653 // Here, MSVC will call f(int) instead of generating a compile error
3654 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003655 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3656 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003657 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003658 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003659 return ImplicitConversionSequence::Better;
3660
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003661 return ImplicitConversionSequence::Indistinguishable;
3662}
3663
3664/// CompareQualificationConversions - Compares two standard conversion
3665/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003666/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3667ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003668CompareQualificationConversions(Sema &S,
3669 const StandardConversionSequence& SCS1,
3670 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003671 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003672 // -- S1 and S2 differ only in their qualification conversion and
3673 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3674 // cv-qualification signature of type T1 is a proper subset of
3675 // the cv-qualification signature of type T2, and S1 is not the
3676 // deprecated string literal array-to-pointer conversion (4.2).
3677 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3678 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3679 return ImplicitConversionSequence::Indistinguishable;
3680
3681 // FIXME: the example in the standard doesn't use a qualification
3682 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003683 QualType T1 = SCS1.getToType(2);
3684 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003685 T1 = S.Context.getCanonicalType(T1);
3686 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003687 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003688 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3689 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003690
3691 // If the types are the same, we won't learn anything by unwrapped
3692 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003693 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003694 return ImplicitConversionSequence::Indistinguishable;
3695
Chandler Carruth607f38e2009-12-29 07:16:59 +00003696 // If the type is an array type, promote the element qualifiers to the type
3697 // for comparison.
3698 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003699 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003700 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003701 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003702
Mike Stump11289f42009-09-09 15:08:12 +00003703 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003704 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003705
3706 // Objective-C++ ARC:
3707 // Prefer qualification conversions not involving a change in lifetime
3708 // to qualification conversions that do not change lifetime.
3709 if (SCS1.QualificationIncludesObjCLifetime !=
3710 SCS2.QualificationIncludesObjCLifetime) {
3711 Result = SCS1.QualificationIncludesObjCLifetime
3712 ? ImplicitConversionSequence::Worse
3713 : ImplicitConversionSequence::Better;
3714 }
3715
John McCall5c32be02010-08-24 20:38:10 +00003716 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003717 // Within each iteration of the loop, we check the qualifiers to
3718 // determine if this still looks like a qualification
3719 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003720 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003721 // until there are no more pointers or pointers-to-members left
3722 // to unwrap. This essentially mimics what
3723 // IsQualificationConversion does, but here we're checking for a
3724 // strict subset of qualifiers.
3725 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3726 // The qualifiers are the same, so this doesn't tell us anything
3727 // about how the sequences rank.
3728 ;
3729 else if (T2.isMoreQualifiedThan(T1)) {
3730 // T1 has fewer qualifiers, so it could be the better sequence.
3731 if (Result == ImplicitConversionSequence::Worse)
3732 // Neither has qualifiers that are a subset of the other's
3733 // qualifiers.
3734 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003735
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003736 Result = ImplicitConversionSequence::Better;
3737 } else if (T1.isMoreQualifiedThan(T2)) {
3738 // T2 has fewer qualifiers, so it could be the better sequence.
3739 if (Result == ImplicitConversionSequence::Better)
3740 // Neither has qualifiers that are a subset of the other's
3741 // qualifiers.
3742 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003743
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003744 Result = ImplicitConversionSequence::Worse;
3745 } else {
3746 // Qualifiers are disjoint.
3747 return ImplicitConversionSequence::Indistinguishable;
3748 }
3749
3750 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003751 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003752 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003753 }
3754
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003755 // Check that the winning standard conversion sequence isn't using
3756 // the deprecated string literal array to pointer conversion.
3757 switch (Result) {
3758 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003759 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003760 Result = ImplicitConversionSequence::Indistinguishable;
3761 break;
3762
3763 case ImplicitConversionSequence::Indistinguishable:
3764 break;
3765
3766 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003767 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003768 Result = ImplicitConversionSequence::Indistinguishable;
3769 break;
3770 }
3771
3772 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003773}
3774
Douglas Gregor5c407d92008-10-23 00:40:37 +00003775/// CompareDerivedToBaseConversions - Compares two standard conversion
3776/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003777/// various kinds of derived-to-base conversions (C++
3778/// [over.ics.rank]p4b3). As part of these checks, we also look at
3779/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003780ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003781CompareDerivedToBaseConversions(Sema &S,
3782 const StandardConversionSequence& SCS1,
3783 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003784 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003785 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003786 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003787 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003788
3789 // Adjust the types we're converting from via the array-to-pointer
3790 // conversion, if we need to.
3791 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003792 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003793 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003794 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003795
3796 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003797 FromType1 = S.Context.getCanonicalType(FromType1);
3798 ToType1 = S.Context.getCanonicalType(ToType1);
3799 FromType2 = S.Context.getCanonicalType(FromType2);
3800 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003801
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003802 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003803 //
3804 // If class B is derived directly or indirectly from class A and
3805 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003806 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003807 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003808 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003809 SCS2.Second == ICK_Pointer_Conversion &&
3810 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3811 FromType1->isPointerType() && FromType2->isPointerType() &&
3812 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003813 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003814 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003815 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003816 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003817 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003818 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003819 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003820 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003821
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003822 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003823 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003824 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003825 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003826 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003827 return ImplicitConversionSequence::Worse;
3828 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003829
3830 // -- conversion of B* to A* is better than conversion of C* to A*,
3831 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003832 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003833 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003834 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003835 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003836 }
3837 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3838 SCS2.Second == ICK_Pointer_Conversion) {
3839 const ObjCObjectPointerType *FromPtr1
3840 = FromType1->getAs<ObjCObjectPointerType>();
3841 const ObjCObjectPointerType *FromPtr2
3842 = FromType2->getAs<ObjCObjectPointerType>();
3843 const ObjCObjectPointerType *ToPtr1
3844 = ToType1->getAs<ObjCObjectPointerType>();
3845 const ObjCObjectPointerType *ToPtr2
3846 = ToType2->getAs<ObjCObjectPointerType>();
3847
3848 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3849 // Apply the same conversion ranking rules for Objective-C pointer types
3850 // that we do for C++ pointers to class types. However, we employ the
3851 // Objective-C pseudo-subtyping relationship used for assignment of
3852 // Objective-C pointer types.
3853 bool FromAssignLeft
3854 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3855 bool FromAssignRight
3856 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3857 bool ToAssignLeft
3858 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3859 bool ToAssignRight
3860 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3861
3862 // A conversion to an a non-id object pointer type or qualified 'id'
3863 // type is better than a conversion to 'id'.
3864 if (ToPtr1->isObjCIdType() &&
3865 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3866 return ImplicitConversionSequence::Worse;
3867 if (ToPtr2->isObjCIdType() &&
3868 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3869 return ImplicitConversionSequence::Better;
3870
3871 // A conversion to a non-id object pointer type is better than a
3872 // conversion to a qualified 'id' type
3873 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3874 return ImplicitConversionSequence::Worse;
3875 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3876 return ImplicitConversionSequence::Better;
3877
3878 // A conversion to an a non-Class object pointer type or qualified 'Class'
3879 // type is better than a conversion to 'Class'.
3880 if (ToPtr1->isObjCClassType() &&
3881 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3882 return ImplicitConversionSequence::Worse;
3883 if (ToPtr2->isObjCClassType() &&
3884 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3885 return ImplicitConversionSequence::Better;
3886
3887 // A conversion to a non-Class object pointer type is better than a
3888 // conversion to a qualified 'Class' type.
3889 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3890 return ImplicitConversionSequence::Worse;
3891 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3892 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003893
Douglas Gregor058d3de2011-01-31 18:51:41 +00003894 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3895 if (S.Context.hasSameType(FromType1, FromType2) &&
3896 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3897 (ToAssignLeft != ToAssignRight))
3898 return ToAssignLeft? ImplicitConversionSequence::Worse
3899 : ImplicitConversionSequence::Better;
3900
3901 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3902 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3903 (FromAssignLeft != FromAssignRight))
3904 return FromAssignLeft? ImplicitConversionSequence::Better
3905 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003906 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003907 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003908
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003909 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003910 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3911 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3912 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003913 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003914 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003915 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003916 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003917 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003918 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003920 ToType2->getAs<MemberPointerType>();
3921 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3922 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3923 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3924 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3925 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3926 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3927 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3928 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003929 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003930 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003931 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003932 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003933 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003934 return ImplicitConversionSequence::Better;
3935 }
3936 // conversion of B::* to C::* is better than conversion of A::* to C::*
3937 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003938 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003939 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003940 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003941 return ImplicitConversionSequence::Worse;
3942 }
3943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003944
Douglas Gregor5ab11652010-04-17 22:01:05 +00003945 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003946 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003947 // -- binding of an expression of type C to a reference of type
3948 // B& is better than binding an expression of type C to a
3949 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003950 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3951 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3952 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003953 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003954 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003955 return ImplicitConversionSequence::Worse;
3956 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003957
Douglas Gregor2fe98832008-11-03 19:09:14 +00003958 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003959 // -- binding of an expression of type B to a reference of type
3960 // A& is better than binding an expression of type C to a
3961 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003962 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3963 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3964 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003965 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003966 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003967 return ImplicitConversionSequence::Worse;
3968 }
3969 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003970
Douglas Gregor5c407d92008-10-23 00:40:37 +00003971 return ImplicitConversionSequence::Indistinguishable;
3972}
3973
Douglas Gregor45bb4832013-03-26 23:36:30 +00003974/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3975/// C++ class.
3976static bool isTypeValid(QualType T) {
3977 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3978 return !Record->isInvalidDecl();
3979
3980 return true;
3981}
3982
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003983/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3984/// determine whether they are reference-related,
3985/// reference-compatible, reference-compatible with added
3986/// qualification, or incompatible, for use in C++ initialization by
3987/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3988/// type, and the first type (T1) is the pointee type of the reference
3989/// type being initialized.
3990Sema::ReferenceCompareResult
3991Sema::CompareReferenceRelationship(SourceLocation Loc,
3992 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003993 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003994 bool &ObjCConversion,
3995 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003996 assert(!OrigT1->isReferenceType() &&
3997 "T1 must be the pointee type of the reference type");
3998 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3999
4000 QualType T1 = Context.getCanonicalType(OrigT1);
4001 QualType T2 = Context.getCanonicalType(OrigT2);
4002 Qualifiers T1Quals, T2Quals;
4003 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4004 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4005
4006 // C++ [dcl.init.ref]p4:
4007 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4008 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4009 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004010 DerivedToBase = false;
4011 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004012 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004013 if (UnqualT1 == UnqualT2) {
4014 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004015 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004016 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4017 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004018 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004019 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4020 UnqualT2->isObjCObjectOrInterfaceType() &&
4021 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4022 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004023 else
4024 return Ref_Incompatible;
4025
4026 // At this point, we know that T1 and T2 are reference-related (at
4027 // least).
4028
4029 // If the type is an array type, promote the element qualifiers to the type
4030 // for comparison.
4031 if (isa<ArrayType>(T1) && T1Quals)
4032 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4033 if (isa<ArrayType>(T2) && T2Quals)
4034 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4035
4036 // C++ [dcl.init.ref]p4:
4037 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4038 // reference-related to T2 and cv1 is the same cv-qualification
4039 // as, or greater cv-qualification than, cv2. For purposes of
4040 // overload resolution, cases for which cv1 is greater
4041 // cv-qualification than cv2 are identified as
4042 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004043 //
4044 // Note that we also require equivalence of Objective-C GC and address-space
4045 // qualifiers when performing these computations, so that e.g., an int in
4046 // address space 1 is not reference-compatible with an int in address
4047 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004048 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4049 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004050 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4051 ObjCLifetimeConversion = true;
4052
John McCall31168b02011-06-15 23:02:42 +00004053 T1Quals.removeObjCLifetime();
4054 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004055 }
4056
Douglas Gregord517d552011-04-28 17:56:11 +00004057 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004058 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004059 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004060 return Ref_Compatible_With_Added_Qualification;
4061 else
4062 return Ref_Related;
4063}
4064
Douglas Gregor836a7e82010-08-11 02:15:33 +00004065/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004066/// with DeclType. Return true if something definite is found.
4067static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004068FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4069 QualType DeclType, SourceLocation DeclLoc,
4070 Expr *Init, QualType T2, bool AllowRvalues,
4071 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004072 assert(T2->isRecordType() && "Can only find conversions of record types.");
4073 CXXRecordDecl *T2RecordDecl
4074 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4075
4076 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004077 std::pair<CXXRecordDecl::conversion_iterator,
4078 CXXRecordDecl::conversion_iterator>
4079 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4080 for (CXXRecordDecl::conversion_iterator
4081 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004082 NamedDecl *D = *I;
4083 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4084 if (isa<UsingShadowDecl>(D))
4085 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4086
4087 FunctionTemplateDecl *ConvTemplate
4088 = dyn_cast<FunctionTemplateDecl>(D);
4089 CXXConversionDecl *Conv;
4090 if (ConvTemplate)
4091 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4092 else
4093 Conv = cast<CXXConversionDecl>(D);
4094
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004096 // explicit conversions, skip it.
4097 if (!AllowExplicit && Conv->isExplicit())
4098 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099
Douglas Gregor836a7e82010-08-11 02:15:33 +00004100 if (AllowRvalues) {
4101 bool DerivedToBase = false;
4102 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004103 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004104
4105 // If we are initializing an rvalue reference, don't permit conversion
4106 // functions that return lvalues.
4107 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4108 const ReferenceType *RefType
4109 = Conv->getConversionType()->getAs<LValueReferenceType>();
4110 if (RefType && !RefType->getPointeeType()->isFunctionType())
4111 continue;
4112 }
4113
Douglas Gregor836a7e82010-08-11 02:15:33 +00004114 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004115 S.CompareReferenceRelationship(
4116 DeclLoc,
4117 Conv->getConversionType().getNonReferenceType()
4118 .getUnqualifiedType(),
4119 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004120 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004121 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004122 continue;
4123 } else {
4124 // If the conversion function doesn't return a reference type,
4125 // it can't be considered for this conversion. An rvalue reference
4126 // is only acceptable if its referencee is a function type.
4127
4128 const ReferenceType *RefType =
4129 Conv->getConversionType()->getAs<ReferenceType>();
4130 if (!RefType ||
4131 (!RefType->isLValueReferenceType() &&
4132 !RefType->getPointeeType()->isFunctionType()))
4133 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004134 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004135
Douglas Gregor836a7e82010-08-11 02:15:33 +00004136 if (ConvTemplate)
4137 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004138 Init, DeclType, CandidateSet,
4139 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004140 else
4141 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004142 DeclType, CandidateSet,
4143 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004144 }
4145
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004146 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4147
Sebastian Redld92badf2010-06-30 18:13:39 +00004148 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004149 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004150 case OR_Success:
4151 // C++ [over.ics.ref]p1:
4152 //
4153 // [...] If the parameter binds directly to the result of
4154 // applying a conversion function to the argument
4155 // expression, the implicit conversion sequence is a
4156 // user-defined conversion sequence (13.3.3.1.2), with the
4157 // second standard conversion sequence either an identity
4158 // conversion or, if the conversion function returns an
4159 // entity of a type that is a derived class of the parameter
4160 // type, a derived-to-base Conversion.
4161 if (!Best->FinalConversion.DirectBinding)
4162 return false;
4163
4164 ICS.setUserDefined();
4165 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4166 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004167 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004168 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004169 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004170 ICS.UserDefined.EllipsisConversion = false;
4171 assert(ICS.UserDefined.After.ReferenceBinding &&
4172 ICS.UserDefined.After.DirectBinding &&
4173 "Expected a direct reference binding!");
4174 return true;
4175
4176 case OR_Ambiguous:
4177 ICS.setAmbiguous();
4178 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4179 Cand != CandidateSet.end(); ++Cand)
4180 if (Cand->Viable)
4181 ICS.Ambiguous.addConversion(Cand->Function);
4182 return true;
4183
4184 case OR_No_Viable_Function:
4185 case OR_Deleted:
4186 // There was no suitable conversion, or we found a deleted
4187 // conversion; continue with other checks.
4188 return false;
4189 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004190
David Blaikie8a40f702012-01-17 06:56:22 +00004191 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004192}
4193
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004194/// \brief Compute an implicit conversion sequence for reference
4195/// initialization.
4196static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004197TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004198 SourceLocation DeclLoc,
4199 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004200 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004201 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4202
4203 // Most paths end in a failed conversion.
4204 ImplicitConversionSequence ICS;
4205 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4206
4207 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4208 QualType T2 = Init->getType();
4209
4210 // If the initializer is the address of an overloaded function, try
4211 // to resolve the overloaded function. If all goes well, T2 is the
4212 // type of the resulting function.
4213 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4214 DeclAccessPair Found;
4215 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4216 false, Found))
4217 T2 = Fn->getType();
4218 }
4219
4220 // Compute some basic properties of the types and the initializer.
4221 bool isRValRef = DeclType->isRValueReferenceType();
4222 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004223 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004224 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004225 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004226 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004227 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004228 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004229
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004230
Sebastian Redld92badf2010-06-30 18:13:39 +00004231 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004232 // A reference to type "cv1 T1" is initialized by an expression
4233 // of type "cv2 T2" as follows:
4234
Sebastian Redld92badf2010-06-30 18:13:39 +00004235 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004236 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004237 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4238 // reference-compatible with "cv2 T2," or
4239 //
4240 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4241 if (InitCategory.isLValue() &&
4242 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004243 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004244 // When a parameter of reference type binds directly (8.5.3)
4245 // to an argument expression, the implicit conversion sequence
4246 // is the identity conversion, unless the argument expression
4247 // has a type that is a derived class of the parameter type,
4248 // in which case the implicit conversion sequence is a
4249 // derived-to-base Conversion (13.3.3.1).
4250 ICS.setStandard();
4251 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004252 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4253 : ObjCConversion? ICK_Compatible_Conversion
4254 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004255 ICS.Standard.Third = ICK_Identity;
4256 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4257 ICS.Standard.setToType(0, T2);
4258 ICS.Standard.setToType(1, T1);
4259 ICS.Standard.setToType(2, T1);
4260 ICS.Standard.ReferenceBinding = true;
4261 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004262 ICS.Standard.IsLvalueReference = !isRValRef;
4263 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4264 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004265 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004266 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004267 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004268 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004269
Sebastian Redld92badf2010-06-30 18:13:39 +00004270 // Nothing more to do: the inaccessibility/ambiguity check for
4271 // derived-to-base conversions is suppressed when we're
4272 // computing the implicit conversion sequence (C++
4273 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004274 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004275 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004276
Sebastian Redld92badf2010-06-30 18:13:39 +00004277 // -- has a class type (i.e., T2 is a class type), where T1 is
4278 // not reference-related to T2, and can be implicitly
4279 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4280 // is reference-compatible with "cv3 T3" 92) (this
4281 // conversion is selected by enumerating the applicable
4282 // conversion functions (13.3.1.6) and choosing the best
4283 // one through overload resolution (13.3)),
4284 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004286 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004287 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4288 Init, T2, /*AllowRvalues=*/false,
4289 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004290 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004291 }
4292 }
4293
Sebastian Redld92badf2010-06-30 18:13:39 +00004294 // -- Otherwise, the reference shall be an lvalue reference to a
4295 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004296 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004297 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004298 // We actually handle one oddity of C++ [over.ics.ref] at this
4299 // point, which is that, due to p2 (which short-circuits reference
4300 // binding by only attempting a simple conversion for non-direct
4301 // bindings) and p3's strange wording, we allow a const volatile
4302 // reference to bind to an rvalue. Hence the check for the presence
4303 // of "const" rather than checking for "const" being the only
4304 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004305 // This is also the point where rvalue references and lvalue inits no longer
4306 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004307 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004308 return ICS;
4309
Douglas Gregorf143cd52011-01-24 16:14:37 +00004310 // -- If the initializer expression
4311 //
4312 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004313 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004314 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4315 (InitCategory.isXValue() ||
4316 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4317 (InitCategory.isLValue() && T2->isFunctionType()))) {
4318 ICS.setStandard();
4319 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004321 : ObjCConversion? ICK_Compatible_Conversion
4322 : ICK_Identity;
4323 ICS.Standard.Third = ICK_Identity;
4324 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4325 ICS.Standard.setToType(0, T2);
4326 ICS.Standard.setToType(1, T1);
4327 ICS.Standard.setToType(2, T1);
4328 ICS.Standard.ReferenceBinding = true;
4329 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4330 // binding unless we're binding to a class prvalue.
4331 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4332 // allow the use of rvalue references in C++98/03 for the benefit of
4333 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004335 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004336 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004337 ICS.Standard.IsLvalueReference = !isRValRef;
4338 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004339 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004340 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004341 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004342 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004343 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346
Douglas Gregorf143cd52011-01-24 16:14:37 +00004347 // -- has a class type (i.e., T2 is a class type), where T1 is not
4348 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004349 // an xvalue, class prvalue, or function lvalue of type
4350 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004351 // "cv3 T3",
4352 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004354 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004355 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004356 // class subobject).
4357 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004358 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004359 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4360 Init, T2, /*AllowRvalues=*/true,
4361 AllowExplicit)) {
4362 // In the second case, if the reference is an rvalue reference
4363 // and the second standard conversion sequence of the
4364 // user-defined conversion sequence includes an lvalue-to-rvalue
4365 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004367 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4368 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4369
Douglas Gregor95273c32011-01-21 16:36:05 +00004370 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004372
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004373 // -- Otherwise, a temporary of type "cv1 T1" is created and
4374 // initialized from the initializer expression using the
4375 // rules for a non-reference copy initialization (8.5). The
4376 // reference is then bound to the temporary. If T1 is
4377 // reference-related to T2, cv1 must be the same
4378 // cv-qualification as, or greater cv-qualification than,
4379 // cv2; otherwise, the program is ill-formed.
4380 if (RefRelationship == Sema::Ref_Related) {
4381 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4382 // we would be reference-compatible or reference-compatible with
4383 // added qualification. But that wasn't the case, so the reference
4384 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004385 //
4386 // Note that we only want to check address spaces and cvr-qualifiers here.
4387 // ObjC GC and lifetime qualifiers aren't important.
4388 Qualifiers T1Quals = T1.getQualifiers();
4389 Qualifiers T2Quals = T2.getQualifiers();
4390 T1Quals.removeObjCGCAttr();
4391 T1Quals.removeObjCLifetime();
4392 T2Quals.removeObjCGCAttr();
4393 T2Quals.removeObjCLifetime();
4394 if (!T1Quals.compatiblyIncludes(T2Quals))
4395 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004396 }
4397
4398 // If at least one of the types is a class type, the types are not
4399 // related, and we aren't allowed any user conversions, the
4400 // reference binding fails. This case is important for breaking
4401 // recursion, since TryImplicitConversion below will attempt to
4402 // create a temporary through the use of a copy constructor.
4403 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4404 (T1->isRecordType() || T2->isRecordType()))
4405 return ICS;
4406
Douglas Gregorcba72b12011-01-21 05:18:22 +00004407 // If T1 is reference-related to T2 and the reference is an rvalue
4408 // reference, the initializer expression shall not be an lvalue.
4409 if (RefRelationship >= Sema::Ref_Related &&
4410 isRValRef && Init->Classify(S.Context).isLValue())
4411 return ICS;
4412
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004413 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004414 // When a parameter of reference type is not bound directly to
4415 // an argument expression, the conversion sequence is the one
4416 // required to convert the argument expression to the
4417 // underlying type of the reference according to
4418 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4419 // to copy-initializing a temporary of the underlying type with
4420 // the argument expression. Any difference in top-level
4421 // cv-qualification is subsumed by the initialization itself
4422 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004423 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4424 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004425 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004426 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004427 /*AllowObjCWritebackConversion=*/false,
4428 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004429
4430 // Of course, that's still a reference binding.
4431 if (ICS.isStandard()) {
4432 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004433 ICS.Standard.IsLvalueReference = !isRValRef;
4434 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4435 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004436 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004437 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004438 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004439 // Don't allow rvalue references to bind to lvalues.
4440 if (DeclType->isRValueReferenceType()) {
4441 if (const ReferenceType *RefType
4442 = ICS.UserDefined.ConversionFunction->getResultType()
4443 ->getAs<LValueReferenceType>()) {
4444 if (!RefType->getPointeeType()->isFunctionType()) {
4445 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4446 DeclType);
4447 return ICS;
4448 }
4449 }
4450 }
Ismail Pazarbasi99afd962014-01-24 10:54:12 +00004451 ICS.UserDefined.Before.setAsIdentityConversion();
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004452 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004453 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4454 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4455 ICS.UserDefined.After.BindsToRvalue = true;
4456 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4457 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004458 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004459
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004460 return ICS;
4461}
4462
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004463static ImplicitConversionSequence
4464TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4465 bool SuppressUserConversions,
4466 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004467 bool AllowObjCWritebackConversion,
4468 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004469
4470/// TryListConversion - Try to copy-initialize a value of type ToType from the
4471/// initializer list From.
4472static ImplicitConversionSequence
4473TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4474 bool SuppressUserConversions,
4475 bool InOverloadResolution,
4476 bool AllowObjCWritebackConversion) {
4477 // C++11 [over.ics.list]p1:
4478 // When an argument is an initializer list, it is not an expression and
4479 // special rules apply for converting it to a parameter type.
4480
4481 ImplicitConversionSequence Result;
4482 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4483
Sebastian Redl09edce02012-01-23 22:09:39 +00004484 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004485 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004486 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004487 return Result;
4488
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004489 // C++11 [over.ics.list]p2:
4490 // If the parameter type is std::initializer_list<X> or "array of X" and
4491 // all the elements can be implicitly converted to X, the implicit
4492 // conversion sequence is the worst conversion necessary to convert an
4493 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004494 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004495 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004496 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004497 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004498 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004499 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004500 if (!X.isNull()) {
4501 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4502 Expr *Init = From->getInit(i);
4503 ImplicitConversionSequence ICS =
4504 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4505 InOverloadResolution,
4506 AllowObjCWritebackConversion);
4507 // If a single element isn't convertible, fail.
4508 if (ICS.isBad()) {
4509 Result = ICS;
4510 break;
4511 }
4512 // Otherwise, look for the worst conversion.
4513 if (Result.isBad() ||
4514 CompareImplicitConversionSequences(S, ICS, Result) ==
4515 ImplicitConversionSequence::Worse)
4516 Result = ICS;
4517 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004518
4519 // For an empty list, we won't have computed any conversion sequence.
4520 // Introduce the identity conversion sequence.
4521 if (From->getNumInits() == 0) {
4522 Result.setStandard();
4523 Result.Standard.setAsIdentityConversion();
4524 Result.Standard.setFromType(ToType);
4525 Result.Standard.setAllToTypes(ToType);
4526 }
4527
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004528 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004529 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004530 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004531
4532 // C++11 [over.ics.list]p3:
4533 // Otherwise, if the parameter is a non-aggregate class X and overload
4534 // resolution chooses a single best constructor [...] the implicit
4535 // conversion sequence is a user-defined conversion sequence. If multiple
4536 // constructors are viable but none is better than the others, the
4537 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004538 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4539 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004540 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4541 /*AllowExplicit=*/false,
4542 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004543 AllowObjCWritebackConversion,
4544 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004545 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004546
4547 // C++11 [over.ics.list]p4:
4548 // Otherwise, if the parameter has an aggregate type which can be
4549 // initialized from the initializer list [...] the implicit conversion
4550 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004551 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004552 // Type is an aggregate, argument is an init list. At this point it comes
4553 // down to checking whether the initialization works.
4554 // FIXME: Find out whether this parameter is consumed or not.
4555 InitializedEntity Entity =
4556 InitializedEntity::InitializeParameter(S.Context, ToType,
4557 /*Consumed=*/false);
4558 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4559 Result.setUserDefined();
4560 Result.UserDefined.Before.setAsIdentityConversion();
4561 // Initializer lists don't have a type.
4562 Result.UserDefined.Before.setFromType(QualType());
4563 Result.UserDefined.Before.setAllToTypes(QualType());
4564
4565 Result.UserDefined.After.setAsIdentityConversion();
4566 Result.UserDefined.After.setFromType(ToType);
4567 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004568 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004569 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004570 return Result;
4571 }
4572
4573 // C++11 [over.ics.list]p5:
4574 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004575 if (ToType->isReferenceType()) {
4576 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4577 // mention initializer lists in any way. So we go by what list-
4578 // initialization would do and try to extrapolate from that.
4579
4580 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4581
4582 // If the initializer list has a single element that is reference-related
4583 // to the parameter type, we initialize the reference from that.
4584 if (From->getNumInits() == 1) {
4585 Expr *Init = From->getInit(0);
4586
4587 QualType T2 = Init->getType();
4588
4589 // If the initializer is the address of an overloaded function, try
4590 // to resolve the overloaded function. If all goes well, T2 is the
4591 // type of the resulting function.
4592 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4593 DeclAccessPair Found;
4594 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4595 Init, ToType, false, Found))
4596 T2 = Fn->getType();
4597 }
4598
4599 // Compute some basic properties of the types and the initializer.
4600 bool dummy1 = false;
4601 bool dummy2 = false;
4602 bool dummy3 = false;
4603 Sema::ReferenceCompareResult RefRelationship
4604 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4605 dummy2, dummy3);
4606
Richard Smith4d2bbd72013-09-06 01:22:42 +00004607 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004608 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4609 SuppressUserConversions,
4610 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004611 }
Sebastian Redldf888642011-12-03 14:54:30 +00004612 }
4613
4614 // Otherwise, we bind the reference to a temporary created from the
4615 // initializer list.
4616 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4617 InOverloadResolution,
4618 AllowObjCWritebackConversion);
4619 if (Result.isFailure())
4620 return Result;
4621 assert(!Result.isEllipsis() &&
4622 "Sub-initialization cannot result in ellipsis conversion.");
4623
4624 // Can we even bind to a temporary?
4625 if (ToType->isRValueReferenceType() ||
4626 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4627 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4628 Result.UserDefined.After;
4629 SCS.ReferenceBinding = true;
4630 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4631 SCS.BindsToRvalue = true;
4632 SCS.BindsToFunctionLvalue = false;
4633 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4634 SCS.ObjCLifetimeConversionBinding = false;
4635 } else
4636 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4637 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004638 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004639 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004640
4641 // C++11 [over.ics.list]p6:
4642 // Otherwise, if the parameter type is not a class:
4643 if (!ToType->isRecordType()) {
4644 // - if the initializer list has one element, the implicit conversion
4645 // sequence is the one required to convert the element to the
4646 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004647 unsigned NumInits = From->getNumInits();
4648 if (NumInits == 1)
4649 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4650 SuppressUserConversions,
4651 InOverloadResolution,
4652 AllowObjCWritebackConversion);
4653 // - if the initializer list has no elements, the implicit conversion
4654 // sequence is the identity conversion.
4655 else if (NumInits == 0) {
4656 Result.setStandard();
4657 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004658 Result.Standard.setFromType(ToType);
4659 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004660 }
4661 return Result;
4662 }
4663
4664 // C++11 [over.ics.list]p7:
4665 // In all cases other than those enumerated above, no conversion is possible
4666 return Result;
4667}
4668
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004669/// TryCopyInitialization - Try to copy-initialize a value of type
4670/// ToType from the expression From. Return the implicit conversion
4671/// sequence required to pass this argument, which may be a bad
4672/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004673/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004674/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004675static ImplicitConversionSequence
4676TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004678 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004679 bool AllowObjCWritebackConversion,
4680 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004681 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4682 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4683 InOverloadResolution,AllowObjCWritebackConversion);
4684
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004685 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004686 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004687 /*FIXME:*/From->getLocStart(),
4688 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004689 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004690
John McCall5c32be02010-08-24 20:38:10 +00004691 return TryImplicitConversion(S, From, ToType,
4692 SuppressUserConversions,
4693 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004694 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004695 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004696 AllowObjCWritebackConversion,
4697 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004698}
4699
Anna Zaks1b068122011-07-28 19:46:48 +00004700static bool TryCopyInitialization(const CanQualType FromQTy,
4701 const CanQualType ToQTy,
4702 Sema &S,
4703 SourceLocation Loc,
4704 ExprValueKind FromVK) {
4705 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4706 ImplicitConversionSequence ICS =
4707 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4708
4709 return !ICS.isBad();
4710}
4711
Douglas Gregor436424c2008-11-18 23:14:02 +00004712/// TryObjectArgumentInitialization - Try to initialize the object
4713/// parameter of the given member function (@c Method) from the
4714/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004715static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004716TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004717 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004718 CXXMethodDecl *Method,
4719 CXXRecordDecl *ActingContext) {
4720 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004721 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4722 // const volatile object.
4723 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4724 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004725 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004726
4727 // Set up the conversion sequence as a "bad" conversion, to allow us
4728 // to exit early.
4729 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004730
4731 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004732 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004733 FromType = PT->getPointeeType();
4734
Douglas Gregor02824322011-01-26 19:30:28 +00004735 // When we had a pointer, it's implicitly dereferenced, so we
4736 // better have an lvalue.
4737 assert(FromClassification.isLValue());
4738 }
4739
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004740 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004741
Douglas Gregor02824322011-01-26 19:30:28 +00004742 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004743 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004744 // parameter is
4745 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004746 // - "lvalue reference to cv X" for functions declared without a
4747 // ref-qualifier or with the & ref-qualifier
4748 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004749 // ref-qualifier
4750 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004751 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004752 // cv-qualification on the member function declaration.
4753 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004754 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004755 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004756 // (C++ [over.match.funcs]p5). We perform a simplified version of
4757 // reference binding here, that allows class rvalues to bind to
4758 // non-constant references.
4759
Douglas Gregor02824322011-01-26 19:30:28 +00004760 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004761 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004762 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004763 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004764 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004765 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004766 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004767 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004768 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004769
4770 // Check that we have either the same type or a derived type. It
4771 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004772 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004773 ImplicitConversionKind SecondKind;
4774 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4775 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004776 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004777 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004778 else {
John McCall65eb8792010-02-25 01:37:24 +00004779 ICS.setBad(BadConversionSequence::unrelated_class,
4780 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004781 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004782 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004783
Douglas Gregor02824322011-01-26 19:30:28 +00004784 // Check the ref-qualifier.
4785 switch (Method->getRefQualifier()) {
4786 case RQ_None:
4787 // Do nothing; we don't care about lvalueness or rvalueness.
4788 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004789
Douglas Gregor02824322011-01-26 19:30:28 +00004790 case RQ_LValue:
4791 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4792 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004793 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004794 ImplicitParamType);
4795 return ICS;
4796 }
4797 break;
4798
4799 case RQ_RValue:
4800 if (!FromClassification.isRValue()) {
4801 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004803 ImplicitParamType);
4804 return ICS;
4805 }
4806 break;
4807 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808
Douglas Gregor436424c2008-11-18 23:14:02 +00004809 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004810 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004811 ICS.Standard.setAsIdentityConversion();
4812 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004813 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004814 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004815 ICS.Standard.ReferenceBinding = true;
4816 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004817 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004818 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004819 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4820 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4821 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004822 return ICS;
4823}
4824
4825/// PerformObjectArgumentInitialization - Perform initialization of
4826/// the implicit object parameter for the given Method with the given
4827/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004828ExprResult
4829Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004830 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004831 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004832 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004833 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004834 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004835 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004836
Douglas Gregor02824322011-01-26 19:30:28 +00004837 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004838 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004839 FromRecordType = PT->getPointeeType();
4840 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004841 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004842 } else {
4843 FromRecordType = From->getType();
4844 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004845 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004846 }
4847
John McCall6e9f8f62009-12-03 04:06:58 +00004848 // Note that we always use the true parent context when performing
4849 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004850 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004851 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4852 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004853 if (ICS.isBad()) {
4854 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4855 Qualifiers FromQs = FromRecordType.getQualifiers();
4856 Qualifiers ToQs = DestType.getQualifiers();
4857 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4858 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004859 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004860 diag::err_member_function_call_bad_cvr)
4861 << Method->getDeclName() << FromRecordType << (CVR - 1)
4862 << From->getSourceRange();
4863 Diag(Method->getLocation(), diag::note_previous_decl)
4864 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004865 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004866 }
4867 }
4868
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004869 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004870 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004871 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004872 }
Mike Stump11289f42009-09-09 15:08:12 +00004873
John Wiegley01296292011-04-08 18:41:53 +00004874 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4875 ExprResult FromRes =
4876 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4877 if (FromRes.isInvalid())
4878 return ExprError();
4879 From = FromRes.take();
4880 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004881
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004882 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004883 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004884 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004885 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004886}
4887
Douglas Gregor5fb53972009-01-14 15:45:31 +00004888/// TryContextuallyConvertToBool - Attempt to contextually convert the
4889/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004890static ImplicitConversionSequence
4891TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004892 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004893 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004894 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004895 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004896 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004897 /*AllowObjCWritebackConversion=*/false,
4898 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004899}
4900
4901/// PerformContextuallyConvertToBool - Perform a contextual conversion
4902/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004903ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004904 if (checkPlaceholderForOverload(*this, From))
4905 return ExprError();
4906
John McCall5c32be02010-08-24 20:38:10 +00004907 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004908 if (!ICS.isBad())
4909 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004910
Fariborz Jahanian76197412009-11-18 18:26:29 +00004911 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004912 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004913 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004914 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004915 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004916}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Richard Smithf8379a02012-01-18 23:55:52 +00004918/// Check that the specified conversion is permitted in a converted constant
4919/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4920/// is acceptable.
4921static bool CheckConvertedConstantConversions(Sema &S,
4922 StandardConversionSequence &SCS) {
4923 // Since we know that the target type is an integral or unscoped enumeration
4924 // type, most conversion kinds are impossible. All possible First and Third
4925 // conversions are fine.
4926 switch (SCS.Second) {
4927 case ICK_Identity:
4928 case ICK_Integral_Promotion:
4929 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004930 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004931 return true;
4932
4933 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004934 // Conversion from an integral or unscoped enumeration type to bool is
4935 // classified as ICK_Boolean_Conversion, but it's also an integral
4936 // conversion, so it's permitted in a converted constant expression.
4937 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4938 SCS.getToType(2)->isBooleanType();
4939
Richard Smithf8379a02012-01-18 23:55:52 +00004940 case ICK_Floating_Integral:
4941 case ICK_Complex_Real:
4942 return false;
4943
4944 case ICK_Lvalue_To_Rvalue:
4945 case ICK_Array_To_Pointer:
4946 case ICK_Function_To_Pointer:
4947 case ICK_NoReturn_Adjustment:
4948 case ICK_Qualification:
4949 case ICK_Compatible_Conversion:
4950 case ICK_Vector_Conversion:
4951 case ICK_Vector_Splat:
4952 case ICK_Derived_To_Base:
4953 case ICK_Pointer_Conversion:
4954 case ICK_Pointer_Member:
4955 case ICK_Block_Pointer_Conversion:
4956 case ICK_Writeback_Conversion:
4957 case ICK_Floating_Promotion:
4958 case ICK_Complex_Promotion:
4959 case ICK_Complex_Conversion:
4960 case ICK_Floating_Conversion:
4961 case ICK_TransparentUnionConversion:
4962 llvm_unreachable("unexpected second conversion kind");
4963
4964 case ICK_Num_Conversion_Kinds:
4965 break;
4966 }
4967
4968 llvm_unreachable("unknown conversion kind");
4969}
4970
4971/// CheckConvertedConstantExpression - Check that the expression From is a
4972/// converted constant expression of type T, perform the conversion and produce
4973/// the converted expression, per C++11 [expr.const]p3.
4974ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4975 llvm::APSInt &Value,
4976 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004977 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004978 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4979
4980 if (checkPlaceholderForOverload(*this, From))
4981 return ExprError();
4982
4983 // C++11 [expr.const]p3 with proposed wording fixes:
4984 // A converted constant expression of type T is a core constant expression,
4985 // implicitly converted to a prvalue of type T, where the converted
4986 // expression is a literal constant expression and the implicit conversion
4987 // sequence contains only user-defined conversions, lvalue-to-rvalue
4988 // conversions, integral promotions, and integral conversions other than
4989 // narrowing conversions.
4990 ImplicitConversionSequence ICS =
4991 TryImplicitConversion(From, T,
4992 /*SuppressUserConversions=*/false,
4993 /*AllowExplicit=*/false,
4994 /*InOverloadResolution=*/false,
4995 /*CStyle=*/false,
4996 /*AllowObjcWritebackConversion=*/false);
4997 StandardConversionSequence *SCS = 0;
4998 switch (ICS.getKind()) {
4999 case ImplicitConversionSequence::StandardConversion:
5000 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005001 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005002 diag::err_typecheck_converted_constant_expression_disallowed)
5003 << From->getType() << From->getSourceRange() << T;
5004 SCS = &ICS.Standard;
5005 break;
5006 case ImplicitConversionSequence::UserDefinedConversion:
5007 // We are converting from class type to an integral or enumeration type, so
5008 // the Before sequence must be trivial.
5009 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
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.UserDefined.After;
5014 break;
5015 case ImplicitConversionSequence::AmbiguousConversion:
5016 case ImplicitConversionSequence::BadConversion:
5017 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005018 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005019 diag::err_typecheck_converted_constant_expression)
5020 << From->getType() << From->getSourceRange() << T;
5021 return ExprError();
5022
5023 case ImplicitConversionSequence::EllipsisConversion:
5024 llvm_unreachable("ellipsis conversion in converted constant expression");
5025 }
5026
5027 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5028 if (Result.isInvalid())
5029 return Result;
5030
5031 // Check for a narrowing implicit conversion.
5032 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005033 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005034 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5035 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005036 case NK_Variable_Narrowing:
5037 // Implicit conversion to a narrower type, and the value is not a constant
5038 // expression. We'll diagnose this in a moment.
5039 case NK_Not_Narrowing:
5040 break;
5041
5042 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005043 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005044 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005045 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005046 break;
5047
5048 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005049 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005050 << CCE << /*Constant*/0 << From->getType() << T;
5051 break;
5052 }
5053
5054 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005055 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005056 Expr::EvalResult Eval;
5057 Eval.Diag = &Notes;
5058
Douglas Gregorebe2db72013-04-08 23:24:07 +00005059 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005060 // The expression can't be folded, so we can't keep it at this position in
5061 // the AST.
5062 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005063 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005064 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005065
5066 if (Notes.empty()) {
5067 // It's a constant expression.
5068 return Result;
5069 }
Richard Smithf8379a02012-01-18 23:55:52 +00005070 }
5071
5072 // It's not a constant expression. Produce an appropriate diagnostic.
5073 if (Notes.size() == 1 &&
5074 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5075 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5076 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005077 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005078 << CCE << From->getSourceRange();
5079 for (unsigned I = 0; I < Notes.size(); ++I)
5080 Diag(Notes[I].first, Notes[I].second);
5081 }
Richard Smith911e1422012-01-30 22:27:01 +00005082 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005083}
5084
John McCallfec112d2011-09-09 06:11:02 +00005085/// dropPointerConversions - If the given standard conversion sequence
5086/// involves any pointer conversions, remove them. This may change
5087/// the result type of the conversion sequence.
5088static void dropPointerConversion(StandardConversionSequence &SCS) {
5089 if (SCS.Second == ICK_Pointer_Conversion) {
5090 SCS.Second = ICK_Identity;
5091 SCS.Third = ICK_Identity;
5092 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5093 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005094}
John McCall5c32be02010-08-24 20:38:10 +00005095
John McCallfec112d2011-09-09 06:11:02 +00005096/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5097/// convert the expression From to an Objective-C pointer type.
5098static ImplicitConversionSequence
5099TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5100 // Do an implicit conversion to 'id'.
5101 QualType Ty = S.Context.getObjCIdType();
5102 ImplicitConversionSequence ICS
5103 = TryImplicitConversion(S, From, Ty,
5104 // FIXME: Are these flags correct?
5105 /*SuppressUserConversions=*/false,
5106 /*AllowExplicit=*/true,
5107 /*InOverloadResolution=*/false,
5108 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005109 /*AllowObjCWritebackConversion=*/false,
5110 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005111
5112 // Strip off any final conversions to 'id'.
5113 switch (ICS.getKind()) {
5114 case ImplicitConversionSequence::BadConversion:
5115 case ImplicitConversionSequence::AmbiguousConversion:
5116 case ImplicitConversionSequence::EllipsisConversion:
5117 break;
5118
5119 case ImplicitConversionSequence::UserDefinedConversion:
5120 dropPointerConversion(ICS.UserDefined.After);
5121 break;
5122
5123 case ImplicitConversionSequence::StandardConversion:
5124 dropPointerConversion(ICS.Standard);
5125 break;
5126 }
5127
5128 return ICS;
5129}
5130
5131/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5132/// conversion of the expression From to an Objective-C pointer type.
5133ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005134 if (checkPlaceholderForOverload(*this, From))
5135 return ExprError();
5136
John McCall8b07ec22010-05-15 11:32:37 +00005137 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005138 ImplicitConversionSequence ICS =
5139 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005140 if (!ICS.isBad())
5141 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005142 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005143}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005144
Richard Smith8dd34252012-02-04 07:07:42 +00005145/// Determine whether the provided type is an integral type, or an enumeration
5146/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005147bool Sema::ICEConvertDiagnoser::match(QualType T) {
5148 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5149 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005150}
5151
Larisse Voufo236bec22013-06-10 06:50:24 +00005152static ExprResult
5153diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5154 Sema::ContextualImplicitConverter &Converter,
5155 QualType T, UnresolvedSetImpl &ViableConversions) {
5156
5157 if (Converter.Suppress)
5158 return ExprError();
5159
5160 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5161 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5162 CXXConversionDecl *Conv =
5163 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5164 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5165 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5166 }
5167 return SemaRef.Owned(From);
5168}
5169
5170static bool
5171diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5172 Sema::ContextualImplicitConverter &Converter,
5173 QualType T, bool HadMultipleCandidates,
5174 UnresolvedSetImpl &ExplicitConversions) {
5175 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5176 DeclAccessPair Found = ExplicitConversions[0];
5177 CXXConversionDecl *Conversion =
5178 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5179
5180 // The user probably meant to invoke the given explicit
5181 // conversion; use it.
5182 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5183 std::string TypeStr;
5184 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5185
5186 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5187 << FixItHint::CreateInsertion(From->getLocStart(),
5188 "static_cast<" + TypeStr + ">(")
5189 << FixItHint::CreateInsertion(
5190 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5191 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5192
5193 // If we aren't in a SFINAE context, build a call to the
5194 // explicit conversion function.
5195 if (SemaRef.isSFINAEContext())
5196 return true;
5197
5198 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5199 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5200 HadMultipleCandidates);
5201 if (Result.isInvalid())
5202 return true;
5203 // Record usage of conversion in an implicit cast.
5204 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5205 CK_UserDefinedConversion, Result.get(), 0,
5206 Result.get()->getValueKind());
5207 }
5208 return false;
5209}
5210
5211static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5212 Sema::ContextualImplicitConverter &Converter,
5213 QualType T, bool HadMultipleCandidates,
5214 DeclAccessPair &Found) {
5215 CXXConversionDecl *Conversion =
5216 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5217 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5218
5219 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5220 if (!Converter.SuppressConversion) {
5221 if (SemaRef.isSFINAEContext())
5222 return true;
5223
5224 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5225 << From->getSourceRange();
5226 }
5227
5228 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5229 HadMultipleCandidates);
5230 if (Result.isInvalid())
5231 return true;
5232 // Record usage of conversion in an implicit cast.
5233 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5234 CK_UserDefinedConversion, Result.get(), 0,
5235 Result.get()->getValueKind());
5236 return false;
5237}
5238
5239static ExprResult finishContextualImplicitConversion(
5240 Sema &SemaRef, SourceLocation Loc, Expr *From,
5241 Sema::ContextualImplicitConverter &Converter) {
5242 if (!Converter.match(From->getType()) && !Converter.Suppress)
5243 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5244 << From->getSourceRange();
5245
5246 return SemaRef.DefaultLvalueConversion(From);
5247}
5248
5249static void
5250collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5251 UnresolvedSetImpl &ViableConversions,
5252 OverloadCandidateSet &CandidateSet) {
5253 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5254 DeclAccessPair FoundDecl = ViableConversions[I];
5255 NamedDecl *D = FoundDecl.getDecl();
5256 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5257 if (isa<UsingShadowDecl>(D))
5258 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5259
5260 CXXConversionDecl *Conv;
5261 FunctionTemplateDecl *ConvTemplate;
5262 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5263 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5264 else
5265 Conv = cast<CXXConversionDecl>(D);
5266
5267 if (ConvTemplate)
5268 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005269 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5270 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005271 else
5272 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005273 ToType, CandidateSet,
5274 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005275 }
5276}
5277
Richard Smithccc11812013-05-21 19:05:48 +00005278/// \brief Attempt to convert the given expression to a type which is accepted
5279/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005280///
Richard Smithccc11812013-05-21 19:05:48 +00005281/// This routine will attempt to convert an expression of class type to a
5282/// type accepted by the specified converter. In C++11 and before, the class
5283/// must have a single non-explicit conversion function converting to a matching
5284/// type. In C++1y, there can be multiple such conversion functions, but only
5285/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005286///
Douglas Gregor4799d032010-06-30 00:20:43 +00005287/// \param Loc The source location of the construct that requires the
5288/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005289///
James Dennett18348b62012-06-22 08:52:37 +00005290/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005291///
Richard Smithccc11812013-05-21 19:05:48 +00005292/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005293///
Douglas Gregor4799d032010-06-30 00:20:43 +00005294/// \returns The expression, converted to an integral or enumeration type if
5295/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005296ExprResult Sema::PerformContextualImplicitConversion(
5297 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005298 // We can't perform any more checking for type-dependent expressions.
5299 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005300 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005301
Eli Friedman1da70392012-01-26 00:26:18 +00005302 // Process placeholders immediately.
5303 if (From->hasPlaceholderType()) {
5304 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005305 if (result.isInvalid())
5306 return result;
Eli Friedman1da70392012-01-26 00:26:18 +00005307 From = result.take();
5308 }
5309
Richard Smithccc11812013-05-21 19:05:48 +00005310 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005311 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005312 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005313 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005314
5315 // FIXME: Check for missing '()' if T is a function type?
5316
Richard Smithccc11812013-05-21 19:05:48 +00005317 // We can only perform contextual implicit conversions on objects of class
5318 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005319 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005320 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005321 if (!Converter.Suppress)
5322 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005323 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005325
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005326 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005327 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005328 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005329 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005330
5331 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5332 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5333
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005334 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smithccc11812013-05-21 19:05:48 +00005335 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005336 }
Richard Smithccc11812013-05-21 19:05:48 +00005337 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005338
5339 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005340 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005341
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005342 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005343 UnresolvedSet<4>
5344 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005345 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005346 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005347 CXXRecordDecl::conversion_iterator> Conversions =
5348 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349
Larisse Voufo236bec22013-06-10 06:50:24 +00005350 bool HadMultipleCandidates =
5351 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005352
Larisse Voufo236bec22013-06-10 06:50:24 +00005353 // To check that there is only one target type, in C++1y:
5354 QualType ToType;
5355 bool HasUniqueTargetType = true;
5356
5357 // Collect explicit or viable (potentially in C++1y) conversions.
5358 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5359 E = Conversions.second;
5360 I != E; ++I) {
5361 NamedDecl *D = (*I)->getUnderlyingDecl();
5362 CXXConversionDecl *Conversion;
5363 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5364 if (ConvTemplate) {
5365 if (getLangOpts().CPlusPlus1y)
5366 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5367 else
5368 continue; // C++11 does not consider conversion operator templates(?).
5369 } else
5370 Conversion = cast<CXXConversionDecl>(D);
5371
5372 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5373 "Conversion operator templates are considered potentially "
5374 "viable in C++1y");
5375
5376 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5377 if (Converter.match(CurToType) || ConvTemplate) {
5378
5379 if (Conversion->isExplicit()) {
5380 // FIXME: For C++1y, do we need this restriction?
5381 // cf. diagnoseNoViableConversion()
5382 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005383 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005384 } else {
5385 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5386 if (ToType.isNull())
5387 ToType = CurToType.getUnqualifiedType();
5388 else if (HasUniqueTargetType &&
5389 (CurToType.getUnqualifiedType() != ToType))
5390 HasUniqueTargetType = false;
5391 }
5392 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005393 }
Richard Smith8dd34252012-02-04 07:07:42 +00005394 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005396
Larisse Voufo236bec22013-06-10 06:50:24 +00005397 if (getLangOpts().CPlusPlus1y) {
5398 // C++1y [conv]p6:
5399 // ... An expression e of class type E appearing in such a context
5400 // is said to be contextually implicitly converted to a specified
5401 // type T and is well-formed if and only if e can be implicitly
5402 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005403 // for conversion functions whose return type is cv T or reference to
5404 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005405 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005406
Larisse Voufo236bec22013-06-10 06:50:24 +00005407 // If no unique T is found:
5408 if (ToType.isNull()) {
5409 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5410 HadMultipleCandidates,
5411 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005412 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005413 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005414 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005415
Larisse Voufo236bec22013-06-10 06:50:24 +00005416 // If more than one unique Ts are found:
5417 if (!HasUniqueTargetType)
5418 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5419 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005420
Larisse Voufo236bec22013-06-10 06:50:24 +00005421 // If one unique T is found:
5422 // First, build a candidate set from the previously recorded
5423 // potentially viable conversions.
5424 OverloadCandidateSet CandidateSet(Loc);
5425 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5426 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
Larisse Voufo236bec22013-06-10 06:50:24 +00005428 // Then, perform overload resolution over the candidate set.
5429 OverloadCandidateSet::iterator Best;
5430 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5431 case OR_Success: {
5432 // Apply this conversion.
5433 DeclAccessPair Found =
5434 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5435 if (recordConversion(*this, Loc, From, Converter, T,
5436 HadMultipleCandidates, Found))
5437 return ExprError();
5438 break;
5439 }
5440 case OR_Ambiguous:
5441 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5442 ViableConversions);
5443 case OR_No_Viable_Function:
5444 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5445 HadMultipleCandidates,
5446 ExplicitConversions))
5447 return ExprError();
5448 // fall through 'OR_Deleted' case.
5449 case OR_Deleted:
5450 // We'll complain below about a non-integral condition type.
5451 break;
5452 }
5453 } else {
5454 switch (ViableConversions.size()) {
5455 case 0: {
5456 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5457 HadMultipleCandidates,
5458 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005459 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005460
Larisse Voufo236bec22013-06-10 06:50:24 +00005461 // We'll complain below about a non-integral condition type.
5462 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005463 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005464 case 1: {
5465 // Apply this conversion.
5466 DeclAccessPair Found = ViableConversions[0];
5467 if (recordConversion(*this, Loc, From, Converter, T,
5468 HadMultipleCandidates, Found))
5469 return ExprError();
5470 break;
5471 }
5472 default:
5473 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5474 ViableConversions);
5475 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005476 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005477
Larisse Voufo236bec22013-06-10 06:50:24 +00005478 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005479}
5480
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005481/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005482/// candidate functions, using the given function call arguments. If
5483/// @p SuppressUserConversions, then don't allow user-defined
5484/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005485///
James Dennett2a4d13c2012-06-15 07:13:21 +00005486/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005487/// based on an incomplete set of function arguments. This feature is used by
5488/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005489void
5490Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005491 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005492 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005493 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005494 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005495 bool PartialOverloading,
5496 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005497 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005498 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005499 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005500 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005501 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005502
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005503 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005504 if (!isa<CXXConstructorDecl>(Method)) {
5505 // If we get here, it's because we're calling a member function
5506 // that is named without a member access expression (e.g.,
5507 // "this->f") that was either written explicitly or created
5508 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005509 // function, e.g., X::f(). We use an empty type for the implied
5510 // object argument (C++ [over.call.func]p3), and the acting context
5511 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005512 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005514 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005515 return;
5516 }
5517 // We treat a constructor like a non-member function, since its object
5518 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005519 }
5520
Douglas Gregorff7028a2009-11-13 23:59:09 +00005521 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005522 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005523
Richard Smith8b86f2d2013-11-04 01:48:18 +00005524 // C++11 [class.copy]p11: [DR1402]
5525 // A defaulted move constructor that is defined as deleted is ignored by
5526 // overload resolution.
5527 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5528 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5529 Constructor->isMoveConstructor())
5530 return;
5531
Douglas Gregor27381f32009-11-23 12:27:39 +00005532 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005533 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005534
Richard Smith8b86f2d2013-11-04 01:48:18 +00005535 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005536 // C++ [class.copy]p3:
5537 // A member function template is never instantiated to perform the copy
5538 // of a class object to an object of its class type.
5539 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005540 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005541 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005542 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5543 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005544 return;
5545 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005546
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005547 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005548 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005549 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005550 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005551 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005552 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005553 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005554 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005556 unsigned NumParams = Proto->getNumParams();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005557
5558 // (C++ 13.3.2p2): A candidate function having fewer than m
5559 // parameters is viable only if it has an ellipsis in its parameter
5560 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005561 if ((Args.size() + (PartialOverloading && Args.size())) > NumParams &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005562 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005563 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005564 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005565 return;
5566 }
5567
5568 // (C++ 13.3.2p2): A candidate function having more than m parameters
5569 // is viable only if the (m+1)st parameter has a default argument
5570 // (8.3.6). For the purposes of overload resolution, the
5571 // parameter list is truncated on the right, so that there are
5572 // exactly m parameters.
5573 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005574 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005575 // Not enough arguments.
5576 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005577 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005578 return;
5579 }
5580
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005581 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005582 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005583 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5584 if (CheckCUDATarget(Caller, Function)) {
5585 Candidate.Viable = false;
5586 Candidate.FailureKind = ovl_fail_bad_target;
5587 return;
5588 }
5589
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005590 // Determine the implicit conversion sequences for each of the
5591 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005592 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005593 if (ArgIdx < NumParams) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005594 // (C++ 13.3.2p3): for F to be a viable function, there shall
5595 // exist for each argument an implicit conversion sequence
5596 // (13.3.3.1) that converts that argument to the corresponding
5597 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005598 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005599 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005600 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005601 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005602 /*InOverloadResolution=*/true,
5603 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005604 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005605 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005606 if (Candidate.Conversions[ArgIdx].isBad()) {
5607 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005608 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005609 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005610 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005611 } else {
5612 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5613 // argument for which there is no corresponding parameter is
5614 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005615 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005616 }
5617 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005618
5619 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5620 Candidate.Viable = false;
5621 Candidate.FailureKind = ovl_fail_enable_if;
5622 Candidate.DeductionFailure.Data = FailedAttr;
5623 return;
5624 }
5625}
5626
5627static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5628
5629EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5630 bool MissingImplicitThis) {
5631 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5632 // we need to find the first failing one.
5633 if (!Function->hasAttrs())
5634 return 0;
5635 AttrVec Attrs = Function->getAttrs();
5636 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5637 IsNotEnableIfAttr);
5638 if (Attrs.begin() == E)
5639 return 0;
5640 std::reverse(Attrs.begin(), E);
5641
5642 SFINAETrap Trap(*this);
5643
5644 // Convert the arguments.
5645 SmallVector<Expr *, 16> ConvertedArgs;
5646 bool InitializationFailed = false;
5647 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5648 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5649 !cast<CXXMethodDecl>(Function)->isStatic()) {
5650 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5651 ExprResult R =
5652 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5653 Method, Method);
5654 if (R.isInvalid()) {
5655 InitializationFailed = true;
5656 break;
5657 }
5658 ConvertedArgs.push_back(R.take());
5659 } else {
5660 ExprResult R =
5661 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5662 Context,
5663 Function->getParamDecl(i)),
5664 SourceLocation(),
5665 Args[i]);
5666 if (R.isInvalid()) {
5667 InitializationFailed = true;
5668 break;
5669 }
5670 ConvertedArgs.push_back(R.take());
5671 }
5672 }
5673
5674 if (InitializationFailed || Trap.hasErrorOccurred())
5675 return cast<EnableIfAttr>(Attrs[0]);
5676
5677 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5678 APValue Result;
5679 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5680 if (!EIA->getCond()->EvaluateWithSubstitution(
5681 Result, Context, Function,
5682 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(),
5683 ConvertedArgs.size())) ||
5684 !Result.isInt() || !Result.getInt().getBoolValue()) {
5685 return EIA;
5686 }
5687 }
5688 return 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005689}
5690
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005691/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005692/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005693void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005694 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005695 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005696 bool SuppressUserConversions,
5697 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005698 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005699 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5700 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005701 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005702 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005703 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005704 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005705 Args.slice(1), CandidateSet,
5706 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005707 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005708 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005709 SuppressUserConversions);
5710 } else {
John McCalla0296f72010-03-19 07:35:19 +00005711 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005712 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5713 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005714 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005715 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005716 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005717 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005718 Args[0]->Classify(Context), Args.slice(1),
5719 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005720 else
John McCalla0296f72010-03-19 07:35:19 +00005721 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005722 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005723 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005724 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005725 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005726}
5727
John McCallf0f1cf02009-11-17 07:50:12 +00005728/// AddMethodCandidate - Adds a named decl (which is some kind of
5729/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005730void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005731 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005732 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005733 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005734 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005735 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005736 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005737 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005738
5739 if (isa<UsingShadowDecl>(Decl))
5740 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741
John McCallf0f1cf02009-11-17 07:50:12 +00005742 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5743 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5744 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005745 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5746 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005747 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005748 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005749 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005750 } else {
John McCalla0296f72010-03-19 07:35:19 +00005751 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005752 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005753 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005754 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005755 }
5756}
5757
Douglas Gregor436424c2008-11-18 23:14:02 +00005758/// AddMethodCandidate - Adds the given C++ member function to the set
5759/// of candidate functions, using the given function call arguments
5760/// and the object argument (@c Object). For example, in a call
5761/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5762/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5763/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005764/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005765void
John McCalla0296f72010-03-19 07:35:19 +00005766Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005767 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005768 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005769 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005770 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005771 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005772 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005773 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005774 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005775 assert(!isa<CXXConstructorDecl>(Method) &&
5776 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005777
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005778 if (!CandidateSet.isNewCandidate(Method))
5779 return;
5780
Richard Smith8b86f2d2013-11-04 01:48:18 +00005781 // C++11 [class.copy]p23: [DR1402]
5782 // A defaulted move assignment operator that is defined as deleted is
5783 // ignored by overload resolution.
5784 if (Method->isDefaulted() && Method->isDeleted() &&
5785 Method->isMoveAssignmentOperator())
5786 return;
5787
Douglas Gregor27381f32009-11-23 12:27:39 +00005788 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005789 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005790
Douglas Gregor436424c2008-11-18 23:14:02 +00005791 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005792 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005793 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005794 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005795 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005796 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005797 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005798
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005799 unsigned NumParams = Proto->getNumParams();
Douglas Gregor436424c2008-11-18 23:14:02 +00005800
5801 // (C++ 13.3.2p2): A candidate function having fewer than m
5802 // parameters is viable only if it has an ellipsis in its parameter
5803 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005804 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005805 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005806 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005807 return;
5808 }
5809
5810 // (C++ 13.3.2p2): A candidate function having more than m parameters
5811 // is viable only if the (m+1)st parameter has a default argument
5812 // (8.3.6). For the purposes of overload resolution, the
5813 // parameter list is truncated on the right, so that there are
5814 // exactly m parameters.
5815 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005816 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005817 // Not enough arguments.
5818 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005819 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005820 return;
5821 }
5822
5823 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005824
John McCall6e9f8f62009-12-03 04:06:58 +00005825 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005826 // The implicit object argument is ignored.
5827 Candidate.IgnoreObjectArgument = true;
5828 else {
5829 // Determine the implicit conversion sequence for the object
5830 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005831 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005832 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5833 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005834 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005835 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005836 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005837 return;
5838 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005839 }
5840
5841 // Determine the implicit conversion sequences for each of the
5842 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005843 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00005844 if (ArgIdx < NumParams) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005845 // (C++ 13.3.2p3): for F to be a viable function, there shall
5846 // exist for each argument an implicit conversion sequence
5847 // (13.3.3.1) that converts that argument to the corresponding
5848 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00005849 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005850 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005851 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005852 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005853 /*InOverloadResolution=*/true,
5854 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005855 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005856 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005857 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005858 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005859 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005860 }
5861 } else {
5862 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5863 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005864 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005865 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005866 }
5867 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005868
5869 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5870 Candidate.Viable = false;
5871 Candidate.FailureKind = ovl_fail_enable_if;
5872 Candidate.DeductionFailure.Data = FailedAttr;
5873 return;
5874 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005875}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005876
Douglas Gregor97628d62009-08-21 00:16:32 +00005877/// \brief Add a C++ member function template as a candidate to the candidate
5878/// set, using template argument deduction to produce an appropriate member
5879/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005880void
Douglas Gregor97628d62009-08-21 00:16:32 +00005881Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005882 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005883 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005884 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005885 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005886 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005887 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005888 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005889 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005890 if (!CandidateSet.isNewCandidate(MethodTmpl))
5891 return;
5892
Douglas Gregor97628d62009-08-21 00:16:32 +00005893 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005894 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005895 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005896 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005897 // candidate functions in the usual way.113) A given name can refer to one
5898 // or more function templates and also to a set of overloaded non-template
5899 // functions. In such a case, the candidate functions generated from each
5900 // function template are combined with the set of non-template candidate
5901 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005902 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005903 FunctionDecl *Specialization = 0;
5904 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005905 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5906 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005907 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005908 Candidate.FoundDecl = FoundDecl;
5909 Candidate.Function = MethodTmpl->getTemplatedDecl();
5910 Candidate.Viable = false;
5911 Candidate.FailureKind = ovl_fail_bad_deduction;
5912 Candidate.IsSurrogate = false;
5913 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005914 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005915 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005916 Info);
5917 return;
5918 }
Mike Stump11289f42009-09-09 15:08:12 +00005919
Douglas Gregor97628d62009-08-21 00:16:32 +00005920 // Add the function template specialization produced by template argument
5921 // deduction as a candidate.
5922 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005923 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005924 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005925 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005926 ActingContext, ObjectType, ObjectClassification, Args,
5927 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005928}
5929
Douglas Gregor05155d82009-08-21 23:19:43 +00005930/// \brief Add a C++ function template specialization as a candidate
5931/// in the candidate set, using template argument deduction to produce
5932/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005933void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005934Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005935 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005936 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005937 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005938 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005939 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005940 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5941 return;
5942
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005943 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005944 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005945 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005946 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005947 // candidate functions in the usual way.113) A given name can refer to one
5948 // or more function templates and also to a set of overloaded non-template
5949 // functions. In such a case, the candidate functions generated from each
5950 // function template are combined with the set of non-template candidate
5951 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005952 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005953 FunctionDecl *Specialization = 0;
5954 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005955 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5956 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005957 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005958 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005959 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5960 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005961 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005962 Candidate.IsSurrogate = false;
5963 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005964 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005965 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005966 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005967 return;
5968 }
Mike Stump11289f42009-09-09 15:08:12 +00005969
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005970 // Add the function template specialization produced by template argument
5971 // deduction as a candidate.
5972 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005973 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005974 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005975}
Mike Stump11289f42009-09-09 15:08:12 +00005976
Douglas Gregor4b60a152013-11-07 22:34:54 +00005977/// Determine whether this is an allowable conversion from the result
5978/// of an explicit conversion operator to the expected type, per C++
5979/// [over.match.conv]p1 and [over.match.ref]p1.
5980///
5981/// \param ConvType The return type of the conversion function.
5982///
5983/// \param ToType The type we are converting to.
5984///
5985/// \param AllowObjCPointerConversion Allow a conversion from one
5986/// Objective-C pointer to another.
5987///
5988/// \returns true if the conversion is allowable, false otherwise.
5989static bool isAllowableExplicitConversion(Sema &S,
5990 QualType ConvType, QualType ToType,
5991 bool AllowObjCPointerConversion) {
5992 QualType ToNonRefType = ToType.getNonReferenceType();
5993
5994 // Easy case: the types are the same.
5995 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
5996 return true;
5997
5998 // Allow qualification conversions.
5999 bool ObjCLifetimeConversion;
6000 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6001 ObjCLifetimeConversion))
6002 return true;
6003
6004 // If we're not allowed to consider Objective-C pointer conversions,
6005 // we're done.
6006 if (!AllowObjCPointerConversion)
6007 return false;
6008
6009 // Is this an Objective-C pointer conversion?
6010 bool IncompatibleObjC = false;
6011 QualType ConvertedType;
6012 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6013 IncompatibleObjC);
6014}
6015
Douglas Gregora1f013e2008-11-07 22:36:19 +00006016/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006017/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006018/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006019/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006020/// (which may or may not be the same type as the type that the
6021/// conversion function produces).
6022void
6023Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006024 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006025 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006026 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006027 OverloadCandidateSet& CandidateSet,
6028 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006029 assert(!Conversion->getDescribedFunctionTemplate() &&
6030 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006031 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006032 if (!CandidateSet.isNewCandidate(Conversion))
6033 return;
6034
Richard Smith2a7d4812013-05-04 07:00:32 +00006035 // If the conversion function has an undeduced return type, trigger its
6036 // deduction now.
6037 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6038 if (DeduceReturnType(Conversion, From->getExprLoc()))
6039 return;
6040 ConvType = Conversion->getConversionType().getNonReferenceType();
6041 }
6042
Richard Smith089c3162013-09-21 21:55:46 +00006043 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6044 // operator is only a candidate if its return type is the target type or
6045 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006046 if (Conversion->isExplicit() &&
6047 !isAllowableExplicitConversion(*this, ConvType, ToType,
6048 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006049 return;
6050
Douglas Gregor27381f32009-11-23 12:27:39 +00006051 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006052 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006053
Douglas Gregora1f013e2008-11-07 22:36:19 +00006054 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006055 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006056 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006057 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006058 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006059 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006060 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006061 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006062 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006063 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006064 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006065
Douglas Gregor6affc782010-08-19 15:37:02 +00006066 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006067 // For conversion functions, the function is considered to be a member of
6068 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006069 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006070 //
6071 // Determine the implicit conversion sequence for the implicit
6072 // object parameter.
6073 QualType ImplicitParamType = From->getType();
6074 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6075 ImplicitParamType = FromPtrType->getPointeeType();
6076 CXXRecordDecl *ConversionContext
6077 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006078
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006079 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006080 = TryObjectArgumentInitialization(*this, From->getType(),
6081 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006082 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006083
John McCall0d1da222010-01-12 00:44:57 +00006084 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006085 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006086 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006087 return;
6088 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006089
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006090 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006091 // derived to base as such conversions are given Conversion Rank. They only
6092 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6093 QualType FromCanon
6094 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6095 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6096 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6097 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006098 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006099 return;
6100 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006101
Douglas Gregora1f013e2008-11-07 22:36:19 +00006102 // To determine what the conversion from the result of calling the
6103 // conversion function to the type we're eventually trying to
6104 // convert to (ToType), we need to synthesize a call to the
6105 // conversion function and attempt copy initialization from it. This
6106 // makes sure that we get the right semantics with respect to
6107 // lvalues/rvalues and the type. Fortunately, we can allocate this
6108 // call on the stack and we don't need its arguments to be
6109 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006110 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006111 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006112 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6113 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006114 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006115 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006116
Richard Smith48d24642011-07-13 22:53:21 +00006117 QualType ConversionType = Conversion->getConversionType();
6118 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006119 Candidate.Viable = false;
6120 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6121 return;
6122 }
6123
Richard Smith48d24642011-07-13 22:53:21 +00006124 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006125
Mike Stump11289f42009-09-09 15:08:12 +00006126 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006127 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6128 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006129 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006130 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006131 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006132 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006133 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006134 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006135 /*InOverloadResolution=*/false,
6136 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006137
John McCall0d1da222010-01-12 00:44:57 +00006138 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006139 case ImplicitConversionSequence::StandardConversion:
6140 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006141
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006142 // C++ [over.ics.user]p3:
6143 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006144 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006145 // shall have exact match rank.
6146 if (Conversion->getPrimaryTemplate() &&
6147 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6148 Candidate.Viable = false;
6149 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006150 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006152
Douglas Gregorcba72b12011-01-21 05:18:22 +00006153 // C++0x [dcl.init.ref]p5:
6154 // In the second case, if the reference is an rvalue reference and
6155 // the second standard conversion sequence of the user-defined
6156 // conversion sequence includes an lvalue-to-rvalue conversion, the
6157 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006158 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006159 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6160 Candidate.Viable = false;
6161 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006162 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006163 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006164 break;
6165
6166 case ImplicitConversionSequence::BadConversion:
6167 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006168 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006169 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006170
6171 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006172 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006173 "Can only end up with a standard conversion sequence or failure");
6174 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006175
6176 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6177 Candidate.Viable = false;
6178 Candidate.FailureKind = ovl_fail_enable_if;
6179 Candidate.DeductionFailure.Data = FailedAttr;
6180 return;
6181 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006182}
6183
Douglas Gregor05155d82009-08-21 23:19:43 +00006184/// \brief Adds a conversion function template specialization
6185/// candidate to the overload set, using template argument deduction
6186/// to deduce the template arguments of the conversion function
6187/// template from the type that we are converting to (C++
6188/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006189void
Douglas Gregor05155d82009-08-21 23:19:43 +00006190Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006191 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006192 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006193 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006194 OverloadCandidateSet &CandidateSet,
6195 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006196 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6197 "Only conversion function templates permitted here");
6198
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006199 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6200 return;
6201
Craig Toppere6706e42012-09-19 02:26:47 +00006202 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00006203 CXXConversionDecl *Specialization = 0;
6204 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006205 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006206 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006207 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006208 Candidate.FoundDecl = FoundDecl;
6209 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6210 Candidate.Viable = false;
6211 Candidate.FailureKind = ovl_fail_bad_deduction;
6212 Candidate.IsSurrogate = false;
6213 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006214 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006215 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006216 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006217 return;
6218 }
Mike Stump11289f42009-09-09 15:08:12 +00006219
Douglas Gregor05155d82009-08-21 23:19:43 +00006220 // Add the conversion function template specialization produced by
6221 // template argument deduction as a candidate.
6222 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006223 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006224 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006225}
6226
Douglas Gregorab7897a2008-11-19 22:57:39 +00006227/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6228/// converts the given @c Object to a function pointer via the
6229/// conversion function @c Conversion, and then attempts to call it
6230/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6231/// the type of function that we'll eventually be calling.
6232void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006233 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006234 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006235 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006236 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006237 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006238 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006239 if (!CandidateSet.isNewCandidate(Conversion))
6240 return;
6241
Douglas Gregor27381f32009-11-23 12:27:39 +00006242 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006243 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006244
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006245 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006246 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006247 Candidate.Function = 0;
6248 Candidate.Surrogate = Conversion;
6249 Candidate.Viable = true;
6250 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006251 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006252 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006253
6254 // Determine the implicit conversion sequence for the implicit
6255 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006256 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006257 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006258 Object->Classify(Context),
6259 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006260 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006261 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006262 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006263 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006264 return;
6265 }
6266
6267 // The first conversion is actually a user-defined conversion whose
6268 // first conversion is ObjectInit's standard conversion (which is
6269 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006270 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006271 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006272 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006273 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006274 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006275 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006276 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006277 = Candidate.Conversions[0].UserDefined.Before;
6278 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6279
Mike Stump11289f42009-09-09 15:08:12 +00006280 // Find the
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006281 unsigned NumParams = Proto->getNumParams();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006282
6283 // (C++ 13.3.2p2): A candidate function having fewer than m
6284 // parameters is viable only if it has an ellipsis in its parameter
6285 // list (8.3.5).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006286 if (Args.size() > NumParams && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006287 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006288 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006289 return;
6290 }
6291
6292 // Function types don't have any default arguments, so just check if
6293 // we have enough arguments.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006294 if (Args.size() < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006295 // Not enough arguments.
6296 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006297 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006298 return;
6299 }
6300
6301 // Determine the implicit conversion sequences for each of the
6302 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006303 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00006304 if (ArgIdx < NumParams) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006305 // (C++ 13.3.2p3): for F to be a viable function, there shall
6306 // exist for each argument an implicit conversion sequence
6307 // (13.3.3.1) that converts that argument to the corresponding
6308 // parameter of F.
Alp Toker9cacbab2014-01-20 20:26:09 +00006309 QualType ParamType = Proto->getParamType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006310 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006311 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006312 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006313 /*InOverloadResolution=*/false,
6314 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006315 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006316 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006317 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006318 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006319 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006320 }
6321 } else {
6322 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6323 // argument for which there is no corresponding parameter is
6324 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006325 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006326 }
6327 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006328
6329 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6330 Candidate.Viable = false;
6331 Candidate.FailureKind = ovl_fail_enable_if;
6332 Candidate.DeductionFailure.Data = FailedAttr;
6333 return;
6334 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006335}
6336
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006337/// \brief Add overload candidates for overloaded operators that are
6338/// member functions.
6339///
6340/// Add the overloaded operator candidates that are member functions
6341/// for the operator Op that was used in an operator expression such
6342/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6343/// CandidateSet will store the added overload candidates. (C++
6344/// [over.match.oper]).
6345void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6346 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006347 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006348 OverloadCandidateSet& CandidateSet,
6349 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006350 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6351
6352 // C++ [over.match.oper]p3:
6353 // For a unary operator @ with an operand of a type whose
6354 // cv-unqualified version is T1, and for a binary operator @ with
6355 // a left operand of a type whose cv-unqualified version is T1 and
6356 // a right operand of a type whose cv-unqualified version is T2,
6357 // three sets of candidate functions, designated member
6358 // candidates, non-member candidates and built-in candidates, are
6359 // constructed as follows:
6360 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006361
Richard Smith0feaf0c2013-04-20 12:41:22 +00006362 // -- If T1 is a complete class type or a class currently being
6363 // defined, the set of member candidates is the result of the
6364 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6365 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006366 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006367 // Complete the type if it can be completed.
6368 RequireCompleteType(OpLoc, T1, 0);
6369 // If the type is neither complete nor being defined, bail out now.
6370 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006371 return;
Mike Stump11289f42009-09-09 15:08:12 +00006372
John McCall27b18f82009-11-17 02:14:36 +00006373 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6374 LookupQualifiedName(Operators, T1Rec->getDecl());
6375 Operators.suppressDiagnostics();
6376
Mike Stump11289f42009-09-09 15:08:12 +00006377 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006378 OperEnd = Operators.end();
6379 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006380 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006381 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006382 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006383 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006384 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006385 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006386 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006387}
6388
Douglas Gregora11693b2008-11-12 17:17:38 +00006389/// AddBuiltinCandidate - Add a candidate for a built-in
6390/// operator. ResultTy and ParamTys are the result and parameter types
6391/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006392/// arguments being passed to the candidate. IsAssignmentOperator
6393/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006394/// operator. NumContextualBoolArguments is the number of arguments
6395/// (at the beginning of the argument list) that will be contextually
6396/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006397void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006398 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006399 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006400 bool IsAssignmentOperator,
6401 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006402 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006403 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006404
Douglas Gregora11693b2008-11-12 17:17:38 +00006405 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006406 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00006407 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00006408 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006409 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006410 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006411 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006412 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006413 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6414
6415 // Determine the implicit conversion sequences for each of the
6416 // arguments.
6417 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006418 Candidate.ExplicitCallArguments = Args.size();
6419 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006420 // C++ [over.match.oper]p4:
6421 // For the built-in assignment operators, conversions of the
6422 // left operand are restricted as follows:
6423 // -- no temporaries are introduced to hold the left operand, and
6424 // -- no user-defined conversions are applied to the left
6425 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006426 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006427 //
6428 // We block these conversions by turning off user-defined
6429 // conversions, since that is the only way that initialization of
6430 // a reference to a non-class type can occur from something that
6431 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006432 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006433 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006434 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006435 Candidate.Conversions[ArgIdx]
6436 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006437 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006438 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006439 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006440 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006441 /*InOverloadResolution=*/false,
6442 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006443 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006444 }
John McCall0d1da222010-01-12 00:44:57 +00006445 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006446 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006447 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006448 break;
6449 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006450 }
6451}
6452
Craig Toppercd7b0332013-07-01 06:29:40 +00006453namespace {
6454
Douglas Gregora11693b2008-11-12 17:17:38 +00006455/// BuiltinCandidateTypeSet - A set of types that will be used for the
6456/// candidate operator functions for built-in operators (C++
6457/// [over.built]). The types are separated into pointer types and
6458/// enumeration types.
6459class BuiltinCandidateTypeSet {
6460 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006461 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006462
6463 /// PointerTypes - The set of pointer types that will be used in the
6464 /// built-in candidates.
6465 TypeSet PointerTypes;
6466
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006467 /// MemberPointerTypes - The set of member pointer types that will be
6468 /// used in the built-in candidates.
6469 TypeSet MemberPointerTypes;
6470
Douglas Gregora11693b2008-11-12 17:17:38 +00006471 /// EnumerationTypes - The set of enumeration types that will be
6472 /// used in the built-in candidates.
6473 TypeSet EnumerationTypes;
6474
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006475 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006476 /// candidates.
6477 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006478
6479 /// \brief A flag indicating non-record types are viable candidates
6480 bool HasNonRecordTypes;
6481
6482 /// \brief A flag indicating whether either arithmetic or enumeration types
6483 /// were present in the candidate set.
6484 bool HasArithmeticOrEnumeralTypes;
6485
Douglas Gregor80af3132011-05-21 23:15:46 +00006486 /// \brief A flag indicating whether the nullptr type was present in the
6487 /// candidate set.
6488 bool HasNullPtrType;
6489
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006490 /// Sema - The semantic analysis instance where we are building the
6491 /// candidate type set.
6492 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006493
Douglas Gregora11693b2008-11-12 17:17:38 +00006494 /// Context - The AST context in which we will build the type sets.
6495 ASTContext &Context;
6496
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006497 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6498 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006499 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006500
6501public:
6502 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006503 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006504
Mike Stump11289f42009-09-09 15:08:12 +00006505 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006506 : HasNonRecordTypes(false),
6507 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006508 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006509 SemaRef(SemaRef),
6510 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006511
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006513 SourceLocation Loc,
6514 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006515 bool AllowExplicitConversions,
6516 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006517
6518 /// pointer_begin - First pointer type found;
6519 iterator pointer_begin() { return PointerTypes.begin(); }
6520
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006521 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006522 iterator pointer_end() { return PointerTypes.end(); }
6523
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006524 /// member_pointer_begin - First member pointer type found;
6525 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6526
6527 /// member_pointer_end - Past the last member pointer type found;
6528 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6529
Douglas Gregora11693b2008-11-12 17:17:38 +00006530 /// enumeration_begin - First enumeration type found;
6531 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6532
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006533 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006534 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006536 iterator vector_begin() { return VectorTypes.begin(); }
6537 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006538
6539 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6540 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006541 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006542};
6543
Craig Toppercd7b0332013-07-01 06:29:40 +00006544} // end anonymous namespace
6545
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006546/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006547/// the set of pointer types along with any more-qualified variants of
6548/// that type. For example, if @p Ty is "int const *", this routine
6549/// will add "int const *", "int const volatile *", "int const
6550/// restrict *", and "int const volatile restrict *" to the set of
6551/// pointer types. Returns true if the add of @p Ty itself succeeded,
6552/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006553///
6554/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006555bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006556BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6557 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006558
Douglas Gregora11693b2008-11-12 17:17:38 +00006559 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006560 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006561 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006562
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006563 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006564 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006565 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006566 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006567 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6568 PointeeTy = PTy->getPointeeType();
6569 buildObjCPtr = true;
6570 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006571 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006572 }
6573
Sebastian Redl4990a632009-11-18 20:39:26 +00006574 // Don't add qualified variants of arrays. For one, they're not allowed
6575 // (the qualifier would sink to the element type), and for another, the
6576 // only overload situation where it matters is subscript or pointer +- int,
6577 // and those shouldn't have qualifier variants anyway.
6578 if (PointeeTy->isArrayType())
6579 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006580
John McCall8ccfcb52009-09-24 19:53:00 +00006581 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006582 bool hasVolatile = VisibleQuals.hasVolatile();
6583 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006584
John McCall8ccfcb52009-09-24 19:53:00 +00006585 // Iterate through all strict supersets of BaseCVR.
6586 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6587 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006588 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006589 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006590
6591 // Skip over restrict if no restrict found anywhere in the types, or if
6592 // the type cannot be restrict-qualified.
6593 if ((CVR & Qualifiers::Restrict) &&
6594 (!hasRestrict ||
6595 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6596 continue;
6597
6598 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006599 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006600
6601 // Build qualified pointer type.
6602 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006603 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006604 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006605 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006606 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6607
6608 // Insert qualified pointer type.
6609 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006610 }
6611
6612 return true;
6613}
6614
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006615/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6616/// to the set of pointer types along with any more-qualified variants of
6617/// that type. For example, if @p Ty is "int const *", this routine
6618/// will add "int const *", "int const volatile *", "int const
6619/// restrict *", and "int const volatile restrict *" to the set of
6620/// pointer types. Returns true if the add of @p Ty itself succeeded,
6621/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006622///
6623/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006624bool
6625BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6626 QualType Ty) {
6627 // Insert this type.
6628 if (!MemberPointerTypes.insert(Ty))
6629 return false;
6630
John McCall8ccfcb52009-09-24 19:53:00 +00006631 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6632 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006633
John McCall8ccfcb52009-09-24 19:53:00 +00006634 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006635 // Don't add qualified variants of arrays. For one, they're not allowed
6636 // (the qualifier would sink to the element type), and for another, the
6637 // only overload situation where it matters is subscript or pointer +- int,
6638 // and those shouldn't have qualifier variants anyway.
6639 if (PointeeTy->isArrayType())
6640 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006641 const Type *ClassTy = PointerTy->getClass();
6642
6643 // Iterate through all strict supersets of the pointee type's CVR
6644 // qualifiers.
6645 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6646 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6647 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006648
John McCall8ccfcb52009-09-24 19:53:00 +00006649 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006650 MemberPointerTypes.insert(
6651 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006652 }
6653
6654 return true;
6655}
6656
Douglas Gregora11693b2008-11-12 17:17:38 +00006657/// AddTypesConvertedFrom - Add each of the types to which the type @p
6658/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006659/// primarily interested in pointer types and enumeration types. We also
6660/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006661/// AllowUserConversions is true if we should look at the conversion
6662/// functions of a class type, and AllowExplicitConversions if we
6663/// should also include the explicit conversion functions of a class
6664/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006665void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006666BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006667 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006668 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006669 bool AllowExplicitConversions,
6670 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006671 // Only deal with canonical types.
6672 Ty = Context.getCanonicalType(Ty);
6673
6674 // Look through reference types; they aren't part of the type of an
6675 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006676 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006677 Ty = RefTy->getPointeeType();
6678
John McCall33ddac02011-01-19 10:06:00 +00006679 // If we're dealing with an array type, decay to the pointer.
6680 if (Ty->isArrayType())
6681 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6682
6683 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006684 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006685
Chandler Carruth00a38332010-12-13 01:44:01 +00006686 // Flag if we ever add a non-record type.
6687 const RecordType *TyRec = Ty->getAs<RecordType>();
6688 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6689
Chandler Carruth00a38332010-12-13 01:44:01 +00006690 // Flag if we encounter an arithmetic type.
6691 HasArithmeticOrEnumeralTypes =
6692 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6693
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006694 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6695 PointerTypes.insert(Ty);
6696 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006697 // Insert our type, and its more-qualified variants, into the set
6698 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006699 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006700 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006701 } else if (Ty->isMemberPointerType()) {
6702 // Member pointers are far easier, since the pointee can't be converted.
6703 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6704 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006705 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006706 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006707 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006708 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006709 // We treat vector types as arithmetic types in many contexts as an
6710 // extension.
6711 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006712 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006713 } else if (Ty->isNullPtrType()) {
6714 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006715 } else if (AllowUserConversions && TyRec) {
6716 // No conversion functions in incomplete types.
6717 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6718 return;
Mike Stump11289f42009-09-09 15:08:12 +00006719
Chandler Carruth00a38332010-12-13 01:44:01 +00006720 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006721 std::pair<CXXRecordDecl::conversion_iterator,
6722 CXXRecordDecl::conversion_iterator>
6723 Conversions = ClassDecl->getVisibleConversionFunctions();
6724 for (CXXRecordDecl::conversion_iterator
6725 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006726 NamedDecl *D = I.getDecl();
6727 if (isa<UsingShadowDecl>(D))
6728 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006729
Chandler Carruth00a38332010-12-13 01:44:01 +00006730 // Skip conversion function templates; they don't tell us anything
6731 // about which builtin types we can convert to.
6732 if (isa<FunctionTemplateDecl>(D))
6733 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006734
Chandler Carruth00a38332010-12-13 01:44:01 +00006735 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6736 if (AllowExplicitConversions || !Conv->isExplicit()) {
6737 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6738 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006739 }
6740 }
6741 }
6742}
6743
Douglas Gregor84605ae2009-08-24 13:43:27 +00006744/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6745/// the volatile- and non-volatile-qualified assignment operators for the
6746/// given type to the candidate set.
6747static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6748 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006749 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006750 OverloadCandidateSet &CandidateSet) {
6751 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006752
Douglas Gregor84605ae2009-08-24 13:43:27 +00006753 // T& operator=(T&, T)
6754 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6755 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006756 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006757 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006758
Douglas Gregor84605ae2009-08-24 13:43:27 +00006759 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6760 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006761 ParamTypes[0]
6762 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006763 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006764 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006765 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006766 }
6767}
Mike Stump11289f42009-09-09 15:08:12 +00006768
Sebastian Redl1054fae2009-10-25 17:03:50 +00006769/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6770/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006771static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6772 Qualifiers VRQuals;
6773 const RecordType *TyRec;
6774 if (const MemberPointerType *RHSMPType =
6775 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006776 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006777 else
6778 TyRec = ArgExpr->getType()->getAs<RecordType>();
6779 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006780 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006781 VRQuals.addVolatile();
6782 VRQuals.addRestrict();
6783 return VRQuals;
6784 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006785
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006786 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006787 if (!ClassDecl->hasDefinition())
6788 return VRQuals;
6789
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006790 std::pair<CXXRecordDecl::conversion_iterator,
6791 CXXRecordDecl::conversion_iterator>
6792 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006794 for (CXXRecordDecl::conversion_iterator
6795 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006796 NamedDecl *D = I.getDecl();
6797 if (isa<UsingShadowDecl>(D))
6798 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6799 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006800 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6801 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6802 CanTy = ResTypeRef->getPointeeType();
6803 // Need to go down the pointer/mempointer chain and add qualifiers
6804 // as see them.
6805 bool done = false;
6806 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006807 if (CanTy.isRestrictQualified())
6808 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006809 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6810 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006811 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006812 CanTy->getAs<MemberPointerType>())
6813 CanTy = ResTypeMPtr->getPointeeType();
6814 else
6815 done = true;
6816 if (CanTy.isVolatileQualified())
6817 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006818 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6819 return VRQuals;
6820 }
6821 }
6822 }
6823 return VRQuals;
6824}
John McCall52872982010-11-13 05:51:15 +00006825
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006826namespace {
John McCall52872982010-11-13 05:51:15 +00006827
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006828/// \brief Helper class to manage the addition of builtin operator overload
6829/// candidates. It provides shared state and utility methods used throughout
6830/// the process, as well as a helper method to add each group of builtin
6831/// operator overloads from the standard to a candidate set.
6832class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006833 // Common instance state available to all overload candidate addition methods.
6834 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006835 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006836 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006837 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006838 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006839 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006840
Chandler Carruthc6586e52010-12-12 10:35:00 +00006841 // Define some constants used to index and iterate over the arithemetic types
6842 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006843 // The "promoted arithmetic types" are the arithmetic
6844 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006845 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006846 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006847 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006848 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006849 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006850 LastPromotedArithmeticType = 11;
6851 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006852
Chandler Carruthc6586e52010-12-12 10:35:00 +00006853 /// \brief Get the canonical type for a given arithmetic type index.
6854 CanQualType getArithmeticType(unsigned index) {
6855 assert(index < NumArithmeticTypes);
6856 static CanQualType ASTContext::* const
6857 ArithmeticTypes[NumArithmeticTypes] = {
6858 // Start of promoted types.
6859 &ASTContext::FloatTy,
6860 &ASTContext::DoubleTy,
6861 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006862
Chandler Carruthc6586e52010-12-12 10:35:00 +00006863 // Start of integral types.
6864 &ASTContext::IntTy,
6865 &ASTContext::LongTy,
6866 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006867 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006868 &ASTContext::UnsignedIntTy,
6869 &ASTContext::UnsignedLongTy,
6870 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006871 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006872 // End of promoted types.
6873
6874 &ASTContext::BoolTy,
6875 &ASTContext::CharTy,
6876 &ASTContext::WCharTy,
6877 &ASTContext::Char16Ty,
6878 &ASTContext::Char32Ty,
6879 &ASTContext::SignedCharTy,
6880 &ASTContext::ShortTy,
6881 &ASTContext::UnsignedCharTy,
6882 &ASTContext::UnsignedShortTy,
6883 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006884 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006885 };
6886 return S.Context.*ArithmeticTypes[index];
6887 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006888
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006889 /// \brief Gets the canonical type resulting from the usual arithemetic
6890 /// converions for the given arithmetic types.
6891 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6892 // Accelerator table for performing the usual arithmetic conversions.
6893 // The rules are basically:
6894 // - if either is floating-point, use the wider floating-point
6895 // - if same signedness, use the higher rank
6896 // - if same size, use unsigned of the higher rank
6897 // - use the larger type
6898 // These rules, together with the axiom that higher ranks are
6899 // never smaller, are sufficient to precompute all of these results
6900 // *except* when dealing with signed types of higher rank.
6901 // (we could precompute SLL x UI for all known platforms, but it's
6902 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006903 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006904 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006905 Dep=-1,
6906 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006907 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006908 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006909 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006910/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6911/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6912/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6913/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6914/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6915/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6916/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6917/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6918/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6919/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6920/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006921 };
6922
6923 assert(L < LastPromotedArithmeticType);
6924 assert(R < LastPromotedArithmeticType);
6925 int Idx = ConversionsTable[L][R];
6926
6927 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006928 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006929
6930 // Slow path: we need to compare widths.
6931 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006932 CanQualType LT = getArithmeticType(L),
6933 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006934 unsigned LW = S.Context.getIntWidth(LT),
6935 RW = S.Context.getIntWidth(RT);
6936
6937 // If they're different widths, use the signed type.
6938 if (LW > RW) return LT;
6939 else if (LW < RW) return RT;
6940
6941 // Otherwise, use the unsigned type of the signed type's rank.
6942 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6943 assert(L == SLL || R == SLL);
6944 return S.Context.UnsignedLongLongTy;
6945 }
6946
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006947 /// \brief Helper method to factor out the common pattern of adding overloads
6948 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006949 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006950 bool HasVolatile,
6951 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006952 QualType ParamTypes[2] = {
6953 S.Context.getLValueReferenceType(CandidateTy),
6954 S.Context.IntTy
6955 };
6956
6957 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00006958 if (Args.size() == 1)
6959 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006960 else
Richard Smithe54c3072013-05-05 15:51:06 +00006961 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006962
6963 // Use a heuristic to reduce number of builtin candidates in the set:
6964 // add volatile version only if there are conversions to a volatile type.
6965 if (HasVolatile) {
6966 ParamTypes[0] =
6967 S.Context.getLValueReferenceType(
6968 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00006969 if (Args.size() == 1)
6970 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006971 else
Richard Smithe54c3072013-05-05 15:51:06 +00006972 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006973 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006974
6975 // Add restrict version only if there are conversions to a restrict type
6976 // and our candidate type is a non-restrict-qualified pointer.
6977 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6978 !CandidateTy.isRestrictQualified()) {
6979 ParamTypes[0]
6980 = S.Context.getLValueReferenceType(
6981 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00006982 if (Args.size() == 1)
6983 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006984 else
Richard Smithe54c3072013-05-05 15:51:06 +00006985 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006986
6987 if (HasVolatile) {
6988 ParamTypes[0]
6989 = S.Context.getLValueReferenceType(
6990 S.Context.getCVRQualifiedType(CandidateTy,
6991 (Qualifiers::Volatile |
6992 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00006993 if (Args.size() == 1)
6994 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006995 else
Richard Smithe54c3072013-05-05 15:51:06 +00006996 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006997 }
6998 }
6999
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007000 }
7001
7002public:
7003 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007004 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007005 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007006 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007007 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007008 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007009 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007010 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007011 HasArithmeticOrEnumeralCandidateType(
7012 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007013 CandidateTypes(CandidateTypes),
7014 CandidateSet(CandidateSet) {
7015 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007016 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007017 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007018 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007019 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007020 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007021 assert(getArithmeticType(FirstPromotedArithmeticType)
7022 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007023 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007024 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007025 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007026 "Invalid last promoted arithmetic type");
7027 }
7028
7029 // C++ [over.built]p3:
7030 //
7031 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7032 // is either volatile or empty, there exist candidate operator
7033 // functions of the form
7034 //
7035 // VQ T& operator++(VQ T&);
7036 // T operator++(VQ T&, int);
7037 //
7038 // C++ [over.built]p4:
7039 //
7040 // For every pair (T, VQ), where T is an arithmetic type other
7041 // than bool, and VQ is either volatile or empty, there exist
7042 // candidate operator functions of the form
7043 //
7044 // VQ T& operator--(VQ T&);
7045 // T operator--(VQ T&, int);
7046 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007047 if (!HasArithmeticOrEnumeralCandidateType)
7048 return;
7049
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007050 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7051 Arith < NumArithmeticTypes; ++Arith) {
7052 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007053 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007054 VisibleTypeConversionsQuals.hasVolatile(),
7055 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007056 }
7057 }
7058
7059 // C++ [over.built]p5:
7060 //
7061 // For every pair (T, VQ), where T is a cv-qualified or
7062 // cv-unqualified object type, and VQ is either volatile or
7063 // empty, there exist candidate operator functions of the form
7064 //
7065 // T*VQ& operator++(T*VQ&);
7066 // T*VQ& operator--(T*VQ&);
7067 // T* operator++(T*VQ&, int);
7068 // T* operator--(T*VQ&, int);
7069 void addPlusPlusMinusMinusPointerOverloads() {
7070 for (BuiltinCandidateTypeSet::iterator
7071 Ptr = CandidateTypes[0].pointer_begin(),
7072 PtrEnd = CandidateTypes[0].pointer_end();
7073 Ptr != PtrEnd; ++Ptr) {
7074 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007075 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007076 continue;
7077
7078 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007079 (!(*Ptr).isVolatileQualified() &&
7080 VisibleTypeConversionsQuals.hasVolatile()),
7081 (!(*Ptr).isRestrictQualified() &&
7082 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007083 }
7084 }
7085
7086 // C++ [over.built]p6:
7087 // For every cv-qualified or cv-unqualified object type T, there
7088 // exist candidate operator functions of the form
7089 //
7090 // T& operator*(T*);
7091 //
7092 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007094 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007095 // T& operator*(T*);
7096 void addUnaryStarPointerOverloads() {
7097 for (BuiltinCandidateTypeSet::iterator
7098 Ptr = CandidateTypes[0].pointer_begin(),
7099 PtrEnd = CandidateTypes[0].pointer_end();
7100 Ptr != PtrEnd; ++Ptr) {
7101 QualType ParamTy = *Ptr;
7102 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007103 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7104 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007105
Douglas Gregor02824322011-01-26 19:30:28 +00007106 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7107 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7108 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007109
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007110 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007111 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007112 }
7113 }
7114
7115 // C++ [over.built]p9:
7116 // For every promoted arithmetic type T, there exist candidate
7117 // operator functions of the form
7118 //
7119 // T operator+(T);
7120 // T operator-(T);
7121 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007122 if (!HasArithmeticOrEnumeralCandidateType)
7123 return;
7124
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007125 for (unsigned Arith = FirstPromotedArithmeticType;
7126 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007127 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007128 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007129 }
7130
7131 // Extension: We also add these operators for vector types.
7132 for (BuiltinCandidateTypeSet::iterator
7133 Vec = CandidateTypes[0].vector_begin(),
7134 VecEnd = CandidateTypes[0].vector_end();
7135 Vec != VecEnd; ++Vec) {
7136 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007137 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007138 }
7139 }
7140
7141 // C++ [over.built]p8:
7142 // For every type T, there exist candidate operator functions of
7143 // the form
7144 //
7145 // T* operator+(T*);
7146 void addUnaryPlusPointerOverloads() {
7147 for (BuiltinCandidateTypeSet::iterator
7148 Ptr = CandidateTypes[0].pointer_begin(),
7149 PtrEnd = CandidateTypes[0].pointer_end();
7150 Ptr != PtrEnd; ++Ptr) {
7151 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007152 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007153 }
7154 }
7155
7156 // C++ [over.built]p10:
7157 // For every promoted integral type T, there exist candidate
7158 // operator functions of the form
7159 //
7160 // T operator~(T);
7161 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007162 if (!HasArithmeticOrEnumeralCandidateType)
7163 return;
7164
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007165 for (unsigned Int = FirstPromotedIntegralType;
7166 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007167 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007168 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007169 }
7170
7171 // Extension: We also add this operator for vector types.
7172 for (BuiltinCandidateTypeSet::iterator
7173 Vec = CandidateTypes[0].vector_begin(),
7174 VecEnd = CandidateTypes[0].vector_end();
7175 Vec != VecEnd; ++Vec) {
7176 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007177 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007178 }
7179 }
7180
7181 // C++ [over.match.oper]p16:
7182 // For every pointer to member type T, there exist candidate operator
7183 // functions of the form
7184 //
7185 // bool operator==(T,T);
7186 // bool operator!=(T,T);
7187 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7188 /// Set of (canonical) types that we've already handled.
7189 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7190
Richard Smithe54c3072013-05-05 15:51:06 +00007191 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007192 for (BuiltinCandidateTypeSet::iterator
7193 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7194 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7195 MemPtr != MemPtrEnd;
7196 ++MemPtr) {
7197 // Don't add the same builtin candidate twice.
7198 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7199 continue;
7200
7201 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007202 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007203 }
7204 }
7205 }
7206
7207 // C++ [over.built]p15:
7208 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007209 // For every T, where T is an enumeration type, a pointer type, or
7210 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007211 //
7212 // bool operator<(T, T);
7213 // bool operator>(T, T);
7214 // bool operator<=(T, T);
7215 // bool operator>=(T, T);
7216 // bool operator==(T, T);
7217 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007218 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007219 // C++ [over.match.oper]p3:
7220 // [...]the built-in candidates include all of the candidate operator
7221 // functions defined in 13.6 that, compared to the given operator, [...]
7222 // do not have the same parameter-type-list as any non-template non-member
7223 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007224 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007225 // Note that in practice, this only affects enumeration types because there
7226 // aren't any built-in candidates of record type, and a user-defined operator
7227 // must have an operand of record or enumeration type. Also, the only other
7228 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007229 // cannot be overloaded for enumeration types, so this is the only place
7230 // where we must suppress candidates like this.
7231 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7232 UserDefinedBinaryOperators;
7233
Richard Smithe54c3072013-05-05 15:51:06 +00007234 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007235 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7236 CandidateTypes[ArgIdx].enumeration_end()) {
7237 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7238 CEnd = CandidateSet.end();
7239 C != CEnd; ++C) {
7240 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7241 continue;
7242
Eli Friedman14f082b2012-09-18 21:52:24 +00007243 if (C->Function->isFunctionTemplateSpecialization())
7244 continue;
7245
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007246 QualType FirstParamType =
7247 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7248 QualType SecondParamType =
7249 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7250
7251 // Skip if either parameter isn't of enumeral type.
7252 if (!FirstParamType->isEnumeralType() ||
7253 !SecondParamType->isEnumeralType())
7254 continue;
7255
7256 // Add this operator to the set of known user-defined operators.
7257 UserDefinedBinaryOperators.insert(
7258 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7259 S.Context.getCanonicalType(SecondParamType)));
7260 }
7261 }
7262 }
7263
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007264 /// Set of (canonical) types that we've already handled.
7265 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7266
Richard Smithe54c3072013-05-05 15:51:06 +00007267 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007268 for (BuiltinCandidateTypeSet::iterator
7269 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7270 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7271 Ptr != PtrEnd; ++Ptr) {
7272 // Don't add the same builtin candidate twice.
7273 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7274 continue;
7275
7276 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007277 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007278 }
7279 for (BuiltinCandidateTypeSet::iterator
7280 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7281 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7282 Enum != EnumEnd; ++Enum) {
7283 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7284
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007285 // Don't add the same builtin candidate twice, or if a user defined
7286 // candidate exists.
7287 if (!AddedTypes.insert(CanonType) ||
7288 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7289 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007290 continue;
7291
7292 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007293 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007294 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007295
7296 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7297 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7298 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007299 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007300 NullPtrTy))) {
7301 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007302 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007303 CandidateSet);
7304 }
7305 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007306 }
7307 }
7308
7309 // C++ [over.built]p13:
7310 //
7311 // For every cv-qualified or cv-unqualified object type T
7312 // there exist candidate operator functions of the form
7313 //
7314 // T* operator+(T*, ptrdiff_t);
7315 // T& operator[](T*, ptrdiff_t); [BELOW]
7316 // T* operator-(T*, ptrdiff_t);
7317 // T* operator+(ptrdiff_t, T*);
7318 // T& operator[](ptrdiff_t, T*); [BELOW]
7319 //
7320 // C++ [over.built]p14:
7321 //
7322 // For every T, where T is a pointer to object type, there
7323 // exist candidate operator functions of the form
7324 //
7325 // ptrdiff_t operator-(T, T);
7326 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7327 /// Set of (canonical) types that we've already handled.
7328 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7329
7330 for (int Arg = 0; Arg < 2; ++Arg) {
7331 QualType AsymetricParamTypes[2] = {
7332 S.Context.getPointerDiffType(),
7333 S.Context.getPointerDiffType(),
7334 };
7335 for (BuiltinCandidateTypeSet::iterator
7336 Ptr = CandidateTypes[Arg].pointer_begin(),
7337 PtrEnd = CandidateTypes[Arg].pointer_end();
7338 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007339 QualType PointeeTy = (*Ptr)->getPointeeType();
7340 if (!PointeeTy->isObjectType())
7341 continue;
7342
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007343 AsymetricParamTypes[Arg] = *Ptr;
7344 if (Arg == 0 || Op == OO_Plus) {
7345 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7346 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007347 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007348 }
7349 if (Op == OO_Minus) {
7350 // ptrdiff_t operator-(T, T);
7351 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7352 continue;
7353
7354 QualType ParamTypes[2] = { *Ptr, *Ptr };
7355 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007356 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007357 }
7358 }
7359 }
7360 }
7361
7362 // C++ [over.built]p12:
7363 //
7364 // For every pair of promoted arithmetic types L and R, there
7365 // exist candidate operator functions of the form
7366 //
7367 // LR operator*(L, R);
7368 // LR operator/(L, R);
7369 // LR operator+(L, R);
7370 // LR operator-(L, R);
7371 // bool operator<(L, R);
7372 // bool operator>(L, R);
7373 // bool operator<=(L, R);
7374 // bool operator>=(L, R);
7375 // bool operator==(L, R);
7376 // bool operator!=(L, R);
7377 //
7378 // where LR is the result of the usual arithmetic conversions
7379 // between types L and R.
7380 //
7381 // C++ [over.built]p24:
7382 //
7383 // For every pair of promoted arithmetic types L and R, there exist
7384 // candidate operator functions of the form
7385 //
7386 // LR operator?(bool, L, R);
7387 //
7388 // where LR is the result of the usual arithmetic conversions
7389 // between types L and R.
7390 // Our candidates ignore the first parameter.
7391 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007392 if (!HasArithmeticOrEnumeralCandidateType)
7393 return;
7394
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007395 for (unsigned Left = FirstPromotedArithmeticType;
7396 Left < LastPromotedArithmeticType; ++Left) {
7397 for (unsigned Right = FirstPromotedArithmeticType;
7398 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007399 QualType LandR[2] = { getArithmeticType(Left),
7400 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007401 QualType Result =
7402 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007403 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007404 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007405 }
7406 }
7407
7408 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7409 // conditional operator for vector types.
7410 for (BuiltinCandidateTypeSet::iterator
7411 Vec1 = CandidateTypes[0].vector_begin(),
7412 Vec1End = CandidateTypes[0].vector_end();
7413 Vec1 != Vec1End; ++Vec1) {
7414 for (BuiltinCandidateTypeSet::iterator
7415 Vec2 = CandidateTypes[1].vector_begin(),
7416 Vec2End = CandidateTypes[1].vector_end();
7417 Vec2 != Vec2End; ++Vec2) {
7418 QualType LandR[2] = { *Vec1, *Vec2 };
7419 QualType Result = S.Context.BoolTy;
7420 if (!isComparison) {
7421 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7422 Result = *Vec1;
7423 else
7424 Result = *Vec2;
7425 }
7426
Richard Smithe54c3072013-05-05 15:51:06 +00007427 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007428 }
7429 }
7430 }
7431
7432 // C++ [over.built]p17:
7433 //
7434 // For every pair of promoted integral types L and R, there
7435 // exist candidate operator functions of the form
7436 //
7437 // LR operator%(L, R);
7438 // LR operator&(L, R);
7439 // LR operator^(L, R);
7440 // LR operator|(L, R);
7441 // L operator<<(L, R);
7442 // L operator>>(L, R);
7443 //
7444 // where LR is the result of the usual arithmetic conversions
7445 // between types L and R.
7446 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007447 if (!HasArithmeticOrEnumeralCandidateType)
7448 return;
7449
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007450 for (unsigned Left = FirstPromotedIntegralType;
7451 Left < LastPromotedIntegralType; ++Left) {
7452 for (unsigned Right = FirstPromotedIntegralType;
7453 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007454 QualType LandR[2] = { getArithmeticType(Left),
7455 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007456 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7457 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007458 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007459 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007460 }
7461 }
7462 }
7463
7464 // C++ [over.built]p20:
7465 //
7466 // For every pair (T, VQ), where T is an enumeration or
7467 // pointer to member type and VQ is either volatile or
7468 // empty, there exist candidate operator functions of the form
7469 //
7470 // VQ T& operator=(VQ T&, T);
7471 void addAssignmentMemberPointerOrEnumeralOverloads() {
7472 /// Set of (canonical) types that we've already handled.
7473 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7474
7475 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7476 for (BuiltinCandidateTypeSet::iterator
7477 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7478 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7479 Enum != EnumEnd; ++Enum) {
7480 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7481 continue;
7482
Richard Smithe54c3072013-05-05 15:51:06 +00007483 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007484 }
7485
7486 for (BuiltinCandidateTypeSet::iterator
7487 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7488 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7489 MemPtr != MemPtrEnd; ++MemPtr) {
7490 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7491 continue;
7492
Richard Smithe54c3072013-05-05 15:51:06 +00007493 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007494 }
7495 }
7496 }
7497
7498 // C++ [over.built]p19:
7499 //
7500 // For every pair (T, VQ), where T is any type and VQ is either
7501 // volatile or empty, there exist candidate operator functions
7502 // of the form
7503 //
7504 // T*VQ& operator=(T*VQ&, T*);
7505 //
7506 // C++ [over.built]p21:
7507 //
7508 // For every pair (T, VQ), where T is a cv-qualified or
7509 // cv-unqualified object type and VQ is either volatile or
7510 // empty, there exist candidate operator functions of the form
7511 //
7512 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7513 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7514 void addAssignmentPointerOverloads(bool isEqualOp) {
7515 /// Set of (canonical) types that we've already handled.
7516 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7517
7518 for (BuiltinCandidateTypeSet::iterator
7519 Ptr = CandidateTypes[0].pointer_begin(),
7520 PtrEnd = CandidateTypes[0].pointer_end();
7521 Ptr != PtrEnd; ++Ptr) {
7522 // If this is operator=, keep track of the builtin candidates we added.
7523 if (isEqualOp)
7524 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007525 else if (!(*Ptr)->getPointeeType()->isObjectType())
7526 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007527
7528 // non-volatile version
7529 QualType ParamTypes[2] = {
7530 S.Context.getLValueReferenceType(*Ptr),
7531 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7532 };
Richard Smithe54c3072013-05-05 15:51:06 +00007533 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007534 /*IsAssigmentOperator=*/ isEqualOp);
7535
Douglas Gregor5bee2582012-06-04 00:15:09 +00007536 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7537 VisibleTypeConversionsQuals.hasVolatile();
7538 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007539 // volatile version
7540 ParamTypes[0] =
7541 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
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
7546 if (!(*Ptr).isRestrictQualified() &&
7547 VisibleTypeConversionsQuals.hasRestrict()) {
7548 // restrict version
7549 ParamTypes[0]
7550 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007551 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007552 /*IsAssigmentOperator=*/isEqualOp);
7553
7554 if (NeedVolatile) {
7555 // volatile restrict version
7556 ParamTypes[0]
7557 = S.Context.getLValueReferenceType(
7558 S.Context.getCVRQualifiedType(*Ptr,
7559 (Qualifiers::Volatile |
7560 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007561 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007562 /*IsAssigmentOperator=*/isEqualOp);
7563 }
7564 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007565 }
7566
7567 if (isEqualOp) {
7568 for (BuiltinCandidateTypeSet::iterator
7569 Ptr = CandidateTypes[1].pointer_begin(),
7570 PtrEnd = CandidateTypes[1].pointer_end();
7571 Ptr != PtrEnd; ++Ptr) {
7572 // Make sure we don't add the same candidate twice.
7573 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7574 continue;
7575
Chandler Carruth8e543b32010-12-12 08:17:55 +00007576 QualType ParamTypes[2] = {
7577 S.Context.getLValueReferenceType(*Ptr),
7578 *Ptr,
7579 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007580
7581 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007582 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007583 /*IsAssigmentOperator=*/true);
7584
Douglas Gregor5bee2582012-06-04 00:15:09 +00007585 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7586 VisibleTypeConversionsQuals.hasVolatile();
7587 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007588 // volatile version
7589 ParamTypes[0] =
7590 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007591 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7592 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007593 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007594
7595 if (!(*Ptr).isRestrictQualified() &&
7596 VisibleTypeConversionsQuals.hasRestrict()) {
7597 // restrict version
7598 ParamTypes[0]
7599 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007600 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7601 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007602
7603 if (NeedVolatile) {
7604 // volatile restrict version
7605 ParamTypes[0]
7606 = S.Context.getLValueReferenceType(
7607 S.Context.getCVRQualifiedType(*Ptr,
7608 (Qualifiers::Volatile |
7609 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007610 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7611 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007612 }
7613 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007614 }
7615 }
7616 }
7617
7618 // C++ [over.built]p18:
7619 //
7620 // For every triple (L, VQ, R), where L is an arithmetic type,
7621 // VQ is either volatile or empty, and R is a promoted
7622 // arithmetic type, there exist candidate operator functions of
7623 // the form
7624 //
7625 // VQ L& operator=(VQ L&, R);
7626 // VQ L& operator*=(VQ L&, R);
7627 // VQ L& operator/=(VQ L&, R);
7628 // VQ L& operator+=(VQ L&, R);
7629 // VQ L& operator-=(VQ L&, R);
7630 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007631 if (!HasArithmeticOrEnumeralCandidateType)
7632 return;
7633
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007634 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7635 for (unsigned Right = FirstPromotedArithmeticType;
7636 Right < LastPromotedArithmeticType; ++Right) {
7637 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007638 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007639
7640 // Add this built-in operator as a candidate (VQ is empty).
7641 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007642 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007643 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007644 /*IsAssigmentOperator=*/isEqualOp);
7645
7646 // Add this built-in operator as a candidate (VQ is 'volatile').
7647 if (VisibleTypeConversionsQuals.hasVolatile()) {
7648 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007649 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007650 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007651 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007652 /*IsAssigmentOperator=*/isEqualOp);
7653 }
7654 }
7655 }
7656
7657 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7658 for (BuiltinCandidateTypeSet::iterator
7659 Vec1 = CandidateTypes[0].vector_begin(),
7660 Vec1End = CandidateTypes[0].vector_end();
7661 Vec1 != Vec1End; ++Vec1) {
7662 for (BuiltinCandidateTypeSet::iterator
7663 Vec2 = CandidateTypes[1].vector_begin(),
7664 Vec2End = CandidateTypes[1].vector_end();
7665 Vec2 != Vec2End; ++Vec2) {
7666 QualType ParamTypes[2];
7667 ParamTypes[1] = *Vec2;
7668 // Add this built-in operator as a candidate (VQ is empty).
7669 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007670 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007671 /*IsAssigmentOperator=*/isEqualOp);
7672
7673 // Add this built-in operator as a candidate (VQ is 'volatile').
7674 if (VisibleTypeConversionsQuals.hasVolatile()) {
7675 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7676 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007677 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007678 /*IsAssigmentOperator=*/isEqualOp);
7679 }
7680 }
7681 }
7682 }
7683
7684 // C++ [over.built]p22:
7685 //
7686 // For every triple (L, VQ, R), where L is an integral type, VQ
7687 // is either volatile or empty, and R is a promoted integral
7688 // type, there exist candidate operator functions of the form
7689 //
7690 // VQ L& operator%=(VQ L&, R);
7691 // VQ L& operator<<=(VQ L&, R);
7692 // VQ L& operator>>=(VQ L&, R);
7693 // VQ L& operator&=(VQ L&, R);
7694 // VQ L& operator^=(VQ L&, R);
7695 // VQ L& operator|=(VQ L&, R);
7696 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007697 if (!HasArithmeticOrEnumeralCandidateType)
7698 return;
7699
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007700 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7701 for (unsigned Right = FirstPromotedIntegralType;
7702 Right < LastPromotedIntegralType; ++Right) {
7703 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007704 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007705
7706 // Add this built-in operator as a candidate (VQ is empty).
7707 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007708 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007709 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007710 if (VisibleTypeConversionsQuals.hasVolatile()) {
7711 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007712 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007713 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7714 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007715 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007716 }
7717 }
7718 }
7719 }
7720
7721 // C++ [over.operator]p23:
7722 //
7723 // There also exist candidate operator functions of the form
7724 //
7725 // bool operator!(bool);
7726 // bool operator&&(bool, bool);
7727 // bool operator||(bool, bool);
7728 void addExclaimOverload() {
7729 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007730 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007731 /*IsAssignmentOperator=*/false,
7732 /*NumContextualBoolArguments=*/1);
7733 }
7734 void addAmpAmpOrPipePipeOverload() {
7735 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007736 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007737 /*IsAssignmentOperator=*/false,
7738 /*NumContextualBoolArguments=*/2);
7739 }
7740
7741 // C++ [over.built]p13:
7742 //
7743 // For every cv-qualified or cv-unqualified object type T there
7744 // exist candidate operator functions of the form
7745 //
7746 // T* operator+(T*, ptrdiff_t); [ABOVE]
7747 // T& operator[](T*, ptrdiff_t);
7748 // T* operator-(T*, ptrdiff_t); [ABOVE]
7749 // T* operator+(ptrdiff_t, T*); [ABOVE]
7750 // T& operator[](ptrdiff_t, T*);
7751 void addSubscriptOverloads() {
7752 for (BuiltinCandidateTypeSet::iterator
7753 Ptr = CandidateTypes[0].pointer_begin(),
7754 PtrEnd = CandidateTypes[0].pointer_end();
7755 Ptr != PtrEnd; ++Ptr) {
7756 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7757 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007758 if (!PointeeType->isObjectType())
7759 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007760
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007761 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7762
7763 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007764 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007765 }
7766
7767 for (BuiltinCandidateTypeSet::iterator
7768 Ptr = CandidateTypes[1].pointer_begin(),
7769 PtrEnd = CandidateTypes[1].pointer_end();
7770 Ptr != PtrEnd; ++Ptr) {
7771 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7772 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007773 if (!PointeeType->isObjectType())
7774 continue;
7775
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007776 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7777
7778 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007779 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007780 }
7781 }
7782
7783 // C++ [over.built]p11:
7784 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7785 // C1 is the same type as C2 or is a derived class of C2, T is an object
7786 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7787 // there exist candidate operator functions of the form
7788 //
7789 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7790 //
7791 // where CV12 is the union of CV1 and CV2.
7792 void addArrowStarOverloads() {
7793 for (BuiltinCandidateTypeSet::iterator
7794 Ptr = CandidateTypes[0].pointer_begin(),
7795 PtrEnd = CandidateTypes[0].pointer_end();
7796 Ptr != PtrEnd; ++Ptr) {
7797 QualType C1Ty = (*Ptr);
7798 QualType C1;
7799 QualifierCollector Q1;
7800 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7801 if (!isa<RecordType>(C1))
7802 continue;
7803 // heuristic to reduce number of builtin candidates in the set.
7804 // Add volatile/restrict version only if there are conversions to a
7805 // volatile/restrict type.
7806 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7807 continue;
7808 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7809 continue;
7810 for (BuiltinCandidateTypeSet::iterator
7811 MemPtr = CandidateTypes[1].member_pointer_begin(),
7812 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7813 MemPtr != MemPtrEnd; ++MemPtr) {
7814 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7815 QualType C2 = QualType(mptr->getClass(), 0);
7816 C2 = C2.getUnqualifiedType();
7817 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7818 break;
7819 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7820 // build CV12 T&
7821 QualType T = mptr->getPointeeType();
7822 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7823 T.isVolatileQualified())
7824 continue;
7825 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7826 T.isRestrictQualified())
7827 continue;
7828 T = Q1.apply(S.Context, T);
7829 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007830 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007831 }
7832 }
7833 }
7834
7835 // Note that we don't consider the first argument, since it has been
7836 // contextually converted to bool long ago. The candidates below are
7837 // therefore added as binary.
7838 //
7839 // C++ [over.built]p25:
7840 // For every type T, where T is a pointer, pointer-to-member, or scoped
7841 // enumeration type, there exist candidate operator functions of the form
7842 //
7843 // T operator?(bool, T, T);
7844 //
7845 void addConditionalOperatorOverloads() {
7846 /// Set of (canonical) types that we've already handled.
7847 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7848
7849 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7850 for (BuiltinCandidateTypeSet::iterator
7851 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7852 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7853 Ptr != PtrEnd; ++Ptr) {
7854 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7855 continue;
7856
7857 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007858 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007859 }
7860
7861 for (BuiltinCandidateTypeSet::iterator
7862 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7863 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7864 MemPtr != MemPtrEnd; ++MemPtr) {
7865 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7866 continue;
7867
7868 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007869 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007870 }
7871
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007872 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007873 for (BuiltinCandidateTypeSet::iterator
7874 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7875 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7876 Enum != EnumEnd; ++Enum) {
7877 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7878 continue;
7879
7880 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7881 continue;
7882
7883 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007884 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007885 }
7886 }
7887 }
7888 }
7889};
7890
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007891} // end anonymous namespace
7892
7893/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7894/// operator overloads to the candidate set (C++ [over.built]), based
7895/// on the operator @p Op and the arguments given. For example, if the
7896/// operator is a binary '+', this routine might add "int
7897/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00007898void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7899 SourceLocation OpLoc,
7900 ArrayRef<Expr *> Args,
7901 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007902 // Find all of the types that the arguments can convert to, but only
7903 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007904 // that make use of these types. Also record whether we encounter non-record
7905 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007906 Qualifiers VisibleTypeConversionsQuals;
7907 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00007908 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007909 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007910
7911 bool HasNonRecordCandidateType = false;
7912 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007913 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00007914 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007915 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7916 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7917 OpLoc,
7918 true,
7919 (Op == OO_Exclaim ||
7920 Op == OO_AmpAmp ||
7921 Op == OO_PipePipe),
7922 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007923 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7924 CandidateTypes[ArgIdx].hasNonRecordTypes();
7925 HasArithmeticOrEnumeralCandidateType =
7926 HasArithmeticOrEnumeralCandidateType ||
7927 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007928 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007929
Chandler Carruth00a38332010-12-13 01:44:01 +00007930 // Exit early when no non-record types have been added to the candidate set
7931 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007932 //
7933 // We can't exit early for !, ||, or &&, since there we have always have
7934 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007935 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007936 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007937 return;
7938
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007939 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007940 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007941 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007942 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007943 CandidateTypes, CandidateSet);
7944
7945 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007946 switch (Op) {
7947 case OO_None:
7948 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007949 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007950
Chandler Carruth5184de02010-12-12 08:51:33 +00007951 case OO_New:
7952 case OO_Delete:
7953 case OO_Array_New:
7954 case OO_Array_Delete:
7955 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007956 llvm_unreachable(
7957 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007958
7959 case OO_Comma:
7960 case OO_Arrow:
7961 // C++ [over.match.oper]p3:
7962 // -- For the operator ',', the unary operator '&', or the
7963 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007964 break;
7965
7966 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007967 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007968 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007969 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007970
7971 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007972 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007973 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007974 } else {
7975 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7976 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7977 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007978 break;
7979
Chandler Carruth5184de02010-12-12 08:51:33 +00007980 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007981 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007982 OpBuilder.addUnaryStarPointerOverloads();
7983 else
7984 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7985 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007986
Chandler Carruth5184de02010-12-12 08:51:33 +00007987 case OO_Slash:
7988 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007989 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007990
7991 case OO_PlusPlus:
7992 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7994 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007995 break;
7996
Douglas Gregor84605ae2009-08-24 13:43:27 +00007997 case OO_EqualEqual:
7998 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007999 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008000 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008001
Douglas Gregora11693b2008-11-12 17:17:38 +00008002 case OO_Less:
8003 case OO_Greater:
8004 case OO_LessEqual:
8005 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008006 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008007 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8008 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008009
Douglas Gregora11693b2008-11-12 17:17:38 +00008010 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008011 case OO_Caret:
8012 case OO_Pipe:
8013 case OO_LessLess:
8014 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008015 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008016 break;
8017
Chandler Carruth5184de02010-12-12 08:51:33 +00008018 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008019 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008020 // C++ [over.match.oper]p3:
8021 // -- For the operator ',', the unary operator '&', or the
8022 // operator '->', the built-in candidates set is empty.
8023 break;
8024
8025 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8026 break;
8027
8028 case OO_Tilde:
8029 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8030 break;
8031
Douglas Gregora11693b2008-11-12 17:17:38 +00008032 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008033 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008034 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008035
8036 case OO_PlusEqual:
8037 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008038 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008039 // Fall through.
8040
8041 case OO_StarEqual:
8042 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008043 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008044 break;
8045
8046 case OO_PercentEqual:
8047 case OO_LessLessEqual:
8048 case OO_GreaterGreaterEqual:
8049 case OO_AmpEqual:
8050 case OO_CaretEqual:
8051 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008052 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008053 break;
8054
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008055 case OO_Exclaim:
8056 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008057 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008058
Douglas Gregora11693b2008-11-12 17:17:38 +00008059 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008060 case OO_PipePipe:
8061 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008062 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008063
8064 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008065 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008066 break;
8067
8068 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008069 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008070 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008071
8072 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008073 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008074 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8075 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008076 }
8077}
8078
Douglas Gregore254f902009-02-04 00:32:51 +00008079/// \brief Add function candidates found via argument-dependent lookup
8080/// to the set of overloading candidates.
8081///
8082/// This routine performs argument-dependent name lookup based on the
8083/// given function name (which may also be an operator name) and adds
8084/// all of the overload candidates found by ADL to the overload
8085/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008086void
Douglas Gregore254f902009-02-04 00:32:51 +00008087Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00008088 bool Operator, SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008089 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008090 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008091 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008092 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008093 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008094
John McCall91f61fc2010-01-26 06:04:06 +00008095 // FIXME: This approach for uniquing ADL results (and removing
8096 // redundant candidates from the set) relies on pointer-equality,
8097 // which means we need to key off the canonical decl. However,
8098 // always going back to the canonical decl might not get us the
8099 // right set of default arguments. What default arguments are
8100 // we supposed to consider on ADL candidates, anyway?
8101
Douglas Gregorcabea402009-09-22 15:41:20 +00008102 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00008103 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008104
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008105 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008106 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8107 CandEnd = CandidateSet.end();
8108 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008109 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008110 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008111 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008112 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008113 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008114
8115 // For each of the ADL candidates we found, add it to the overload
8116 // set.
John McCall8fe68082010-01-26 07:16:45 +00008117 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008118 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008119 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008120 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008121 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008122
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008123 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8124 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008125 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008126 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008127 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008128 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008129 }
Douglas Gregore254f902009-02-04 00:32:51 +00008130}
8131
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008132/// isBetterOverloadCandidate - Determines whether the first overload
8133/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008134bool
John McCall5c32be02010-08-24 20:38:10 +00008135isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008136 const OverloadCandidate &Cand1,
8137 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008138 SourceLocation Loc,
8139 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008140 // Define viable functions to be better candidates than non-viable
8141 // functions.
8142 if (!Cand2.Viable)
8143 return Cand1.Viable;
8144 else if (!Cand1.Viable)
8145 return false;
8146
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008147 // C++ [over.match.best]p1:
8148 //
8149 // -- if F is a static member function, ICS1(F) is defined such
8150 // that ICS1(F) is neither better nor worse than ICS1(G) for
8151 // any function G, and, symmetrically, ICS1(G) is neither
8152 // better nor worse than ICS1(F).
8153 unsigned StartArg = 0;
8154 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8155 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008156
Douglas Gregord3cb3562009-07-07 23:38:56 +00008157 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008158 // A viable function F1 is defined to be a better function than another
8159 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008160 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008161 unsigned NumArgs = Cand1.NumConversions;
8162 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008163 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008164 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008165 switch (CompareImplicitConversionSequences(S,
8166 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008167 Cand2.Conversions[ArgIdx])) {
8168 case ImplicitConversionSequence::Better:
8169 // Cand1 has a better conversion sequence.
8170 HasBetterConversion = true;
8171 break;
8172
8173 case ImplicitConversionSequence::Worse:
8174 // Cand1 can't be better than Cand2.
8175 return false;
8176
8177 case ImplicitConversionSequence::Indistinguishable:
8178 // Do nothing.
8179 break;
8180 }
8181 }
8182
Mike Stump11289f42009-09-09 15:08:12 +00008183 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008184 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008185 if (HasBetterConversion)
8186 return true;
8187
Mike Stump11289f42009-09-09 15:08:12 +00008188 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00008189 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00008190 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00008191 Cand2.Function && Cand2.Function->getPrimaryTemplate())
8192 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008193
8194 // -- F1 and F2 are function template specializations, and the function
8195 // template for F1 is more specialized than the template for F2
8196 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00008197 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00008198 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00008199 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00008200 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00008201 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8202 Cand2.Function->getPrimaryTemplate(),
8203 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008204 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00008205 : TPOC_Call,
Richard Smithe5b52202013-09-11 00:52:39 +00008206 Cand1.ExplicitCallArguments,
8207 Cand2.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00008208 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00008209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008210
Douglas Gregora1f013e2008-11-07 22:36:19 +00008211 // -- the context is an initialization by user-defined conversion
8212 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8213 // from the return type of F1 to the destination type (i.e.,
8214 // the type of the entity being initialized) is a better
8215 // conversion sequence than the standard conversion sequence
8216 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008217 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008218 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008219 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008220 // First check whether we prefer one of the conversion functions over the
8221 // other. This only distinguishes the results in non-standard, extension
8222 // cases such as the conversion from a lambda closure type to a function
8223 // pointer or block.
8224 ImplicitConversionSequence::CompareKind FuncResult
8225 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8226 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8227 return FuncResult;
8228
John McCall5c32be02010-08-24 20:38:10 +00008229 switch (CompareStandardConversionSequences(S,
8230 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00008231 Cand2.FinalConversion)) {
8232 case ImplicitConversionSequence::Better:
8233 // Cand1 has a better conversion sequence.
8234 return true;
8235
8236 case ImplicitConversionSequence::Worse:
8237 // Cand1 can't be better than Cand2.
8238 return false;
8239
8240 case ImplicitConversionSequence::Indistinguishable:
8241 // Do nothing
8242 break;
8243 }
8244 }
8245
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008246 // Check for enable_if value-based overload resolution.
8247 if (Cand1.Function && Cand2.Function &&
8248 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8249 Cand2.Function->hasAttr<EnableIfAttr>())) {
8250 // FIXME: The next several lines are just
8251 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8252 // instead of reverse order which is how they're stored in the AST.
8253 AttrVec Cand1Attrs;
8254 AttrVec::iterator Cand1E = Cand1Attrs.end();
8255 if (Cand1.Function->hasAttrs()) {
8256 Cand1Attrs = Cand1.Function->getAttrs();
8257 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8258 IsNotEnableIfAttr);
8259 std::reverse(Cand1Attrs.begin(), Cand1E);
8260 }
8261
8262 AttrVec Cand2Attrs;
8263 AttrVec::iterator Cand2E = Cand2Attrs.end();
8264 if (Cand2.Function->hasAttrs()) {
8265 Cand2Attrs = Cand2.Function->getAttrs();
8266 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8267 IsNotEnableIfAttr);
8268 std::reverse(Cand2Attrs.begin(), Cand2E);
8269 }
8270 for (AttrVec::iterator
8271 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin();
8272 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) {
8273 if (Cand1I == Cand1E)
8274 return false;
8275 if (Cand2I == Cand2E)
8276 return true;
8277 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8278 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID,
8279 S.getASTContext(), true);
8280 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID,
8281 S.getASTContext(), true);
Nick Lewyckyd950ae72014-01-21 01:30:30 +00008282 if (Cand1ID != Cand2ID)
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008283 return false;
8284 }
8285 }
8286
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008287 return false;
8288}
8289
Mike Stump11289f42009-09-09 15:08:12 +00008290/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008291/// within an overload candidate set.
8292///
James Dennettffad8b72012-06-22 08:10:18 +00008293/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008294/// which overload resolution occurs.
8295///
James Dennettffad8b72012-06-22 08:10:18 +00008296/// \param Best If overload resolution was successful or found a deleted
8297/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008298///
8299/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008300OverloadingResult
8301OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008302 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008303 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008304 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008305 Best = end();
8306 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8307 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008308 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008309 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008310 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008311 }
8312
8313 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008314 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008315 return OR_No_Viable_Function;
8316
8317 // Make sure that this function is better than every other viable
8318 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008319 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008320 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008321 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008322 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008323 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008324 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008325 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008326 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008327 }
Mike Stump11289f42009-09-09 15:08:12 +00008328
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008329 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008330 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008331 (Best->Function->isDeleted() ||
8332 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008333 return OR_Deleted;
8334
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008335 return OR_Success;
8336}
8337
John McCall53262c92010-01-12 02:15:36 +00008338namespace {
8339
8340enum OverloadCandidateKind {
8341 oc_function,
8342 oc_method,
8343 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008344 oc_function_template,
8345 oc_method_template,
8346 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008347 oc_implicit_default_constructor,
8348 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008349 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008350 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008351 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008352 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008353};
8354
John McCalle1ac8d12010-01-13 00:25:19 +00008355OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8356 FunctionDecl *Fn,
8357 std::string &Description) {
8358 bool isTemplate = false;
8359
8360 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8361 isTemplate = true;
8362 Description = S.getTemplateArgumentBindingsText(
8363 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8364 }
John McCallfd0b2f82010-01-06 09:43:14 +00008365
8366 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008367 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008368 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008369
Sebastian Redl08905022011-02-05 19:23:19 +00008370 if (Ctor->getInheritedConstructor())
8371 return oc_implicit_inherited_constructor;
8372
Alexis Hunt119c10e2011-05-25 23:16:36 +00008373 if (Ctor->isDefaultConstructor())
8374 return oc_implicit_default_constructor;
8375
8376 if (Ctor->isMoveConstructor())
8377 return oc_implicit_move_constructor;
8378
8379 assert(Ctor->isCopyConstructor() &&
8380 "unexpected sort of implicit constructor");
8381 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008382 }
8383
8384 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8385 // This actually gets spelled 'candidate function' for now, but
8386 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008387 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008388 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008389
Alexis Hunt119c10e2011-05-25 23:16:36 +00008390 if (Meth->isMoveAssignmentOperator())
8391 return oc_implicit_move_assignment;
8392
Douglas Gregor12695102012-02-10 08:36:38 +00008393 if (Meth->isCopyAssignmentOperator())
8394 return oc_implicit_copy_assignment;
8395
8396 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8397 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008398 }
8399
John McCalle1ac8d12010-01-13 00:25:19 +00008400 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008401}
8402
Larisse Voufo98b20f12013-07-19 23:00:19 +00008403void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008404 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8405 if (!Ctor) return;
8406
8407 Ctor = Ctor->getInheritedConstructor();
8408 if (!Ctor) return;
8409
8410 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8411}
8412
John McCall53262c92010-01-12 02:15:36 +00008413} // end anonymous namespace
8414
8415// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008416void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008417 std::string FnDesc;
8418 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008419 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8420 << (unsigned) K << FnDesc;
8421 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8422 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008423 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008424}
8425
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008426// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008427// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008428void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008429 assert(OverloadedExpr->getType() == Context.OverloadTy);
8430
8431 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8432 OverloadExpr *OvlExpr = Ovl.Expression;
8433
8434 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8435 IEnd = OvlExpr->decls_end();
8436 I != IEnd; ++I) {
8437 if (FunctionTemplateDecl *FunTmpl =
8438 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008439 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008440 } else if (FunctionDecl *Fun
8441 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008442 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008443 }
8444 }
8445}
8446
John McCall0d1da222010-01-12 00:44:57 +00008447/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8448/// "lead" diagnostic; it will be given two arguments, the source and
8449/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008450void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8451 Sema &S,
8452 SourceLocation CaretLoc,
8453 const PartialDiagnostic &PDiag) const {
8454 S.Diag(CaretLoc, PDiag)
8455 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008456 // FIXME: The note limiting machinery is borrowed from
8457 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8458 // refactoring here.
8459 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8460 unsigned CandsShown = 0;
8461 AmbiguousConversionSequence::const_iterator I, E;
8462 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8463 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8464 break;
8465 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008466 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008467 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008468 if (I != E)
8469 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008470}
8471
John McCall0d1da222010-01-12 00:44:57 +00008472namespace {
8473
John McCall6a61b522010-01-13 09:16:55 +00008474void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8475 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8476 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008477 assert(Cand->Function && "for now, candidate must be a function");
8478 FunctionDecl *Fn = Cand->Function;
8479
8480 // There's a conversion slot for the object argument if this is a
8481 // non-constructor method. Note that 'I' corresponds the
8482 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008483 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008484 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008485 if (I == 0)
8486 isObjectArgument = true;
8487 else
8488 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008489 }
8490
John McCalle1ac8d12010-01-13 00:25:19 +00008491 std::string FnDesc;
8492 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8493
John McCall6a61b522010-01-13 09:16:55 +00008494 Expr *FromExpr = Conv.Bad.FromExpr;
8495 QualType FromTy = Conv.Bad.getFromType();
8496 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008497
John McCallfb7ad0f2010-02-02 02:42:52 +00008498 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008499 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008500 Expr *E = FromExpr->IgnoreParens();
8501 if (isa<UnaryOperator>(E))
8502 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008503 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008504
8505 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8506 << (unsigned) FnKind << FnDesc
8507 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8508 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008509 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008510 return;
8511 }
8512
John McCall6d174642010-01-23 08:10:49 +00008513 // Do some hand-waving analysis to see if the non-viability is due
8514 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008515 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8516 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8517 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8518 CToTy = RT->getPointeeType();
8519 else {
8520 // TODO: detect and diagnose the full richness of const mismatches.
8521 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8522 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8523 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8524 }
8525
8526 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8527 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008528 Qualifiers FromQs = CFromTy.getQualifiers();
8529 Qualifiers ToQs = CToTy.getQualifiers();
8530
8531 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8533 << (unsigned) FnKind << FnDesc
8534 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8535 << FromTy
8536 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8537 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008538 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008539 return;
8540 }
8541
John McCall31168b02011-06-15 23:02:42 +00008542 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008543 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008544 << (unsigned) FnKind << FnDesc
8545 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8546 << FromTy
8547 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8548 << (unsigned) isObjectArgument << I+1;
8549 MaybeEmitInheritedConstructorNote(S, Fn);
8550 return;
8551 }
8552
Douglas Gregoraec25842011-04-26 23:16:46 +00008553 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8554 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8555 << (unsigned) FnKind << FnDesc
8556 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8557 << FromTy
8558 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8559 << (unsigned) isObjectArgument << I+1;
8560 MaybeEmitInheritedConstructorNote(S, Fn);
8561 return;
8562 }
8563
John McCall47000992010-01-14 03:28:57 +00008564 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8565 assert(CVR && "unexpected qualifiers mismatch");
8566
8567 if (isObjectArgument) {
8568 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8569 << (unsigned) FnKind << FnDesc
8570 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8571 << FromTy << (CVR - 1);
8572 } else {
8573 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8574 << (unsigned) FnKind << FnDesc
8575 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8576 << FromTy << (CVR - 1) << I+1;
8577 }
Sebastian Redl08905022011-02-05 19:23:19 +00008578 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008579 return;
8580 }
8581
Sebastian Redla72462c2011-09-24 17:48:32 +00008582 // Special diagnostic for failure to convert an initializer list, since
8583 // telling the user that it has type void is not useful.
8584 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8585 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8586 << (unsigned) FnKind << FnDesc
8587 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8588 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8589 MaybeEmitInheritedConstructorNote(S, Fn);
8590 return;
8591 }
8592
John McCall6d174642010-01-23 08:10:49 +00008593 // Diagnose references or pointers to incomplete types differently,
8594 // since it's far from impossible that the incompleteness triggered
8595 // the failure.
8596 QualType TempFromTy = FromTy.getNonReferenceType();
8597 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8598 TempFromTy = PTy->getPointeeType();
8599 if (TempFromTy->isIncompleteType()) {
8600 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8601 << (unsigned) FnKind << FnDesc
8602 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8603 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008604 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008605 return;
8606 }
8607
Douglas Gregor56f2e342010-06-30 23:01:39 +00008608 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008609 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008610 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8611 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8612 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8613 FromPtrTy->getPointeeType()) &&
8614 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8615 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008616 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008617 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008618 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008619 }
8620 } else if (const ObjCObjectPointerType *FromPtrTy
8621 = FromTy->getAs<ObjCObjectPointerType>()) {
8622 if (const ObjCObjectPointerType *ToPtrTy
8623 = ToTy->getAs<ObjCObjectPointerType>())
8624 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8625 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8626 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8627 FromPtrTy->getPointeeType()) &&
8628 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008629 BaseToDerivedConversion = 2;
8630 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008631 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8632 !FromTy->isIncompleteType() &&
8633 !ToRefTy->getPointeeType()->isIncompleteType() &&
8634 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8635 BaseToDerivedConversion = 3;
8636 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8637 ToTy.getNonReferenceType().getCanonicalType() ==
8638 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008639 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8640 << (unsigned) FnKind << FnDesc
8641 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8642 << (unsigned) isObjectArgument << I + 1;
8643 MaybeEmitInheritedConstructorNote(S, Fn);
8644 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008645 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008647
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008648 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008649 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008650 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008651 << (unsigned) FnKind << FnDesc
8652 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008653 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008654 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008655 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008656 return;
8657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008658
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008659 if (isa<ObjCObjectPointerType>(CFromTy) &&
8660 isa<PointerType>(CToTy)) {
8661 Qualifiers FromQs = CFromTy.getQualifiers();
8662 Qualifiers ToQs = CToTy.getQualifiers();
8663 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8664 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8665 << (unsigned) FnKind << FnDesc
8666 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8667 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8668 MaybeEmitInheritedConstructorNote(S, Fn);
8669 return;
8670 }
8671 }
8672
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008673 // Emit the generic diagnostic and, optionally, add the hints to it.
8674 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8675 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008676 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008677 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8678 << (unsigned) (Cand->Fix.Kind);
8679
8680 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008681 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8682 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008683 FDiag << *HI;
8684 S.Diag(Fn->getLocation(), FDiag);
8685
Sebastian Redl08905022011-02-05 19:23:19 +00008686 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008687}
8688
Larisse Voufo98b20f12013-07-19 23:00:19 +00008689/// Additional arity mismatch diagnosis specific to a function overload
8690/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8691/// over a candidate in any candidate set.
8692bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8693 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008694 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008695 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008696
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008697 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008698 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008699 // right number of arguments, because only overloaded operators have
8700 // the weird behavior of overloading member and non-member functions.
8701 // Just don't report anything.
8702 if (Fn->isInvalidDecl() &&
8703 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008704 return true;
8705
8706 if (NumArgs < MinParams) {
8707 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8708 (Cand->FailureKind == ovl_fail_bad_deduction &&
8709 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8710 } else {
8711 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8712 (Cand->FailureKind == ovl_fail_bad_deduction &&
8713 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8714 }
8715
8716 return false;
8717}
8718
8719/// General arity mismatch diagnosis over a candidate in a candidate set.
8720void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8721 assert(isa<FunctionDecl>(D) &&
8722 "The templated declaration should at least be a function"
8723 " when diagnosing bad template argument deduction due to too many"
8724 " or too few arguments");
8725
8726 FunctionDecl *Fn = cast<FunctionDecl>(D);
8727
8728 // TODO: treat calls to a missing default constructor as a special case
8729 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8730 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008731
John McCall6a61b522010-01-13 09:16:55 +00008732 // at least / at most / exactly
8733 unsigned mode, modeCount;
8734 if (NumFormalArgs < MinParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00008735 if (MinParams != FnTy->getNumParams() || FnTy->isVariadic() ||
8736 FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008737 mode = 0; // "at least"
8738 else
8739 mode = 2; // "exactly"
8740 modeCount = MinParams;
8741 } else {
Alp Toker9cacbab2014-01-20 20:26:09 +00008742 if (MinParams != FnTy->getNumParams())
John McCall6a61b522010-01-13 09:16:55 +00008743 mode = 1; // "at most"
8744 else
8745 mode = 2; // "exactly"
Alp Toker9cacbab2014-01-20 20:26:09 +00008746 modeCount = FnTy->getNumParams();
John McCall6a61b522010-01-13 09:16:55 +00008747 }
8748
8749 std::string Description;
8750 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8751
Richard Smith10ff50d2012-05-11 05:16:41 +00008752 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8753 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8754 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8755 << Fn->getParamDecl(0) << NumFormalArgs;
8756 else
8757 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8758 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8759 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008760 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008761}
8762
Larisse Voufo98b20f12013-07-19 23:00:19 +00008763/// Arity mismatch diagnosis specific to a function overload candidate.
8764void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8765 unsigned NumFormalArgs) {
8766 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8767 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8768}
Larisse Voufo47c08452013-07-19 22:53:23 +00008769
Larisse Voufo98b20f12013-07-19 23:00:19 +00008770TemplateDecl *getDescribedTemplate(Decl *Templated) {
8771 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8772 return FD->getDescribedFunctionTemplate();
8773 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8774 return RD->getDescribedClassTemplate();
8775
8776 llvm_unreachable("Unsupported: Getting the described template declaration"
8777 " for bad deduction diagnosis");
8778}
8779
8780/// Diagnose a failed template-argument deduction.
8781void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8782 DeductionFailureInfo &DeductionFailure,
8783 unsigned NumArgs) {
8784 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008785 NamedDecl *ParamD;
8786 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8787 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8788 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008789 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008790 case Sema::TDK_Success:
8791 llvm_unreachable("TDK_success while diagnosing bad deduction");
8792
8793 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008794 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008795 S.Diag(Templated->getLocation(),
8796 diag::note_ovl_candidate_incomplete_deduction)
8797 << ParamD->getDeclName();
8798 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008799 return;
8800 }
8801
John McCall42d7d192010-08-05 09:05:08 +00008802 case Sema::TDK_Underqualified: {
8803 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8804 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8805
Larisse Voufo98b20f12013-07-19 23:00:19 +00008806 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008807
8808 // Param will have been canonicalized, but it should just be a
8809 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008810 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008811 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008812 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008813 assert(S.Context.hasSameType(Param, NonCanonParam));
8814
8815 // Arg has also been canonicalized, but there's nothing we can do
8816 // about that. It also doesn't matter as much, because it won't
8817 // have any template parameters in it (because deduction isn't
8818 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008819 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008820
Larisse Voufo98b20f12013-07-19 23:00:19 +00008821 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8822 << ParamD->getDeclName() << Arg << NonCanonParam;
8823 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008824 return;
8825 }
8826
8827 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008828 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008829 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008830 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008831 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008832 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008833 which = 1;
8834 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008835 which = 2;
8836 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008837
Larisse Voufo98b20f12013-07-19 23:00:19 +00008838 S.Diag(Templated->getLocation(),
8839 diag::note_ovl_candidate_inconsistent_deduction)
8840 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8841 << *DeductionFailure.getSecondArg();
8842 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008843 return;
8844 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008845
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008846 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008847 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008848 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008849 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008850 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008851 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008852 else {
8853 int index = 0;
8854 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8855 index = TTP->getIndex();
8856 else if (NonTypeTemplateParmDecl *NTTP
8857 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8858 index = NTTP->getIndex();
8859 else
8860 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008861 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008862 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008863 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008864 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008865 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008866 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008867
Douglas Gregor02eb4832010-05-08 18:13:28 +00008868 case Sema::TDK_TooManyArguments:
8869 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008870 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008871 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008872
8873 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008874 S.Diag(Templated->getLocation(),
8875 diag::note_ovl_candidate_instantiation_depth);
8876 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008877 return;
8878
8879 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008880 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008881 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008882 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008883 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008884 TemplateArgString = " ";
8885 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00008886 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00008887 }
8888
Richard Smith6f8d2c62012-05-09 05:17:00 +00008889 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008890 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008891 if (PDiag && PDiag->second.getDiagID() ==
8892 diag::err_typename_nested_not_found_enable_if) {
8893 // FIXME: Use the source range of the condition, and the fully-qualified
8894 // name of the enable_if template. These are both present in PDiag.
8895 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8896 << "'enable_if'" << TemplateArgString;
8897 return;
8898 }
8899
Richard Smith9ca64612012-05-07 09:03:25 +00008900 // Format the SFINAE diagnostic into the argument string.
8901 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8902 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008903 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008904 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008905 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008906 SFINAEArgString = ": ";
8907 R = SourceRange(PDiag->first, PDiag->first);
8908 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8909 }
8910
Larisse Voufo98b20f12013-07-19 23:00:19 +00008911 S.Diag(Templated->getLocation(),
8912 diag::note_ovl_candidate_substitution_failure)
8913 << TemplateArgString << SFINAEArgString << R;
8914 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008915 return;
8916 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008917
Richard Smith8c6eeb92013-01-31 04:03:12 +00008918 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008919 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8920 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00008921 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008922 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00008923 return;
8924 }
8925
Richard Trieue3732352013-04-08 21:11:40 +00008926 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00008927 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008928 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8929 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00008930 if (FirstTA.getKind() == TemplateArgument::Template &&
8931 SecondTA.getKind() == TemplateArgument::Template) {
8932 TemplateName FirstTN = FirstTA.getAsTemplate();
8933 TemplateName SecondTN = SecondTA.getAsTemplate();
8934 if (FirstTN.getKind() == TemplateName::Template &&
8935 SecondTN.getKind() == TemplateName::Template) {
8936 if (FirstTN.getAsTemplateDecl()->getName() ==
8937 SecondTN.getAsTemplateDecl()->getName()) {
8938 // FIXME: This fixes a bad diagnostic where both templates are named
8939 // the same. This particular case is a bit difficult since:
8940 // 1) It is passed as a string to the diagnostic printer.
8941 // 2) The diagnostic printer only attempts to find a better
8942 // name for types, not decls.
8943 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008944 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00008945 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8946 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8947 return;
8948 }
8949 }
8950 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00008951 // FIXME: For generic lambda parameters, check if the function is a lambda
8952 // call operator, and if so, emit a prettier and more informative
8953 // diagnostic that mentions 'auto' and lambda in addition to
8954 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008955 S.Diag(Templated->getLocation(),
8956 diag::note_ovl_candidate_non_deduced_mismatch)
8957 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00008958 return;
Richard Trieue3732352013-04-08 21:11:40 +00008959 }
John McCall8b9ed552010-02-01 18:53:26 +00008960 // TODO: diagnose these individually, then kill off
8961 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00008962 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008963 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8964 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008965 return;
8966 }
8967}
8968
Larisse Voufo98b20f12013-07-19 23:00:19 +00008969/// Diagnose a failed template-argument deduction, for function calls.
8970void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8971 unsigned TDK = Cand->DeductionFailure.Result;
8972 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8973 if (CheckArityMismatch(S, Cand, NumArgs))
8974 return;
8975 }
8976 DiagnoseBadDeduction(S, Cand->Function, // pattern
8977 Cand->DeductionFailure, NumArgs);
8978}
8979
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008980/// CUDA: diagnose an invalid call across targets.
8981void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8982 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8983 FunctionDecl *Callee = Cand->Function;
8984
8985 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8986 CalleeTarget = S.IdentifyCUDATarget(Callee);
8987
8988 std::string FnDesc;
8989 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8990
8991 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8992 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8993}
8994
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008995void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
8996 FunctionDecl *Callee = Cand->Function;
8997 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
8998
8999 S.Diag(Callee->getLocation(),
9000 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9001 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9002}
9003
John McCall8b9ed552010-02-01 18:53:26 +00009004/// Generates a 'note' diagnostic for an overload candidate. We've
9005/// already generated a primary error at the call site.
9006///
9007/// It really does need to be a single diagnostic with its caret
9008/// pointed at the candidate declaration. Yes, this creates some
9009/// major challenges of technical writing. Yes, this makes pointing
9010/// out problems with specific arguments quite awkward. It's still
9011/// better than generating twenty screens of text for every failed
9012/// overload.
9013///
9014/// It would be great to be able to express per-candidate problems
9015/// more richly for those diagnostic clients that cared, but we'd
9016/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00009017void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009018 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009019 FunctionDecl *Fn = Cand->Function;
9020
John McCall12f97bc2010-01-08 04:41:39 +00009021 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009022 if (Cand->Viable && (Fn->isDeleted() ||
9023 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009024 std::string FnDesc;
9025 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009026
9027 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009028 << FnKind << FnDesc
9029 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009030 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009031 return;
John McCall12f97bc2010-01-08 04:41:39 +00009032 }
9033
John McCalle1ac8d12010-01-13 00:25:19 +00009034 // We don't really have anything else to say about viable candidates.
9035 if (Cand->Viable) {
9036 S.NoteOverloadCandidate(Fn);
9037 return;
9038 }
John McCall0d1da222010-01-12 00:44:57 +00009039
John McCall6a61b522010-01-13 09:16:55 +00009040 switch (Cand->FailureKind) {
9041 case ovl_fail_too_many_arguments:
9042 case ovl_fail_too_few_arguments:
9043 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009044
John McCall6a61b522010-01-13 09:16:55 +00009045 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009046 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009047
John McCallfe796dd2010-01-23 05:17:32 +00009048 case ovl_fail_trivial_conversion:
9049 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009050 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009051 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009052
John McCall65eb8792010-02-25 01:37:24 +00009053 case ovl_fail_bad_conversion: {
9054 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009055 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009056 if (Cand->Conversions[I].isBad())
9057 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009058
John McCall6a61b522010-01-13 09:16:55 +00009059 // FIXME: this currently happens when we're called from SemaInit
9060 // when user-conversion overload fails. Figure out how to handle
9061 // those conditions and diagnose them well.
9062 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009063 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009064
9065 case ovl_fail_bad_target:
9066 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009067
9068 case ovl_fail_enable_if:
9069 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009070 }
John McCalld3224162010-01-08 00:58:21 +00009071}
9072
9073void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9074 // Desugar the type of the surrogate down to a function type,
9075 // retaining as many typedefs as possible while still showing
9076 // the function type (and, therefore, its parameter types).
9077 QualType FnType = Cand->Surrogate->getConversionType();
9078 bool isLValueReference = false;
9079 bool isRValueReference = false;
9080 bool isPointer = false;
9081 if (const LValueReferenceType *FnTypeRef =
9082 FnType->getAs<LValueReferenceType>()) {
9083 FnType = FnTypeRef->getPointeeType();
9084 isLValueReference = true;
9085 } else if (const RValueReferenceType *FnTypeRef =
9086 FnType->getAs<RValueReferenceType>()) {
9087 FnType = FnTypeRef->getPointeeType();
9088 isRValueReference = true;
9089 }
9090 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9091 FnType = FnTypePtr->getPointeeType();
9092 isPointer = true;
9093 }
9094 // Desugar down to a function type.
9095 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9096 // Reconstruct the pointer/reference as appropriate.
9097 if (isPointer) FnType = S.Context.getPointerType(FnType);
9098 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9099 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9100
9101 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9102 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009103 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009104}
9105
9106void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009107 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009108 SourceLocation OpLoc,
9109 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009110 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009111 std::string TypeStr("operator");
9112 TypeStr += Opc;
9113 TypeStr += "(";
9114 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009115 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009116 TypeStr += ")";
9117 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9118 } else {
9119 TypeStr += ", ";
9120 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9121 TypeStr += ")";
9122 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9123 }
9124}
9125
9126void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9127 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009128 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009129 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9130 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009131 if (ICS.isBad()) break; // all meaningless after first invalid
9132 if (!ICS.isAmbiguous()) continue;
9133
John McCall5c32be02010-08-24 20:38:10 +00009134 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009135 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009136 }
9137}
9138
Larisse Voufo98b20f12013-07-19 23:00:19 +00009139static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009140 if (Cand->Function)
9141 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009142 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009143 return Cand->Surrogate->getLocation();
9144 return SourceLocation();
9145}
9146
Larisse Voufo98b20f12013-07-19 23:00:19 +00009147static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009148 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009149 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009150 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009151
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009152 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009153 case Sema::TDK_Incomplete:
9154 return 1;
9155
9156 case Sema::TDK_Underqualified:
9157 case Sema::TDK_Inconsistent:
9158 return 2;
9159
9160 case Sema::TDK_SubstitutionFailure:
9161 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009162 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009163 return 3;
9164
9165 case Sema::TDK_InstantiationDepth:
9166 case Sema::TDK_FailedOverloadResolution:
9167 return 4;
9168
9169 case Sema::TDK_InvalidExplicitArguments:
9170 return 5;
9171
9172 case Sema::TDK_TooManyArguments:
9173 case Sema::TDK_TooFewArguments:
9174 return 6;
9175 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009176 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009177}
9178
John McCallad2587a2010-01-12 00:48:53 +00009179struct CompareOverloadCandidatesForDisplay {
9180 Sema &S;
9181 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00009182
9183 bool operator()(const OverloadCandidate *L,
9184 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009185 // Fast-path this check.
9186 if (L == R) return false;
9187
John McCall12f97bc2010-01-08 04:41:39 +00009188 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009189 if (L->Viable) {
9190 if (!R->Viable) return true;
9191
9192 // TODO: introduce a tri-valued comparison for overload
9193 // candidates. Would be more worthwhile if we had a sort
9194 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009195 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9196 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009197 } else if (R->Viable)
9198 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009199
John McCall3712d9e2010-01-15 23:32:50 +00009200 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009201
John McCall3712d9e2010-01-15 23:32:50 +00009202 // Criteria by which we can sort non-viable candidates:
9203 if (!L->Viable) {
9204 // 1. Arity mismatches come after other candidates.
9205 if (L->FailureKind == ovl_fail_too_many_arguments ||
9206 L->FailureKind == ovl_fail_too_few_arguments)
9207 return false;
9208 if (R->FailureKind == ovl_fail_too_many_arguments ||
9209 R->FailureKind == ovl_fail_too_few_arguments)
9210 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009211
John McCallfe796dd2010-01-23 05:17:32 +00009212 // 2. Bad conversions come first and are ordered by the number
9213 // of bad conversions and quality of good conversions.
9214 if (L->FailureKind == ovl_fail_bad_conversion) {
9215 if (R->FailureKind != ovl_fail_bad_conversion)
9216 return true;
9217
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009218 // The conversion that can be fixed with a smaller number of changes,
9219 // comes first.
9220 unsigned numLFixes = L->Fix.NumConversionsFixed;
9221 unsigned numRFixes = R->Fix.NumConversionsFixed;
9222 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9223 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009224 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009225 if (numLFixes < numRFixes)
9226 return true;
9227 else
9228 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009229 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009230
John McCallfe796dd2010-01-23 05:17:32 +00009231 // If there's any ordering between the defined conversions...
9232 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009233 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009234
9235 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009236 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009237 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009238 switch (CompareImplicitConversionSequences(S,
9239 L->Conversions[I],
9240 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009241 case ImplicitConversionSequence::Better:
9242 leftBetter++;
9243 break;
9244
9245 case ImplicitConversionSequence::Worse:
9246 leftBetter--;
9247 break;
9248
9249 case ImplicitConversionSequence::Indistinguishable:
9250 break;
9251 }
9252 }
9253 if (leftBetter > 0) return true;
9254 if (leftBetter < 0) return false;
9255
9256 } else if (R->FailureKind == ovl_fail_bad_conversion)
9257 return false;
9258
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009259 if (L->FailureKind == ovl_fail_bad_deduction) {
9260 if (R->FailureKind != ovl_fail_bad_deduction)
9261 return true;
9262
9263 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9264 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009265 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009266 } else if (R->FailureKind == ovl_fail_bad_deduction)
9267 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009268
John McCall3712d9e2010-01-15 23:32:50 +00009269 // TODO: others?
9270 }
9271
9272 // Sort everything else by location.
9273 SourceLocation LLoc = GetLocationForCandidate(L);
9274 SourceLocation RLoc = GetLocationForCandidate(R);
9275
9276 // Put candidates without locations (e.g. builtins) at the end.
9277 if (LLoc.isInvalid()) return false;
9278 if (RLoc.isInvalid()) return true;
9279
9280 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009281 }
9282};
9283
John McCallfe796dd2010-01-23 05:17:32 +00009284/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009285/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009286void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009287 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009288 assert(!Cand->Viable);
9289
9290 // Don't do anything on failures other than bad conversion.
9291 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9292
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009293 // We only want the FixIts if all the arguments can be corrected.
9294 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009295 // Use a implicit copy initialization to check conversion fixes.
9296 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009297
John McCallfe796dd2010-01-23 05:17:32 +00009298 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009299 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009300 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009301 while (true) {
9302 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9303 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009304 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009305 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009306 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009307 }
John McCallfe796dd2010-01-23 05:17:32 +00009308 }
9309
9310 if (ConvIdx == ConvCount)
9311 return;
9312
John McCall65eb8792010-02-25 01:37:24 +00009313 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9314 "remaining conversion is initialized?");
9315
Douglas Gregoradc7a702010-04-16 17:45:54 +00009316 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009317 // operation somehow.
9318 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009319
9320 const FunctionProtoType* Proto;
9321 unsigned ArgIdx = ConvIdx;
9322
9323 if (Cand->IsSurrogate) {
9324 QualType ConvType
9325 = Cand->Surrogate->getConversionType().getNonReferenceType();
9326 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9327 ConvType = ConvPtrType->getPointeeType();
9328 Proto = ConvType->getAs<FunctionProtoType>();
9329 ArgIdx--;
9330 } else if (Cand->Function) {
9331 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9332 if (isa<CXXMethodDecl>(Cand->Function) &&
9333 !isa<CXXConstructorDecl>(Cand->Function))
9334 ArgIdx--;
9335 } else {
9336 // Builtin binary operator with a bad first conversion.
9337 assert(ConvCount <= 3);
9338 for (; ConvIdx != ConvCount; ++ConvIdx)
9339 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009340 = TryCopyInitialization(S, Args[ConvIdx],
9341 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009342 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009343 /*InOverloadResolution*/ true,
9344 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009345 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009346 return;
9347 }
9348
9349 // Fill in the rest of the conversions.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009350 unsigned NumParams = Proto->getNumParams();
John McCallfe796dd2010-01-23 05:17:32 +00009351 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Alp Tokerb3fd5cf2014-01-21 00:32:38 +00009352 if (ArgIdx < NumParams) {
Alp Toker9cacbab2014-01-20 20:26:09 +00009353 Cand->Conversions[ConvIdx] = TryCopyInitialization(
9354 S, Args[ArgIdx], Proto->getParamType(ArgIdx), SuppressUserConversions,
9355 /*InOverloadResolution=*/true,
9356 /*AllowObjCWritebackConversion=*/
9357 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009358 // Store the FixIt in the candidate if it exists.
9359 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009360 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009361 }
John McCallfe796dd2010-01-23 05:17:32 +00009362 else
9363 Cand->Conversions[ConvIdx].setEllipsis();
9364 }
9365}
9366
John McCalld3224162010-01-08 00:58:21 +00009367} // end anonymous namespace
9368
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009369/// PrintOverloadCandidates - When overload resolution fails, prints
9370/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009371/// set.
John McCall5c32be02010-08-24 20:38:10 +00009372void OverloadCandidateSet::NoteCandidates(Sema &S,
9373 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009374 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009375 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009376 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009377 // Sort the candidates by viability and position. Sorting directly would
9378 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009379 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009380 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9381 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009382 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009383 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009384 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009385 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009386 if (Cand->Function || Cand->IsSurrogate)
9387 Cands.push_back(Cand);
9388 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9389 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009390 }
9391 }
9392
John McCallad2587a2010-01-12 00:48:53 +00009393 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00009394 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009395
John McCall0d1da222010-01-12 00:44:57 +00009396 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009397
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009398 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009399 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009400 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009401 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9402 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009403
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009404 // Set an arbitrary limit on the number of candidate functions we'll spam
9405 // the user with. FIXME: This limit should depend on details of the
9406 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009407 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009408 break;
9409 }
9410 ++CandsShown;
9411
John McCalld3224162010-01-08 00:58:21 +00009412 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009413 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009414 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009415 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009416 else {
9417 assert(Cand->Viable &&
9418 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009419 // Generally we only see ambiguities including viable builtin
9420 // operators if overload resolution got screwed up by an
9421 // ambiguous user-defined conversion.
9422 //
9423 // FIXME: It's quite possible for different conversions to see
9424 // different ambiguities, though.
9425 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009426 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009427 ReportedAmbiguousConversions = true;
9428 }
John McCalld3224162010-01-08 00:58:21 +00009429
John McCall0d1da222010-01-12 00:44:57 +00009430 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009431 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009432 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009433 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009434
9435 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009436 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009437}
9438
Larisse Voufo98b20f12013-07-19 23:00:19 +00009439static SourceLocation
9440GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9441 return Cand->Specialization ? Cand->Specialization->getLocation()
9442 : SourceLocation();
9443}
9444
9445struct CompareTemplateSpecCandidatesForDisplay {
9446 Sema &S;
9447 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9448
9449 bool operator()(const TemplateSpecCandidate *L,
9450 const TemplateSpecCandidate *R) {
9451 // Fast-path this check.
9452 if (L == R)
9453 return false;
9454
9455 // Assuming that both candidates are not matches...
9456
9457 // Sort by the ranking of deduction failures.
9458 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9459 return RankDeductionFailure(L->DeductionFailure) <
9460 RankDeductionFailure(R->DeductionFailure);
9461
9462 // Sort everything else by location.
9463 SourceLocation LLoc = GetLocationForCandidate(L);
9464 SourceLocation RLoc = GetLocationForCandidate(R);
9465
9466 // Put candidates without locations (e.g. builtins) at the end.
9467 if (LLoc.isInvalid())
9468 return false;
9469 if (RLoc.isInvalid())
9470 return true;
9471
9472 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9473 }
9474};
9475
9476/// Diagnose a template argument deduction failure.
9477/// We are treating these failures as overload failures due to bad
9478/// deductions.
9479void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9480 DiagnoseBadDeduction(S, Specialization, // pattern
9481 DeductionFailure, /*NumArgs=*/0);
9482}
9483
9484void TemplateSpecCandidateSet::destroyCandidates() {
9485 for (iterator i = begin(), e = end(); i != e; ++i) {
9486 i->DeductionFailure.Destroy();
9487 }
9488}
9489
9490void TemplateSpecCandidateSet::clear() {
9491 destroyCandidates();
9492 Candidates.clear();
9493}
9494
9495/// NoteCandidates - When no template specialization match is found, prints
9496/// diagnostic messages containing the non-matching specializations that form
9497/// the candidate set.
9498/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9499/// OCD == OCD_AllCandidates and Cand->Viable == false.
9500void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9501 // Sort the candidates by position (assuming no candidate is a match).
9502 // Sorting directly would be prohibitive, so we make a set of pointers
9503 // and sort those.
9504 SmallVector<TemplateSpecCandidate *, 32> Cands;
9505 Cands.reserve(size());
9506 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9507 if (Cand->Specialization)
9508 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009509 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009510 // in general, want to list every possible builtin candidate.
9511 }
9512
9513 std::sort(Cands.begin(), Cands.end(),
9514 CompareTemplateSpecCandidatesForDisplay(S));
9515
9516 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9517 // for generalization purposes (?).
9518 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9519
9520 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9521 unsigned CandsShown = 0;
9522 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9523 TemplateSpecCandidate *Cand = *I;
9524
9525 // Set an arbitrary limit on the number of candidates we'll spam
9526 // the user with. FIXME: This limit should depend on details of the
9527 // candidate list.
9528 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9529 break;
9530 ++CandsShown;
9531
9532 assert(Cand->Specialization &&
9533 "Non-matching built-in candidates are not added to Cands.");
9534 Cand->NoteDeductionFailure(S);
9535 }
9536
9537 if (I != E)
9538 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9539}
9540
Douglas Gregorb491ed32011-02-19 21:32:49 +00009541// [PossiblyAFunctionType] --> [Return]
9542// NonFunctionType --> NonFunctionType
9543// R (A) --> R(A)
9544// R (*)(A) --> R (A)
9545// R (&)(A) --> R (A)
9546// R (S::*)(A) --> R (A)
9547QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9548 QualType Ret = PossiblyAFunctionType;
9549 if (const PointerType *ToTypePtr =
9550 PossiblyAFunctionType->getAs<PointerType>())
9551 Ret = ToTypePtr->getPointeeType();
9552 else if (const ReferenceType *ToTypeRef =
9553 PossiblyAFunctionType->getAs<ReferenceType>())
9554 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009555 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009556 PossiblyAFunctionType->getAs<MemberPointerType>())
9557 Ret = MemTypePtr->getPointeeType();
9558 Ret =
9559 Context.getCanonicalType(Ret).getUnqualifiedType();
9560 return Ret;
9561}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009562
Douglas Gregorb491ed32011-02-19 21:32:49 +00009563// A helper class to help with address of function resolution
9564// - allows us to avoid passing around all those ugly parameters
9565class AddressOfFunctionResolver
9566{
9567 Sema& S;
9568 Expr* SourceExpr;
9569 const QualType& TargetType;
9570 QualType TargetFunctionType; // Extracted function type from target type
9571
9572 bool Complain;
9573 //DeclAccessPair& ResultFunctionAccessPair;
9574 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009575
Douglas Gregorb491ed32011-02-19 21:32:49 +00009576 bool TargetTypeIsNonStaticMemberFunction;
9577 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009578 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009579
Douglas Gregorb491ed32011-02-19 21:32:49 +00009580 OverloadExpr::FindResult OvlExprInfo;
9581 OverloadExpr *OvlExpr;
9582 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009583 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009584 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009585
Douglas Gregorb491ed32011-02-19 21:32:49 +00009586public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009587 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9588 const QualType &TargetType, bool Complain)
9589 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9590 Complain(Complain), Context(S.getASTContext()),
9591 TargetTypeIsNonStaticMemberFunction(
9592 !!TargetType->getAs<MemberPointerType>()),
9593 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009594 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009595 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9596 OvlExpr(OvlExprInfo.Expression),
9597 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009598 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009599
David Majnemera4f7c7a2013-08-01 06:13:59 +00009600 if (TargetFunctionType->isFunctionType()) {
9601 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9602 if (!UME->isImplicitAccess() &&
9603 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9604 StaticMemberFunctionFromBoundPointer = true;
9605 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9606 DeclAccessPair dap;
9607 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9608 OvlExpr, false, &dap)) {
9609 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9610 if (!Method->isStatic()) {
9611 // If the target type is a non-function type and the function found
9612 // is a non-static member function, pretend as if that was the
9613 // target, it's the only possible type to end up with.
9614 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009615
David Majnemera4f7c7a2013-08-01 06:13:59 +00009616 // And skip adding the function if its not in the proper form.
9617 // We'll diagnose this due to an empty set of functions.
9618 if (!OvlExprInfo.HasFormOfMemberPointer)
9619 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009620 }
9621
David Majnemera4f7c7a2013-08-01 06:13:59 +00009622 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009623 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009624 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009625 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009626
9627 if (OvlExpr->hasExplicitTemplateArgs())
9628 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009629
Douglas Gregorb491ed32011-02-19 21:32:49 +00009630 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9631 // C++ [over.over]p4:
9632 // If more than one function is selected, [...]
9633 if (Matches.size() > 1) {
9634 if (FoundNonTemplateFunction)
9635 EliminateAllTemplateMatches();
9636 else
9637 EliminateAllExceptMostSpecializedTemplate();
9638 }
9639 }
9640 }
9641
9642private:
9643 bool isTargetTypeAFunction() const {
9644 return TargetFunctionType->isFunctionType();
9645 }
9646
9647 // [ToType] [Return]
9648
9649 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9650 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9651 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9652 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9653 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9654 }
9655
9656 // return true if any matching specializations were found
9657 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9658 const DeclAccessPair& CurAccessFunPair) {
9659 if (CXXMethodDecl *Method
9660 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9661 // Skip non-static function templates when converting to pointer, and
9662 // static when converting to member pointer.
9663 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9664 return false;
9665 }
9666 else if (TargetTypeIsNonStaticMemberFunction)
9667 return false;
9668
9669 // C++ [over.over]p2:
9670 // If the name is a function template, template argument deduction is
9671 // done (14.8.2.2), and if the argument deduction succeeds, the
9672 // resulting template argument list is used to generate a single
9673 // function template specialization, which is added to the set of
9674 // overloaded functions considered.
9675 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009676 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009677 if (Sema::TemplateDeductionResult Result
9678 = S.DeduceTemplateArguments(FunctionTemplate,
9679 &OvlExplicitTemplateArgs,
9680 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009681 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009682 // Make a note of the failed deduction for diagnostics.
9683 FailedCandidates.addCandidate()
9684 .set(FunctionTemplate->getTemplatedDecl(),
9685 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009686 return false;
9687 }
9688
Douglas Gregor19a41f12013-04-17 08:45:07 +00009689 // Template argument deduction ensures that we have an exact match or
9690 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009691 // This function template specicalization works.
9692 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009693 assert(S.isSameOrCompatibleFunctionType(
9694 Context.getCanonicalType(Specialization->getType()),
9695 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009696 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9697 return true;
9698 }
9699
9700 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9701 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009702 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009703 // Skip non-static functions when converting to pointer, and static
9704 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009705 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9706 return false;
9707 }
9708 else if (TargetTypeIsNonStaticMemberFunction)
9709 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009710
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009711 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009712 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009713 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9714 if (S.CheckCUDATarget(Caller, FunDecl))
9715 return false;
9716
Richard Smith2a7d4812013-05-04 07:00:32 +00009717 // If any candidate has a placeholder return type, trigger its deduction
9718 // now.
9719 if (S.getLangOpts().CPlusPlus1y &&
9720 FunDecl->getResultType()->isUndeducedType() &&
9721 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9722 return false;
9723
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009724 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009725 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9726 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009727 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9728 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009729 Matches.push_back(std::make_pair(CurAccessFunPair,
9730 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009731 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009732 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009733 }
Mike Stump11289f42009-09-09 15:08:12 +00009734 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009735
9736 return false;
9737 }
9738
9739 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9740 bool Ret = false;
9741
9742 // If the overload expression doesn't have the form of a pointer to
9743 // member, don't try to convert it to a pointer-to-member type.
9744 if (IsInvalidFormOfPointerToMemberFunction())
9745 return false;
9746
9747 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9748 E = OvlExpr->decls_end();
9749 I != E; ++I) {
9750 // Look through any using declarations to find the underlying function.
9751 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9752
9753 // C++ [over.over]p3:
9754 // Non-member functions and static member functions match
9755 // targets of type "pointer-to-function" or "reference-to-function."
9756 // Nonstatic member functions match targets of
9757 // type "pointer-to-member-function."
9758 // Note that according to DR 247, the containing class does not matter.
9759 if (FunctionTemplateDecl *FunctionTemplate
9760 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9761 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9762 Ret = true;
9763 }
9764 // If we have explicit template arguments supplied, skip non-templates.
9765 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9766 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9767 Ret = true;
9768 }
9769 assert(Ret || Matches.empty());
9770 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009771 }
9772
Douglas Gregorb491ed32011-02-19 21:32:49 +00009773 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009774 // [...] and any given function template specialization F1 is
9775 // eliminated if the set contains a second function template
9776 // specialization whose function template is more specialized
9777 // than the function template of F1 according to the partial
9778 // ordering rules of 14.5.5.2.
9779
9780 // The algorithm specified above is quadratic. We instead use a
9781 // two-pass algorithm (similar to the one used to identify the
9782 // best viable function in an overload set) that identifies the
9783 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009784
9785 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9786 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9787 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009788
Larisse Voufo98b20f12013-07-19 23:00:19 +00009789 // TODO: It looks like FailedCandidates does not serve much purpose
9790 // here, since the no_viable diagnostic has index 0.
9791 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009792 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009793 SourceExpr->getLocStart(), S.PDiag(),
9794 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9795 .second->getDeclName(),
9796 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9797 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009798
Douglas Gregorb491ed32011-02-19 21:32:49 +00009799 if (Result != MatchesCopy.end()) {
9800 // Make it the first and only element
9801 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9802 Matches[0].second = cast<FunctionDecl>(*Result);
9803 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009804 }
9805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009806
Douglas Gregorb491ed32011-02-19 21:32:49 +00009807 void EliminateAllTemplateMatches() {
9808 // [...] any function template specializations in the set are
9809 // eliminated if the set also contains a non-template function, [...]
9810 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9811 if (Matches[I].second->getPrimaryTemplate() == 0)
9812 ++I;
9813 else {
9814 Matches[I] = Matches[--N];
9815 Matches.set_size(N);
9816 }
9817 }
9818 }
9819
9820public:
9821 void ComplainNoMatchesFound() const {
9822 assert(Matches.empty());
9823 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9824 << OvlExpr->getName() << TargetFunctionType
9825 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009826 if (FailedCandidates.empty())
9827 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9828 else {
9829 // We have some deduction failure messages. Use them to diagnose
9830 // the function templates, and diagnose the non-template candidates
9831 // normally.
9832 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9833 IEnd = OvlExpr->decls_end();
9834 I != IEnd; ++I)
9835 if (FunctionDecl *Fun =
9836 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9837 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9838 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9839 }
9840 }
9841
Douglas Gregorb491ed32011-02-19 21:32:49 +00009842 bool IsInvalidFormOfPointerToMemberFunction() const {
9843 return TargetTypeIsNonStaticMemberFunction &&
9844 !OvlExprInfo.HasFormOfMemberPointer;
9845 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009846
Douglas Gregorb491ed32011-02-19 21:32:49 +00009847 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9848 // TODO: Should we condition this on whether any functions might
9849 // have matched, or is it more appropriate to do that in callers?
9850 // TODO: a fixit wouldn't hurt.
9851 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9852 << TargetType << OvlExpr->getSourceRange();
9853 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009854
9855 bool IsStaticMemberFunctionFromBoundPointer() const {
9856 return StaticMemberFunctionFromBoundPointer;
9857 }
9858
9859 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9860 S.Diag(OvlExpr->getLocStart(),
9861 diag::err_invalid_form_pointer_member_function)
9862 << OvlExpr->getSourceRange();
9863 }
9864
Douglas Gregorb491ed32011-02-19 21:32:49 +00009865 void ComplainOfInvalidConversion() const {
9866 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9867 << OvlExpr->getName() << TargetType;
9868 }
9869
9870 void ComplainMultipleMatchesFound() const {
9871 assert(Matches.size() > 1);
9872 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9873 << OvlExpr->getName()
9874 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009875 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009876 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009877
9878 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9879
Douglas Gregorb491ed32011-02-19 21:32:49 +00009880 int getNumMatches() const { return Matches.size(); }
9881
9882 FunctionDecl* getMatchingFunctionDecl() const {
9883 if (Matches.size() != 1) return 0;
9884 return Matches[0].second;
9885 }
9886
9887 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9888 if (Matches.size() != 1) return 0;
9889 return &Matches[0].first;
9890 }
9891};
9892
9893/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9894/// an overloaded function (C++ [over.over]), where @p From is an
9895/// expression with overloaded function type and @p ToType is the type
9896/// we're trying to resolve to. For example:
9897///
9898/// @code
9899/// int f(double);
9900/// int f(int);
9901///
9902/// int (*pfd)(double) = f; // selects f(double)
9903/// @endcode
9904///
9905/// This routine returns the resulting FunctionDecl if it could be
9906/// resolved, and NULL otherwise. When @p Complain is true, this
9907/// routine will emit diagnostics if there is an error.
9908FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009909Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9910 QualType TargetType,
9911 bool Complain,
9912 DeclAccessPair &FoundResult,
9913 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009914 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009915
9916 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9917 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009918 int NumMatches = Resolver.getNumMatches();
9919 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009920 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009921 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9922 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9923 else
9924 Resolver.ComplainNoMatchesFound();
9925 }
9926 else if (NumMatches > 1 && Complain)
9927 Resolver.ComplainMultipleMatchesFound();
9928 else if (NumMatches == 1) {
9929 Fn = Resolver.getMatchingFunctionDecl();
9930 assert(Fn);
9931 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +00009932 if (Complain) {
9933 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9934 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9935 else
9936 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9937 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009938 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009939
9940 if (pHadMultipleCandidates)
9941 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009942 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009943}
9944
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009945/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009946/// resolve that overloaded function expression down to a single function.
9947///
9948/// This routine can only resolve template-ids that refer to a single function
9949/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009950/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009951/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +00009952///
9953/// If no template-ids are found, no diagnostics are emitted and NULL is
9954/// returned.
John McCall0009fcc2011-04-26 20:42:42 +00009955FunctionDecl *
9956Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9957 bool Complain,
9958 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009959 // C++ [over.over]p1:
9960 // [...] [Note: any redundant set of parentheses surrounding the
9961 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009962 // C++ [over.over]p1:
9963 // [...] The overloaded function name can be preceded by the &
9964 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009965
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009966 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009967 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009968 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009969
9970 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009971 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009972 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009973
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009974 // Look through all of the overloaded functions, searching for one
9975 // whose type matches exactly.
9976 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009977 for (UnresolvedSetIterator I = ovl->decls_begin(),
9978 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009979 // C++0x [temp.arg.explicit]p3:
9980 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009981 // where deduction is not done, if a template argument list is
9982 // specified and it, along with any default template arguments,
9983 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009984 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009985 FunctionTemplateDecl *FunctionTemplate
9986 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009987
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009988 // C++ [over.over]p2:
9989 // If the name is a function template, template argument deduction is
9990 // done (14.8.2.2), and if the argument deduction succeeds, the
9991 // resulting template argument list is used to generate a single
9992 // function template specialization, which is added to the set of
9993 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009994 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009995 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009996 if (TemplateDeductionResult Result
9997 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009998 Specialization, Info,
9999 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010000 // Make a note of the failed deduction for diagnostics.
10001 // TODO: Actually use the failed-deduction info?
10002 FailedCandidates.addCandidate()
10003 .set(FunctionTemplate->getTemplatedDecl(),
10004 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010005 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010006 }
10007
John McCall0009fcc2011-04-26 20:42:42 +000010008 assert(Specialization && "no specialization and no error?");
10009
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010010 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010011 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010012 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010013 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10014 << ovl->getName();
10015 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010016 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010017 return 0;
John McCall0009fcc2011-04-26 20:42:42 +000010018 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010019
John McCall0009fcc2011-04-26 20:42:42 +000010020 Matched = Specialization;
10021 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010022 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010023
Richard Smith2a7d4812013-05-04 07:00:32 +000010024 if (Matched && getLangOpts().CPlusPlus1y &&
10025 Matched->getResultType()->isUndeducedType() &&
10026 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10027 return 0;
10028
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010029 return Matched;
10030}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010031
Douglas Gregor1beec452011-03-12 01:48:56 +000010032
10033
10034
John McCall50a2c2c2011-10-11 23:14:30 +000010035// Resolve and fix an overloaded expression that can be resolved
10036// because it identifies a single function template specialization.
10037//
Douglas Gregor1beec452011-03-12 01:48:56 +000010038// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010039//
10040// Return true if it was logically possible to so resolve the
10041// expression, regardless of whether or not it succeeded. Always
10042// returns true if 'complain' is set.
10043bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10044 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10045 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010046 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010047 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010048 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010049
John McCall50a2c2c2011-10-11 23:14:30 +000010050 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010051
John McCall0009fcc2011-04-26 20:42:42 +000010052 DeclAccessPair found;
10053 ExprResult SingleFunctionExpression;
10054 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10055 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010056 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010057 SrcExpr = ExprError();
10058 return true;
10059 }
John McCall0009fcc2011-04-26 20:42:42 +000010060
10061 // It is only correct to resolve to an instance method if we're
10062 // resolving a form that's permitted to be a pointer to member.
10063 // Otherwise we'll end up making a bound member expression, which
10064 // is illegal in all the contexts we resolve like this.
10065 if (!ovl.HasFormOfMemberPointer &&
10066 isa<CXXMethodDecl>(fn) &&
10067 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010068 if (!complain) return false;
10069
10070 Diag(ovl.Expression->getExprLoc(),
10071 diag::err_bound_member_function)
10072 << 0 << ovl.Expression->getSourceRange();
10073
10074 // TODO: I believe we only end up here if there's a mix of
10075 // static and non-static candidates (otherwise the expression
10076 // would have 'bound member' type, not 'overload' type).
10077 // Ideally we would note which candidate was chosen and why
10078 // the static candidates were rejected.
10079 SrcExpr = ExprError();
10080 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010081 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010082
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010083 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010084 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +000010085 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +000010086
10087 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010088 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010089 SingleFunctionExpression =
10090 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +000010091 if (SingleFunctionExpression.isInvalid()) {
10092 SrcExpr = ExprError();
10093 return true;
10094 }
10095 }
John McCall0009fcc2011-04-26 20:42:42 +000010096 }
10097
10098 if (!SingleFunctionExpression.isUsable()) {
10099 if (complain) {
10100 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10101 << ovl.Expression->getName()
10102 << DestTypeForComplaining
10103 << OpRangeForComplaining
10104 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010105 NoteAllOverloadCandidates(SrcExpr.get());
10106
10107 SrcExpr = ExprError();
10108 return true;
10109 }
10110
10111 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010112 }
10113
John McCall50a2c2c2011-10-11 23:14:30 +000010114 SrcExpr = SingleFunctionExpression;
10115 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010116}
10117
Douglas Gregorcabea402009-09-22 15:41:20 +000010118/// \brief Add a single candidate to the overload set.
10119static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010120 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010121 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010122 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010123 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010124 bool PartialOverloading,
10125 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010126 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010127 if (isa<UsingShadowDecl>(Callee))
10128 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10129
Douglas Gregorcabea402009-09-22 15:41:20 +000010130 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010131 if (ExplicitTemplateArgs) {
10132 assert(!KnownValid && "Explicit template arguments?");
10133 return;
10134 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010135 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10136 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010137 return;
John McCalld14a8642009-11-21 08:51:07 +000010138 }
10139
10140 if (FunctionTemplateDecl *FuncTemplate
10141 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010142 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010143 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010144 return;
10145 }
10146
Richard Smith95ce4f62011-06-26 22:19:54 +000010147 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010148}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010149
Douglas Gregorcabea402009-09-22 15:41:20 +000010150/// \brief Add the overload candidates named by callee and/or found by argument
10151/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010152void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010153 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010154 OverloadCandidateSet &CandidateSet,
10155 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010156
10157#ifndef NDEBUG
10158 // Verify that ArgumentDependentLookup is consistent with the rules
10159 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010160 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010161 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10162 // and let Y be the lookup set produced by argument dependent
10163 // lookup (defined as follows). If X contains
10164 //
10165 // -- a declaration of a class member, or
10166 //
10167 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010168 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010169 //
10170 // -- a declaration that is neither a function or a function
10171 // template
10172 //
10173 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010174
John McCall57500772009-12-16 12:17:52 +000010175 if (ULE->requiresADL()) {
10176 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10177 E = ULE->decls_end(); I != E; ++I) {
10178 assert(!(*I)->getDeclContext()->isRecord());
10179 assert(isa<UsingShadowDecl>(*I) ||
10180 !(*I)->getDeclContext()->isFunctionOrMethod());
10181 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010182 }
10183 }
10184#endif
10185
John McCall57500772009-12-16 12:17:52 +000010186 // It would be nice to avoid this copy.
10187 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +000010188 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010189 if (ULE->hasExplicitTemplateArgs()) {
10190 ULE->copyTemplateArgumentsInto(TABuffer);
10191 ExplicitTemplateArgs = &TABuffer;
10192 }
10193
10194 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10195 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010196 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10197 CandidateSet, PartialOverloading,
10198 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010199
John McCall57500772009-12-16 12:17:52 +000010200 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +000010201 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +000010202 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010203 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010204 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010205}
John McCalld681c392009-12-16 08:11:27 +000010206
Richard Smith0603bbb2013-06-12 22:56:54 +000010207/// Determine whether a declaration with the specified name could be moved into
10208/// a different namespace.
10209static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10210 switch (Name.getCXXOverloadedOperator()) {
10211 case OO_New: case OO_Array_New:
10212 case OO_Delete: case OO_Array_Delete:
10213 return false;
10214
10215 default:
10216 return true;
10217 }
10218}
10219
Richard Smith998a5912011-06-05 22:42:48 +000010220/// Attempt to recover from an ill-formed use of a non-dependent name in a
10221/// template, where the non-dependent name was declared after the template
10222/// was defined. This is common in code written for a compilers which do not
10223/// correctly implement two-stage name lookup.
10224///
10225/// Returns true if a viable candidate was found and a diagnostic was issued.
10226static bool
10227DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10228 const CXXScopeSpec &SS, LookupResult &R,
10229 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010230 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010231 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10232 return false;
10233
10234 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010235 if (DC->isTransparentContext())
10236 continue;
10237
Richard Smith998a5912011-06-05 22:42:48 +000010238 SemaRef.LookupQualifiedName(R, DC);
10239
10240 if (!R.empty()) {
10241 R.suppressDiagnostics();
10242
10243 if (isa<CXXRecordDecl>(DC)) {
10244 // Don't diagnose names we find in classes; we get much better
10245 // diagnostics for these from DiagnoseEmptyLookup.
10246 R.clear();
10247 return false;
10248 }
10249
10250 OverloadCandidateSet Candidates(FnLoc);
10251 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10252 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010253 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010254 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010255
10256 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010257 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010258 // No viable functions. Don't bother the user with notes for functions
10259 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010260 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010261 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010262 }
Richard Smith998a5912011-06-05 22:42:48 +000010263
10264 // Find the namespaces where ADL would have looked, and suggest
10265 // declaring the function there instead.
10266 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10267 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010268 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010269 AssociatedNamespaces,
10270 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010271 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010272 if (canBeDeclaredInNamespace(R.getLookupName())) {
10273 DeclContext *Std = SemaRef.getStdNamespace();
10274 for (Sema::AssociatedNamespaceSet::iterator
10275 it = AssociatedNamespaces.begin(),
10276 end = AssociatedNamespaces.end(); it != end; ++it) {
10277 // Never suggest declaring a function within namespace 'std'.
10278 if (Std && Std->Encloses(*it))
10279 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010280
Richard Smith0603bbb2013-06-12 22:56:54 +000010281 // Never suggest declaring a function within a namespace with a
10282 // reserved name, like __gnu_cxx.
10283 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10284 if (NS &&
10285 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10286 continue;
10287
10288 SuggestedNamespaces.insert(*it);
10289 }
Richard Smith998a5912011-06-05 22:42:48 +000010290 }
10291
10292 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10293 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010294 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010295 SemaRef.Diag(Best->Function->getLocation(),
10296 diag::note_not_found_by_two_phase_lookup)
10297 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010298 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010299 SemaRef.Diag(Best->Function->getLocation(),
10300 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010301 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010302 } else {
10303 // FIXME: It would be useful to list the associated namespaces here,
10304 // but the diagnostics infrastructure doesn't provide a way to produce
10305 // a localized representation of a list of items.
10306 SemaRef.Diag(Best->Function->getLocation(),
10307 diag::note_not_found_by_two_phase_lookup)
10308 << R.getLookupName() << 2;
10309 }
10310
10311 // Try to recover by calling this function.
10312 return true;
10313 }
10314
10315 R.clear();
10316 }
10317
10318 return false;
10319}
10320
10321/// Attempt to recover from ill-formed use of a non-dependent operator in a
10322/// template, where the non-dependent operator was declared after the template
10323/// was defined.
10324///
10325/// Returns true if a viable candidate was found and a diagnostic was issued.
10326static bool
10327DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10328 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010329 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010330 DeclarationName OpName =
10331 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10332 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10333 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010334 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010335}
10336
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010337namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010338class BuildRecoveryCallExprRAII {
10339 Sema &SemaRef;
10340public:
10341 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10342 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10343 SemaRef.IsBuildingRecoveryCallExpr = true;
10344 }
10345
10346 ~BuildRecoveryCallExprRAII() {
10347 SemaRef.IsBuildingRecoveryCallExpr = false;
10348 }
10349};
10350
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010351}
10352
John McCalld681c392009-12-16 08:11:27 +000010353/// Attempts to recover from a call where no functions were found.
10354///
10355/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010356static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010357BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010358 UnresolvedLookupExpr *ULE,
10359 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010360 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010361 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010362 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010363 // Do not try to recover if it is already building a recovery call.
10364 // This stops infinite loops for template instantiations like
10365 //
10366 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10367 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10368 //
10369 if (SemaRef.IsBuildingRecoveryCallExpr)
10370 return ExprError();
10371 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010372
10373 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010374 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010375 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010376
John McCall57500772009-12-16 12:17:52 +000010377 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +000010378 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010379 if (ULE->hasExplicitTemplateArgs()) {
10380 ULE->copyTemplateArgumentsInto(TABuffer);
10381 ExplicitTemplateArgs = &TABuffer;
10382 }
10383
John McCalld681c392009-12-16 08:11:27 +000010384 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10385 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010386 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10387 ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010388 NoTypoCorrectionCCC RejectAll;
10389 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10390 (CorrectionCandidateCallback*)&Validator :
10391 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010392 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010393 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010394 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010395 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010396 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010397 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010398
John McCall57500772009-12-16 12:17:52 +000010399 assert(!R.empty() && "lookup results empty despite recovery");
10400
10401 // Build an implicit member call if appropriate. Just drop the
10402 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010403 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010404 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010405 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10406 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010407 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010408 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010409 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010410 else
10411 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10412
10413 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010414 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010415
10416 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010417 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010418 // end up here.
John McCallb268a282010-08-23 23:25:46 +000010419 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010420 MultiExprArg(Args.data(), Args.size()),
10421 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010422}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010423
Sam Panzer0f384432012-08-21 00:52:01 +000010424/// \brief Constructs and populates an OverloadedCandidateSet from
10425/// the given function.
10426/// \returns true when an the ExprResult output parameter has been set.
10427bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10428 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010429 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010430 SourceLocation RParenLoc,
10431 OverloadCandidateSet *CandidateSet,
10432 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010433#ifndef NDEBUG
10434 if (ULE->requiresADL()) {
10435 // To do ADL, we must have found an unqualified name.
10436 assert(!ULE->getQualifier() && "qualified name with ADL");
10437
10438 // We don't perform ADL for implicit declarations of builtins.
10439 // Verify that this was correctly set up.
10440 FunctionDecl *F;
10441 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10442 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10443 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010444 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010445
John McCall57500772009-12-16 12:17:52 +000010446 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010447 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010448 }
John McCall57500772009-12-16 12:17:52 +000010449#endif
10450
John McCall4124c492011-10-17 18:40:02 +000010451 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010452 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010453 *Result = ExprError();
10454 return true;
10455 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010456
John McCall57500772009-12-16 12:17:52 +000010457 // Add the functions denoted by the callee to the set of candidate
10458 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010459 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010460
10461 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010462 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10463 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010464 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010465 // In Microsoft mode, if we are inside a template class member function then
10466 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010467 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010468 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010469 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010470 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010471 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010472 Context.DependentTy, VK_RValue,
10473 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010474 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +000010475 *Result = Owned(CE);
10476 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010477 }
Sam Panzer0f384432012-08-21 00:52:01 +000010478 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010479 }
John McCalld681c392009-12-16 08:11:27 +000010480
John McCall4124c492011-10-17 18:40:02 +000010481 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010482 return false;
10483}
John McCall4124c492011-10-17 18:40:02 +000010484
Sam Panzer0f384432012-08-21 00:52:01 +000010485/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10486/// the completed call expression. If overload resolution fails, emits
10487/// diagnostics and returns ExprError()
10488static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10489 UnresolvedLookupExpr *ULE,
10490 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010491 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010492 SourceLocation RParenLoc,
10493 Expr *ExecConfig,
10494 OverloadCandidateSet *CandidateSet,
10495 OverloadCandidateSet::iterator *Best,
10496 OverloadingResult OverloadResult,
10497 bool AllowTypoCorrection) {
10498 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010499 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010500 RParenLoc, /*EmptyLookup=*/true,
10501 AllowTypoCorrection);
10502
10503 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010504 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010505 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010506 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010507 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10508 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010509 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010510 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10511 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010512 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010513
Richard Smith998a5912011-06-05 22:42:48 +000010514 case OR_No_Viable_Function: {
10515 // Try to recover by looking for viable functions which the user might
10516 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010517 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010518 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010519 /*EmptyLookup=*/false,
10520 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010521 if (!Recovery.isInvalid())
10522 return Recovery;
10523
Sam Panzer0f384432012-08-21 00:52:01 +000010524 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010525 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010526 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010527 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010528 break;
Richard Smith998a5912011-06-05 22:42:48 +000010529 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010530
10531 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010532 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010533 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010534 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010535 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010536
Sam Panzer0f384432012-08-21 00:52:01 +000010537 case OR_Deleted: {
10538 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10539 << (*Best)->Function->isDeleted()
10540 << ULE->getName()
10541 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10542 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010543 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010544
Sam Panzer0f384432012-08-21 00:52:01 +000010545 // We emitted an error for the unvailable/deleted function call but keep
10546 // the call in the AST.
10547 FunctionDecl *FDecl = (*Best)->Function;
10548 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010549 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10550 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010551 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010552 }
10553
Douglas Gregorb412e172010-07-25 18:17:45 +000010554 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010555 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010556}
10557
Sam Panzer0f384432012-08-21 00:52:01 +000010558/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10559/// (which eventually refers to the declaration Func) and the call
10560/// arguments Args/NumArgs, attempt to resolve the function call down
10561/// to a specific function. If overload resolution succeeds, returns
10562/// the call expression produced by overload resolution.
10563/// Otherwise, emits diagnostics and returns ExprError.
10564ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10565 UnresolvedLookupExpr *ULE,
10566 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010567 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010568 SourceLocation RParenLoc,
10569 Expr *ExecConfig,
10570 bool AllowTypoCorrection) {
10571 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10572 ExprResult result;
10573
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010574 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10575 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010576 return result;
10577
10578 OverloadCandidateSet::iterator Best;
10579 OverloadingResult OverloadResult =
10580 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10581
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010582 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010583 RParenLoc, ExecConfig, &CandidateSet,
10584 &Best, OverloadResult,
10585 AllowTypoCorrection);
10586}
10587
John McCall4c4c1df2010-01-26 03:27:55 +000010588static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010589 return Functions.size() > 1 ||
10590 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10591}
10592
Douglas Gregor084d8552009-03-13 23:49:33 +000010593/// \brief Create a unary operation that may resolve to an overloaded
10594/// operator.
10595///
10596/// \param OpLoc The location of the operator itself (e.g., '*').
10597///
10598/// \param OpcIn The UnaryOperator::Opcode that describes this
10599/// operator.
10600///
James Dennett18348b62012-06-22 08:52:37 +000010601/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010602/// considered by overload resolution. The caller needs to build this
10603/// set based on the context using, e.g.,
10604/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10605/// set should not contain any member functions; those will be added
10606/// by CreateOverloadedUnaryOp().
10607///
James Dennett91738ff2012-06-22 10:32:46 +000010608/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010609ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010610Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10611 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010612 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010613 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010614
10615 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10616 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10617 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010618 // TODO: provide better source location info.
10619 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010620
John McCall4124c492011-10-17 18:40:02 +000010621 if (checkPlaceholderForOverload(*this, Input))
10622 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010623
Douglas Gregor084d8552009-03-13 23:49:33 +000010624 Expr *Args[2] = { Input, 0 };
10625 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010626
Douglas Gregor084d8552009-03-13 23:49:33 +000010627 // For post-increment and post-decrement, add the implicit '0' as
10628 // the second argument, so that we know this is a post-increment or
10629 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010630 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010631 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010632 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10633 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010634 NumArgs = 2;
10635 }
10636
Richard Smithe54c3072013-05-05 15:51:06 +000010637 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10638
Douglas Gregor084d8552009-03-13 23:49:33 +000010639 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010640 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +000010641 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010642 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +000010643 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010644 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +000010645 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010646
John McCall58cc69d2010-01-27 01:50:18 +000010647 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010648 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010649 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010650 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010651 /*ADL*/ true, IsOverloaded(Fns),
10652 Fns.begin(), Fns.end());
Richard Smithe54c3072013-05-05 15:51:06 +000010653 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregor084d8552009-03-13 23:49:33 +000010654 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010655 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010656 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010657 }
10658
10659 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010660 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010661
10662 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010663 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010664
10665 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010666 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010667
John McCall4c4c1df2010-01-26 03:27:55 +000010668 // Add candidates from ADL.
Richard Smithe54c3072013-05-05 15:51:06 +000010669 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10670 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall4c4c1df2010-01-26 03:27:55 +000010671 CandidateSet);
10672
Douglas Gregor084d8552009-03-13 23:49:33 +000010673 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010674 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010675
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010676 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10677
Douglas Gregor084d8552009-03-13 23:49:33 +000010678 // Perform overload resolution.
10679 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010680 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010681 case OR_Success: {
10682 // We found a built-in operator or an overloaded operator.
10683 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010684
Douglas Gregor084d8552009-03-13 23:49:33 +000010685 if (FnDecl) {
10686 // We matched an overloaded operator. Build a call to that
10687 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010688
Douglas Gregor084d8552009-03-13 23:49:33 +000010689 // Convert the arguments.
10690 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010691 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010692
John Wiegley01296292011-04-08 18:41:53 +000010693 ExprResult InputRes =
10694 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10695 Best->FoundDecl, Method);
10696 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010697 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010698 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010699 } else {
10700 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010701 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010702 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010703 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010704 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010705 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010706 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010707 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010708 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010709 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010710 }
10711
Douglas Gregor084d8552009-03-13 23:49:33 +000010712 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010713 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010714 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010715 if (FnExpr.isInvalid())
10716 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010717
Richard Smithc1564702013-11-15 02:58:23 +000010718 // Determine the result type.
10719 QualType ResultTy = FnDecl->getResultType();
10720 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10721 ResultTy = ResultTy.getNonLValueExprType(Context);
10722
Eli Friedman030eee42009-11-18 03:58:17 +000010723 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010724 CallExpr *TheCall =
Richard Smithe54c3072013-05-05 15:51:06 +000010725 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010726 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010727
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010728 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010729 FnDecl))
10730 return ExprError();
10731
John McCallb268a282010-08-23 23:25:46 +000010732 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010733 } else {
10734 // We matched a built-in operator. Convert the arguments, then
10735 // break out so that we will build the appropriate built-in
10736 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010737 ExprResult InputRes =
10738 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10739 Best->Conversions[0], AA_Passing);
10740 if (InputRes.isInvalid())
10741 return ExprError();
10742 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010743 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010744 }
John Wiegley01296292011-04-08 18:41:53 +000010745 }
10746
10747 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010748 // This is an erroneous use of an operator which can be overloaded by
10749 // a non-member function. Check for non-member operators which were
10750 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010751 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010752 // FIXME: Recover by calling the found function.
10753 return ExprError();
10754
John Wiegley01296292011-04-08 18:41:53 +000010755 // No viable function; fall through to handling this as a
10756 // built-in operator, which will produce an error message for us.
10757 break;
10758
10759 case OR_Ambiguous:
10760 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10761 << UnaryOperator::getOpcodeStr(Opc)
10762 << Input->getType()
10763 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010764 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010765 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10766 return ExprError();
10767
10768 case OR_Deleted:
10769 Diag(OpLoc, diag::err_ovl_deleted_oper)
10770 << Best->Function->isDeleted()
10771 << UnaryOperator::getOpcodeStr(Opc)
10772 << getDeletedOrUnavailableSuffix(Best->Function)
10773 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010774 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010775 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010776 return ExprError();
10777 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010778
10779 // Either we found no viable overloaded operator or we matched a
10780 // built-in operator. In either case, fall through to trying to
10781 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010782 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010783}
10784
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010785/// \brief Create a binary operation that may resolve to an overloaded
10786/// operator.
10787///
10788/// \param OpLoc The location of the operator itself (e.g., '+').
10789///
10790/// \param OpcIn The BinaryOperator::Opcode that describes this
10791/// operator.
10792///
James Dennett18348b62012-06-22 08:52:37 +000010793/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010794/// considered by overload resolution. The caller needs to build this
10795/// set based on the context using, e.g.,
10796/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10797/// set should not contain any member functions; those will be added
10798/// by CreateOverloadedBinOp().
10799///
10800/// \param LHS Left-hand argument.
10801/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010802ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010803Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010804 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010805 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010806 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010807 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010808 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010809
10810 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10811 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10812 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10813
10814 // If either side is type-dependent, create an appropriate dependent
10815 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010816 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010817 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010818 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010819 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010820 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010821 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010822 Context.DependentTy,
10823 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010824 OpLoc,
10825 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010826
Douglas Gregor5287f092009-11-05 00:51:44 +000010827 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10828 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010829 VK_LValue,
10830 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010831 Context.DependentTy,
10832 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010833 OpLoc,
10834 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010835 }
John McCall4c4c1df2010-01-26 03:27:55 +000010836
10837 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010838 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010839 // TODO: provide better source location info in DNLoc component.
10840 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010841 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010842 = UnresolvedLookupExpr::Create(Context, NamingClass,
10843 NestedNameSpecifierLoc(), OpNameInfo,
10844 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010845 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010846 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10847 Context.DependentTy, VK_RValue,
10848 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010849 }
10850
John McCall4124c492011-10-17 18:40:02 +000010851 // Always do placeholder-like conversions on the RHS.
10852 if (checkPlaceholderForOverload(*this, Args[1]))
10853 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010854
John McCall526ab472011-10-25 17:37:35 +000010855 // Do placeholder-like conversion on the LHS; note that we should
10856 // not get here with a PseudoObject LHS.
10857 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010858 if (checkPlaceholderForOverload(*this, Args[0]))
10859 return ExprError();
10860
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010861 // If this is the assignment operator, we only perform overload resolution
10862 // if the left-hand side is a class or enumeration type. This is actually
10863 // a hack. The standard requires that we do overload resolution between the
10864 // various built-in candidates, but as DR507 points out, this can lead to
10865 // problems. So we do it this way, which pretty much follows what GCC does.
10866 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010867 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010868 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010869
John McCalle26a8722010-12-04 08:14:53 +000010870 // If this is the .* operator, which is not overloadable, just
10871 // create a built-in binary operator.
10872 if (Opc == BO_PtrMemD)
10873 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10874
Douglas Gregor084d8552009-03-13 23:49:33 +000010875 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010876 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010877
10878 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010879 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010880
10881 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010882 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010883
John McCall4c4c1df2010-01-26 03:27:55 +000010884 // Add candidates from ADL.
10885 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010886 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010887 /*ExplicitTemplateArgs*/ 0,
10888 CandidateSet);
10889
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010890 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010891 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010892
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010893 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10894
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010895 // Perform overload resolution.
10896 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010897 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010898 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010899 // We found a built-in operator or an overloaded operator.
10900 FunctionDecl *FnDecl = Best->Function;
10901
10902 if (FnDecl) {
10903 // We matched an overloaded operator. Build a call to that
10904 // operator.
10905
10906 // Convert the arguments.
10907 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010908 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010909 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010910
Chandler Carruth8e543b32010-12-12 08:17:55 +000010911 ExprResult Arg1 =
10912 PerformCopyInitialization(
10913 InitializedEntity::InitializeParameter(Context,
10914 FnDecl->getParamDecl(0)),
10915 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010916 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010917 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010918
John Wiegley01296292011-04-08 18:41:53 +000010919 ExprResult Arg0 =
10920 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10921 Best->FoundDecl, Method);
10922 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010923 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010924 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010925 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010926 } else {
10927 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010928 ExprResult Arg0 = PerformCopyInitialization(
10929 InitializedEntity::InitializeParameter(Context,
10930 FnDecl->getParamDecl(0)),
10931 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010932 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010933 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010934
Chandler Carruth8e543b32010-12-12 08:17:55 +000010935 ExprResult Arg1 =
10936 PerformCopyInitialization(
10937 InitializedEntity::InitializeParameter(Context,
10938 FnDecl->getParamDecl(1)),
10939 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010940 if (Arg1.isInvalid())
10941 return ExprError();
10942 Args[0] = LHS = Arg0.takeAs<Expr>();
10943 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010944 }
10945
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010946 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010947 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000010948 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010949 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010950 if (FnExpr.isInvalid())
10951 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010952
Richard Smithc1564702013-11-15 02:58:23 +000010953 // Determine the result type.
10954 QualType ResultTy = FnDecl->getResultType();
10955 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10956 ResultTy = ResultTy.getNonLValueExprType(Context);
10957
John McCallb268a282010-08-23 23:25:46 +000010958 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010959 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010960 Args, ResultTy, VK, OpLoc,
10961 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010962
10963 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010964 FnDecl))
10965 return ExprError();
10966
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000010967 ArrayRef<const Expr *> ArgsArray(Args, 2);
10968 // Cut off the implicit 'this'.
10969 if (isa<CXXMethodDecl>(FnDecl))
10970 ArgsArray = ArgsArray.slice(1);
10971 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10972 TheCall->getSourceRange(), VariadicDoesNotApply);
10973
John McCallb268a282010-08-23 23:25:46 +000010974 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010975 } else {
10976 // We matched a built-in operator. Convert the arguments, then
10977 // break out so that we will build the appropriate built-in
10978 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010979 ExprResult ArgsRes0 =
10980 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10981 Best->Conversions[0], AA_Passing);
10982 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010983 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010984 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010985
John Wiegley01296292011-04-08 18:41:53 +000010986 ExprResult ArgsRes1 =
10987 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10988 Best->Conversions[1], AA_Passing);
10989 if (ArgsRes1.isInvalid())
10990 return ExprError();
10991 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010992 break;
10993 }
10994 }
10995
Douglas Gregor66950a32009-09-30 21:46:01 +000010996 case OR_No_Viable_Function: {
10997 // C++ [over.match.oper]p9:
10998 // If the operator is the operator , [...] and there are no
10999 // viable functions, then the operator is assumed to be the
11000 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011001 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011002 break;
11003
Chandler Carruth8e543b32010-12-12 08:17:55 +000011004 // For class as left operand for assignment or compound assigment
11005 // operator do not fall through to handling in built-in, but report that
11006 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011007 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011008 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011009 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011010 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11011 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011012 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011013 if (Args[0]->getType()->isIncompleteType()) {
11014 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11015 << Args[0]->getType()
11016 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11017 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011018 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011019 // This is an erroneous use of an operator which can be overloaded by
11020 // a non-member function. Check for non-member operators which were
11021 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011022 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011023 // FIXME: Recover by calling the found function.
11024 return ExprError();
11025
Douglas Gregor66950a32009-09-30 21:46:01 +000011026 // No viable function; try to create a built-in operation, which will
11027 // produce an error. Then, show the non-viable candidates.
11028 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011029 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011030 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011031 "C++ binary operator overloading is missing candidates!");
11032 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011033 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011034 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011035 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011036 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011037
11038 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011039 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011040 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011041 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011042 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011043 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011044 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011045 return ExprError();
11046
11047 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011048 if (isImplicitlyDeleted(Best->Function)) {
11049 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11050 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011051 << Context.getRecordType(Method->getParent())
11052 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011053
Richard Smithde1a4872012-12-28 12:23:24 +000011054 // The user probably meant to call this special member. Just
11055 // explain why it's deleted.
11056 NoteDeletedFunction(Method);
11057 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011058 } else {
11059 Diag(OpLoc, diag::err_ovl_deleted_oper)
11060 << Best->Function->isDeleted()
11061 << BinaryOperator::getOpcodeStr(Opc)
11062 << getDeletedOrUnavailableSuffix(Best->Function)
11063 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11064 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011065 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011066 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011067 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011068 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011069
Douglas Gregor66950a32009-09-30 21:46:01 +000011070 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011071 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011072}
11073
John McCalldadc5752010-08-24 06:29:42 +000011074ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011075Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11076 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011077 Expr *Base, Expr *Idx) {
11078 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011079 DeclarationName OpName =
11080 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11081
11082 // If either side is type-dependent, create an appropriate dependent
11083 // expression.
11084 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11085
John McCall58cc69d2010-01-27 01:50:18 +000011086 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011087 // CHECKME: no 'operator' keyword?
11088 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11089 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011090 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011091 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011092 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011093 /*ADL*/ true, /*Overloaded*/ false,
11094 UnresolvedSetIterator(),
11095 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011096 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011097
Sebastian Redladba46e2009-10-29 20:17:01 +000011098 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011099 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000011100 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000011101 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000011102 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000011103 }
11104
John McCall4124c492011-10-17 18:40:02 +000011105 // Handle placeholders on both operands.
11106 if (checkPlaceholderForOverload(*this, Args[0]))
11107 return ExprError();
11108 if (checkPlaceholderForOverload(*this, Args[1]))
11109 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011110
Sebastian Redladba46e2009-10-29 20:17:01 +000011111 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000011112 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011113
11114 // Subscript can only be overloaded as a member function.
11115
11116 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011117 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011118
11119 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011120 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011121
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011122 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11123
Sebastian Redladba46e2009-10-29 20:17:01 +000011124 // Perform overload resolution.
11125 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011126 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011127 case OR_Success: {
11128 // We found a built-in operator or an overloaded operator.
11129 FunctionDecl *FnDecl = Best->Function;
11130
11131 if (FnDecl) {
11132 // We matched an overloaded operator. Build a call to that
11133 // operator.
11134
John McCalla0296f72010-03-19 07:35:19 +000011135 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011136
Sebastian Redladba46e2009-10-29 20:17:01 +000011137 // Convert the arguments.
11138 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011139 ExprResult Arg0 =
11140 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
11141 Best->FoundDecl, Method);
11142 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011143 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011144 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011145
Anders Carlssona68e51e2010-01-29 18:37:50 +000011146 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011147 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011148 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011149 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011150 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011151 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000011152 Owned(Args[1]));
11153 if (InputInit.isInvalid())
11154 return ExprError();
11155
11156 Args[1] = InputInit.takeAs<Expr>();
11157
Sebastian Redladba46e2009-10-29 20:17:01 +000011158 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011159 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11160 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011161 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011162 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011163 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011164 OpLocInfo.getLoc(),
11165 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011166 if (FnExpr.isInvalid())
11167 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011168
Richard Smithc1564702013-11-15 02:58:23 +000011169 // Determine the result type
11170 QualType ResultTy = FnDecl->getResultType();
11171 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11172 ResultTy = ResultTy.getNonLValueExprType(Context);
11173
John McCallb268a282010-08-23 23:25:46 +000011174 CXXOperatorCallExpr *TheCall =
11175 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011176 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011177 ResultTy, VK, RLoc,
11178 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011179
John McCallb268a282010-08-23 23:25:46 +000011180 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000011181 FnDecl))
11182 return ExprError();
11183
John McCallb268a282010-08-23 23:25:46 +000011184 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011185 } else {
11186 // We matched a built-in operator. Convert the arguments, then
11187 // break out so that we will build the appropriate built-in
11188 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011189 ExprResult ArgsRes0 =
11190 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11191 Best->Conversions[0], AA_Passing);
11192 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011193 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011194 Args[0] = ArgsRes0.take();
11195
11196 ExprResult ArgsRes1 =
11197 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11198 Best->Conversions[1], AA_Passing);
11199 if (ArgsRes1.isInvalid())
11200 return ExprError();
11201 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011202
11203 break;
11204 }
11205 }
11206
11207 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011208 if (CandidateSet.empty())
11209 Diag(LLoc, diag::err_ovl_no_oper)
11210 << Args[0]->getType() << /*subscript*/ 0
11211 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11212 else
11213 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11214 << Args[0]->getType()
11215 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011216 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011217 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011218 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011219 }
11220
11221 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011222 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011223 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011224 << Args[0]->getType() << Args[1]->getType()
11225 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011226 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011227 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011228 return ExprError();
11229
11230 case OR_Deleted:
11231 Diag(LLoc, diag::err_ovl_deleted_oper)
11232 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011233 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011234 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011235 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011236 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011237 return ExprError();
11238 }
11239
11240 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011241 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011242}
11243
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011244/// BuildCallToMemberFunction - Build a call to a member
11245/// function. MemExpr is the expression that refers to the member
11246/// function (and includes the object parameter), Args/NumArgs are the
11247/// arguments to the function call (not including the object
11248/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011249/// expression refers to a non-static member function or an overloaded
11250/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011251ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011252Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011253 SourceLocation LParenLoc,
11254 MultiExprArg Args,
11255 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011256 assert(MemExprE->getType() == Context.BoundMemberTy ||
11257 MemExprE->getType() == Context.OverloadTy);
11258
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011259 // Dig out the member expression. This holds both the object
11260 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011261 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011262
John McCall0009fcc2011-04-26 20:42:42 +000011263 // Determine whether this is a call to a pointer-to-member function.
11264 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11265 assert(op->getType() == Context.BoundMemberTy);
11266 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11267
11268 QualType fnType =
11269 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11270
11271 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11272 QualType resultType = proto->getCallResultType(Context);
11273 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
11274
11275 // Check that the object type isn't more qualified than the
11276 // member function we're calling.
11277 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11278
11279 QualType objectType = op->getLHS()->getType();
11280 if (op->getOpcode() == BO_PtrMemI)
11281 objectType = objectType->castAs<PointerType>()->getPointeeType();
11282 Qualifiers objectQuals = objectType.getQualifiers();
11283
11284 Qualifiers difference = objectQuals - funcQuals;
11285 difference.removeObjCGCAttr();
11286 difference.removeAddressSpace();
11287 if (difference) {
11288 std::string qualsString = difference.getAsString();
11289 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11290 << fnType.getUnqualifiedType()
11291 << qualsString
11292 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11293 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011294
John McCall0009fcc2011-04-26 20:42:42 +000011295 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011296 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011297 resultType, valueKind, RParenLoc);
11298
11299 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011300 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000011301 call, 0))
11302 return ExprError();
11303
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011304 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011305 return ExprError();
11306
Richard Trieu9be9c682013-06-22 02:30:38 +000011307 if (CheckOtherCall(call, proto))
11308 return ExprError();
11309
John McCall0009fcc2011-04-26 20:42:42 +000011310 return MaybeBindToTemporary(call);
11311 }
11312
John McCall4124c492011-10-17 18:40:02 +000011313 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011314 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011315 return ExprError();
11316
John McCall10eae182009-11-30 22:42:35 +000011317 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011318 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000011319 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011320 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000011321 if (isa<MemberExpr>(NakedMemExpr)) {
11322 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011323 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011324 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011325 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011326 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011327 } else {
11328 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011329 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011330
John McCall6e9f8f62009-12-03 04:06:58 +000011331 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011332 Expr::Classification ObjectClassification
11333 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11334 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011335
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011336 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000011337 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000011338
John McCall2d74de92009-12-01 22:10:20 +000011339 // FIXME: avoid copy.
11340 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11341 if (UnresExpr->hasExplicitTemplateArgs()) {
11342 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11343 TemplateArgs = &TemplateArgsBuffer;
11344 }
11345
John McCall10eae182009-11-30 22:42:35 +000011346 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11347 E = UnresExpr->decls_end(); I != E; ++I) {
11348
John McCall6e9f8f62009-12-03 04:06:58 +000011349 NamedDecl *Func = *I;
11350 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11351 if (isa<UsingShadowDecl>(Func))
11352 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11353
Douglas Gregor02824322011-01-26 19:30:28 +000011354
Francois Pichet64225792011-01-18 05:04:39 +000011355 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011356 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011357 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011358 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011359 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011360 // If explicit template arguments were provided, we can't call a
11361 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011362 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011363 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011364
John McCalla0296f72010-03-19 07:35:19 +000011365 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011366 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011367 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011368 } else {
John McCall10eae182009-11-30 22:42:35 +000011369 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011370 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011371 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011372 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011373 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011374 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011375 }
Mike Stump11289f42009-09-09 15:08:12 +000011376
John McCall10eae182009-11-30 22:42:35 +000011377 DeclarationName DeclName = UnresExpr->getMemberName();
11378
John McCall4124c492011-10-17 18:40:02 +000011379 UnbridgedCasts.restore();
11380
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011381 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011382 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011383 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011384 case OR_Success:
11385 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011386 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011387 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011388 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11389 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011390 // If FoundDecl is different from Method (such as if one is a template
11391 // and the other a specialization), make sure DiagnoseUseOfDecl is
11392 // called on both.
11393 // FIXME: This would be more comprehensively addressed by modifying
11394 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11395 // being used.
11396 if (Method != FoundDecl.getDecl() &&
11397 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11398 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011399 break;
11400
11401 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011402 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011403 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011404 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011405 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011406 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011407 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011408
11409 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011410 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011411 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011412 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011413 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011414 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011415
11416 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011417 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011418 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011419 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011420 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011421 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011423 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011424 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011425 }
11426
John McCall16df1e52010-03-30 21:47:33 +000011427 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011428
John McCall2d74de92009-12-01 22:10:20 +000011429 // If overload resolution picked a static member, build a
11430 // non-member call based on that function.
11431 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011432 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11433 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011434 }
11435
John McCall10eae182009-11-30 22:42:35 +000011436 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011437 }
11438
John McCall7decc9e2010-11-18 06:31:45 +000011439 QualType ResultType = Method->getResultType();
11440 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11441 ResultType = ResultType.getNonLValueExprType(Context);
11442
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011443 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011444 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011445 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011446 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011447
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011448 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011449 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011450 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011451 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011452
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011453 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011454 // We only need to do this if there was actually an overload; otherwise
11455 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011456 if (!Method->isStatic()) {
11457 ExprResult ObjectArg =
11458 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11459 FoundDecl, Method);
11460 if (ObjectArg.isInvalid())
11461 return ExprError();
11462 MemExpr->setBase(ObjectArg.take());
11463 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011464
11465 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011466 const FunctionProtoType *Proto =
11467 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011468 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011469 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011470 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011471
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011472 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011473
Richard Smith55ce3522012-06-25 20:30:08 +000011474 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011475 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011476
Anders Carlsson47061ee2011-05-06 14:25:31 +000011477 if ((isa<CXXConstructorDecl>(CurContext) ||
11478 isa<CXXDestructorDecl>(CurContext)) &&
11479 TheCall->getMethodDecl()->isPure()) {
11480 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11481
Chandler Carruth59259262011-06-27 08:31:58 +000011482 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011483 Diag(MemExpr->getLocStart(),
11484 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11485 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11486 << MD->getParent()->getDeclName();
11487
11488 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011489 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011490 }
John McCallb268a282010-08-23 23:25:46 +000011491 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011492}
11493
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011494/// BuildCallToObjectOfClassType - Build a call to an object of class
11495/// type (C++ [over.call.object]), which can end up invoking an
11496/// overloaded function call operator (@c operator()) or performing a
11497/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011498ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011499Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011500 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011501 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011502 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011503 if (checkPlaceholderForOverload(*this, Obj))
11504 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011505 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000011506
11507 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011508 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011509 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011510
John Wiegley01296292011-04-08 18:41:53 +000011511 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11512 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011513
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011514 // C++ [over.call.object]p1:
11515 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011516 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011517 // candidate functions includes at least the function call
11518 // operators of T. The function call operators of T are obtained by
11519 // ordinary lookup of the name operator() in the context of
11520 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000011521 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000011522 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011523
John Wiegley01296292011-04-08 18:41:53 +000011524 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011525 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011526 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011527
John McCall27b18f82009-11-17 02:14:36 +000011528 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11529 LookupQualifiedName(R, Record->getDecl());
11530 R.suppressDiagnostics();
11531
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011532 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011533 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011534 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011535 Object.get()->Classify(Context),
11536 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011537 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011539
Douglas Gregorab7897a2008-11-19 22:57:39 +000011540 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011541 // In addition, for each (non-explicit in C++0x) conversion function
11542 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011543 //
11544 // operator conversion-type-id () cv-qualifier;
11545 //
11546 // where cv-qualifier is the same cv-qualification as, or a
11547 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011548 // denotes the type "pointer to function of (P1,...,Pn) returning
11549 // R", or the type "reference to pointer to function of
11550 // (P1,...,Pn) returning R", or the type "reference to function
11551 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011552 // is also considered as a candidate function. Similarly,
11553 // surrogate call functions are added to the set of candidate
11554 // functions for each conversion function declared in an
11555 // accessible base class provided the function is not hidden
11556 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011557 std::pair<CXXRecordDecl::conversion_iterator,
11558 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011559 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011560 for (CXXRecordDecl::conversion_iterator
11561 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011562 NamedDecl *D = *I;
11563 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11564 if (isa<UsingShadowDecl>(D))
11565 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011566
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011567 // Skip over templated conversion functions; they aren't
11568 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011569 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011570 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011571
John McCall6e9f8f62009-12-03 04:06:58 +000011572 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011573 if (!Conv->isExplicit()) {
11574 // Strip the reference type (if any) and then the pointer type (if
11575 // any) to get down to what might be a function type.
11576 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11577 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11578 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011579
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011580 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11581 {
11582 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011583 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011584 }
11585 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011586 }
Mike Stump11289f42009-09-09 15:08:12 +000011587
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011588 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11589
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011590 // Perform overload resolution.
11591 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011592 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011593 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011594 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011595 // Overload resolution succeeded; we'll build the appropriate call
11596 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011597 break;
11598
11599 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011600 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011601 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011602 << Object.get()->getType() << /*call*/ 1
11603 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011604 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011605 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011606 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011607 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011608 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011609 break;
11610
11611 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011612 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011613 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011614 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011615 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011616 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011617
11618 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011619 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011620 diag::err_ovl_deleted_object_call)
11621 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011622 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011623 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011624 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011625 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011626 break;
Mike Stump11289f42009-09-09 15:08:12 +000011627 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011628
Douglas Gregorb412e172010-07-25 18:17:45 +000011629 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011630 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011631
John McCall4124c492011-10-17 18:40:02 +000011632 UnbridgedCasts.restore();
11633
Douglas Gregorab7897a2008-11-19 22:57:39 +000011634 if (Best->Function == 0) {
11635 // Since there is no function declaration, this is one of the
11636 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011637 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011638 = cast<CXXConversionDecl>(
11639 Best->Conversions[0].UserDefined.ConversionFunction);
11640
John Wiegley01296292011-04-08 18:41:53 +000011641 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011642 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11643 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011644 assert(Conv == Best->FoundDecl.getDecl() &&
11645 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011646 // We selected one of the surrogate functions that converts the
11647 // object parameter to a function pointer. Perform the conversion
11648 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011649
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011650 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011651 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011652 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11653 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011654 if (Call.isInvalid())
11655 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011656 // Record usage of conversion in an implicit cast.
11657 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11658 CK_UserDefinedConversion,
11659 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011660
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011661 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011662 }
11663
John Wiegley01296292011-04-08 18:41:53 +000011664 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011665
Douglas Gregorab7897a2008-11-19 22:57:39 +000011666 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11667 // that calls this method, using Object for the implicit object
11668 // parameter and passing along the remaining arguments.
11669 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011670
11671 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011672 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011673 return ExprError();
11674
Chandler Carruth8e543b32010-12-12 08:17:55 +000011675 const FunctionProtoType *Proto =
11676 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011677
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011678 unsigned NumParams = Proto->getNumParams();
Mike Stump11289f42009-09-09 15:08:12 +000011679
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011680 DeclarationNameInfo OpLocInfo(
11681 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11682 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011683 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011684 HadMultipleCandidates,
11685 OpLocInfo.getLoc(),
11686 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011687 if (NewFn.isInvalid())
11688 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011689
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011690 // Build the full argument list for the method call (the implicit object
11691 // parameter is placed at the beginning of the list).
11692 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11693 MethodArgs[0] = Object.get();
11694 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11695
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011696 // Once we've built TheCall, all of the expressions are properly
11697 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011698 QualType ResultTy = Method->getResultType();
11699 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11700 ResultTy = ResultTy.getNonLValueExprType(Context);
11701
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011702 CXXOperatorCallExpr *TheCall = new (Context)
11703 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11704 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11705 ResultTy, VK, RParenLoc, false);
11706 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011707
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011708 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011709 Method))
11710 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011711
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011712 // We may have default arguments. If so, we need to allocate more
11713 // slots in the call for them.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011714 if (Args.size() < NumParams)
11715 TheCall->setNumArgs(Context, NumParams + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011716
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011717 bool IsError = false;
11718
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011719 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011720 ExprResult ObjRes =
11721 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11722 Best->FoundDecl, Method);
11723 if (ObjRes.isInvalid())
11724 IsError = true;
11725 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011726 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011727 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011728
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011729 // Check the argument types.
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011730 for (unsigned i = 0; i != NumParams; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011731 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011732 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011733 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011734
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011735 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011736
John McCalldadc5752010-08-24 06:29:42 +000011737 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011738 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011739 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011740 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011741 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011742
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011743 IsError |= InputInit.isInvalid();
11744 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011745 } else {
John McCalldadc5752010-08-24 06:29:42 +000011746 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011747 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11748 if (DefArg.isInvalid()) {
11749 IsError = true;
11750 break;
11751 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011752
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011753 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011754 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011755
11756 TheCall->setArg(i + 1, Arg);
11757 }
11758
11759 // If this is a variadic call, handle args passed through "...".
11760 if (Proto->isVariadic()) {
11761 // Promote the arguments (C99 6.5.2.2p7).
Alp Tokerb3fd5cf2014-01-21 00:32:38 +000011762 for (unsigned i = NumParams, e = Args.size(); i < e; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011763 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11764 IsError |= Arg.isInvalid();
11765 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011766 }
11767 }
11768
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011769 if (IsError) return true;
11770
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011771 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011772
Richard Smith55ce3522012-06-25 20:30:08 +000011773 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011774 return true;
11775
John McCalle172be52010-08-24 06:09:16 +000011776 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011777}
11778
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011779/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011780/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011781/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011782ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011783Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11784 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011785 assert(Base->getType()->isRecordType() &&
11786 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011787
John McCall4124c492011-10-17 18:40:02 +000011788 if (checkPlaceholderForOverload(*this, Base))
11789 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011790
John McCallbc077cf2010-02-08 23:07:23 +000011791 SourceLocation Loc = Base->getExprLoc();
11792
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011793 // C++ [over.ref]p1:
11794 //
11795 // [...] An expression x->m is interpreted as (x.operator->())->m
11796 // for a class object x of type T if T::operator->() exists and if
11797 // the operator is selected as the best match function by the
11798 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011799 DeclarationName OpName =
11800 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011801 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011802 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011803
John McCallbc077cf2010-02-08 23:07:23 +000011804 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011805 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011806 return ExprError();
11807
John McCall27b18f82009-11-17 02:14:36 +000011808 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11809 LookupQualifiedName(R, BaseRecord->getDecl());
11810 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011811
11812 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011813 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011814 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011815 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011816 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011817
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011818 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11819
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011820 // Perform overload resolution.
11821 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011822 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011823 case OR_Success:
11824 // Overload resolution succeeded; we'll build the call below.
11825 break;
11826
11827 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011828 if (CandidateSet.empty()) {
11829 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011830 if (NoArrowOperatorFound) {
11831 // Report this specific error to the caller instead of emitting a
11832 // diagnostic, as requested.
11833 *NoArrowOperatorFound = true;
11834 return ExprError();
11835 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011836 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11837 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011838 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011839 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011840 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011841 }
11842 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011843 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011844 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011845 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011846 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011847
11848 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011849 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11850 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011851 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011852 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011853
11854 case OR_Deleted:
11855 Diag(OpLoc, diag::err_ovl_deleted_oper)
11856 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011857 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011858 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011859 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011860 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011861 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011862 }
11863
John McCalla0296f72010-03-19 07:35:19 +000011864 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11865
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011866 // Convert the object parameter.
11867 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011868 ExprResult BaseResult =
11869 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11870 Best->FoundDecl, Method);
11871 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011872 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011873 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011874
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011875 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000011876 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011877 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011878 if (FnExpr.isInvalid())
11879 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011880
John McCall7decc9e2010-11-18 06:31:45 +000011881 QualType ResultTy = Method->getResultType();
11882 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11883 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011884 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011885 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011886 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011887
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011888 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011889 Method))
11890 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011891
11892 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011893}
11894
Richard Smithbcc22fc2012-03-09 08:00:36 +000011895/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11896/// a literal operator described by the provided lookup results.
11897ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11898 DeclarationNameInfo &SuffixInfo,
11899 ArrayRef<Expr*> Args,
11900 SourceLocation LitEndLoc,
11901 TemplateArgumentListInfo *TemplateArgs) {
11902 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011903
Richard Smithbcc22fc2012-03-09 08:00:36 +000011904 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11905 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11906 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011907
Richard Smithbcc22fc2012-03-09 08:00:36 +000011908 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11909
Richard Smithbcc22fc2012-03-09 08:00:36 +000011910 // Perform overload resolution. This will usually be trivial, but might need
11911 // to perform substitutions for a literal operator template.
11912 OverloadCandidateSet::iterator Best;
11913 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11914 case OR_Success:
11915 case OR_Deleted:
11916 break;
11917
11918 case OR_No_Viable_Function:
11919 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11920 << R.getLookupName();
11921 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11922 return ExprError();
11923
11924 case OR_Ambiguous:
11925 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11926 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11927 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011928 }
11929
Richard Smithbcc22fc2012-03-09 08:00:36 +000011930 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000011931 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11932 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000011933 SuffixInfo.getLoc(),
11934 SuffixInfo.getInfo());
11935 if (Fn.isInvalid())
11936 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011937
11938 // Check the argument types. This should almost always be a no-op, except
11939 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011940 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000011941 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000011942 ExprResult InputInit = PerformCopyInitialization(
11943 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11944 SourceLocation(), Args[ArgIdx]);
11945 if (InputInit.isInvalid())
11946 return true;
11947 ConvArgs[ArgIdx] = InputInit.take();
11948 }
11949
Richard Smithc67fdd42012-03-07 08:35:16 +000011950 QualType ResultTy = FD->getResultType();
11951 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11952 ResultTy = ResultTy.getNonLValueExprType(Context);
11953
Richard Smithc67fdd42012-03-07 08:35:16 +000011954 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011955 new (Context) UserDefinedLiteral(Context, Fn.take(),
11956 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011957 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11958
11959 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11960 return ExprError();
11961
Richard Smith55ce3522012-06-25 20:30:08 +000011962 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011963 return ExprError();
11964
11965 return MaybeBindToTemporary(UDL);
11966}
11967
Sam Panzer0f384432012-08-21 00:52:01 +000011968/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11969/// given LookupResult is non-empty, it is assumed to describe a member which
11970/// will be invoked. Otherwise, the function will be found via argument
11971/// dependent lookup.
11972/// CallExpr is set to a valid expression and FRS_Success returned on success,
11973/// otherwise CallExpr is set to ExprError() and some non-success value
11974/// is returned.
11975Sema::ForRangeStatus
11976Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11977 SourceLocation RangeLoc, VarDecl *Decl,
11978 BeginEndFunction BEF,
11979 const DeclarationNameInfo &NameInfo,
11980 LookupResult &MemberLookup,
11981 OverloadCandidateSet *CandidateSet,
11982 Expr *Range, ExprResult *CallExpr) {
11983 CandidateSet->clear();
11984 if (!MemberLookup.empty()) {
11985 ExprResult MemberRef =
11986 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11987 /*IsPtr=*/false, CXXScopeSpec(),
11988 /*TemplateKWLoc=*/SourceLocation(),
11989 /*FirstQualifierInScope=*/0,
11990 MemberLookup,
11991 /*TemplateArgs=*/0);
11992 if (MemberRef.isInvalid()) {
11993 *CallExpr = ExprError();
11994 Diag(Range->getLocStart(), diag::note_in_for_range)
11995 << RangeLoc << BEF << Range->getType();
11996 return FRS_DiagnosticIssued;
11997 }
Dmitri Gribenko78852e92013-05-05 20:40:26 +000011998 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzer0f384432012-08-21 00:52:01 +000011999 if (CallExpr->isInvalid()) {
12000 *CallExpr = ExprError();
12001 Diag(Range->getLocStart(), diag::note_in_for_range)
12002 << RangeLoc << BEF << Range->getType();
12003 return FRS_DiagnosticIssued;
12004 }
12005 } else {
12006 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012007 UnresolvedLookupExpr *Fn =
12008 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
12009 NestedNameSpecifierLoc(), NameInfo,
12010 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012011 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012012
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012013 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012014 CandidateSet, CallExpr);
12015 if (CandidateSet->empty() || CandidateSetError) {
12016 *CallExpr = ExprError();
12017 return FRS_NoViableFunction;
12018 }
12019 OverloadCandidateSet::iterator Best;
12020 OverloadingResult OverloadResult =
12021 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12022
12023 if (OverloadResult == OR_No_Viable_Function) {
12024 *CallExpr = ExprError();
12025 return FRS_NoViableFunction;
12026 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012027 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzer0f384432012-08-21 00:52:01 +000012028 Loc, 0, CandidateSet, &Best,
12029 OverloadResult,
12030 /*AllowTypoCorrection=*/false);
12031 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12032 *CallExpr = ExprError();
12033 Diag(Range->getLocStart(), diag::note_in_for_range)
12034 << RangeLoc << BEF << Range->getType();
12035 return FRS_DiagnosticIssued;
12036 }
12037 }
12038 return FRS_Success;
12039}
12040
12041
Douglas Gregorcd695e52008-11-10 20:40:00 +000012042/// FixOverloadedFunctionReference - E is an expression that refers to
12043/// a C++ overloaded function (possibly with some parentheses and
12044/// perhaps a '&' around it). We have resolved the overloaded function
12045/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012046/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012047Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012048 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012049 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012050 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12051 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012052 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012053 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012054
Douglas Gregor51c538b2009-11-20 19:42:02 +000012055 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012056 }
12057
Douglas Gregor51c538b2009-11-20 19:42:02 +000012058 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012059 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12060 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012061 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012062 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012063 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012064 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012065 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012066 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012067
12068 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012069 ICE->getCastKind(),
12070 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000012071 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012072 }
12073
Douglas Gregor51c538b2009-11-20 19:42:02 +000012074 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012075 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012076 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012077 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12078 if (Method->isStatic()) {
12079 // Do nothing: static member functions aren't any different
12080 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012081 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012082 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012083 // UnresolvedLookupExpr holding an overloaded member function
12084 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012085 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12086 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012087 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012088 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012089
John McCalld14a8642009-11-21 08:51:07 +000012090 assert(isa<DeclRefExpr>(SubExpr)
12091 && "fixed to something other than a decl ref");
12092 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12093 && "fixed to a member ref with no nested name qualifier");
12094
12095 // We have taken the address of a pointer to member
12096 // function. Perform the computation here so that we get the
12097 // appropriate pointer to member type.
12098 QualType ClassType
12099 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12100 QualType MemPtrType
12101 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12102
John McCall7decc9e2010-11-18 06:31:45 +000012103 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12104 VK_RValue, OK_Ordinary,
12105 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012106 }
12107 }
John McCall16df1e52010-03-30 21:47:33 +000012108 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12109 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012110 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012111 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012112
John McCalle3027922010-08-25 11:45:40 +000012113 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012114 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012115 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012116 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012117 }
John McCalld14a8642009-11-21 08:51:07 +000012118
12119 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012120 // FIXME: avoid copy.
12121 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000012122 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012123 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12124 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012125 }
12126
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012127 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12128 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012129 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012130 Fn,
John McCall113bee02012-03-10 09:33:50 +000012131 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012132 ULE->getNameLoc(),
12133 Fn->getType(),
12134 VK_LValue,
12135 Found.getDecl(),
12136 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012137 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012138 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12139 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012140 }
12141
John McCall10eae182009-11-30 22:42:35 +000012142 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012143 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000012144 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
12145 if (MemExpr->hasExplicitTemplateArgs()) {
12146 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12147 TemplateArgs = &TemplateArgsBuffer;
12148 }
John McCall6b51f282009-11-23 01:53:49 +000012149
John McCall2d74de92009-12-01 22:10:20 +000012150 Expr *Base;
12151
John McCall7decc9e2010-11-18 06:31:45 +000012152 // If we're filling in a static method where we used to have an
12153 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012154 if (MemExpr->isImplicitAccess()) {
12155 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012156 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12157 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012158 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012159 Fn,
John McCall113bee02012-03-10 09:33:50 +000012160 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012161 MemExpr->getMemberLoc(),
12162 Fn->getType(),
12163 VK_LValue,
12164 Found.getDecl(),
12165 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012166 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012167 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12168 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012169 } else {
12170 SourceLocation Loc = MemExpr->getMemberLoc();
12171 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012172 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012173 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012174 Base = new (Context) CXXThisExpr(Loc,
12175 MemExpr->getBaseType(),
12176 /*isImplicit=*/true);
12177 }
John McCall2d74de92009-12-01 22:10:20 +000012178 } else
John McCallc3007a22010-10-26 07:05:15 +000012179 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012180
John McCall4adb38c2011-04-27 00:36:17 +000012181 ExprValueKind valueKind;
12182 QualType type;
12183 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12184 valueKind = VK_LValue;
12185 type = Fn->getType();
12186 } else {
12187 valueKind = VK_RValue;
12188 type = Context.BoundMemberTy;
12189 }
12190
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012191 MemberExpr *ME = MemberExpr::Create(Context, Base,
12192 MemExpr->isArrow(),
12193 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012194 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012195 Fn,
12196 Found,
12197 MemExpr->getMemberNameInfo(),
12198 TemplateArgs,
12199 type, valueKind, OK_Ordinary);
12200 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012201 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012202 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012204
John McCallc3007a22010-10-26 07:05:15 +000012205 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012206}
12207
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012208ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012209 DeclAccessPair Found,
12210 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000012211 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012212}
12213
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012214} // end namespace clang