blob: 366f38e31daf6a2c762836344401221026460957 [file] [log] [blame]
Nick Lewyckye1121512013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Chandler Carruth3a022472012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssond624e162009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
David Majnemerc729b0b2013-09-16 22:44:20 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Lex/Preprocessor.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/SemaInternal.h"
29#include "clang/Sema/Template.h"
30#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000031#include "llvm/ADT/DenseSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000032#include "llvm/ADT/STLExtras.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000033#include "llvm/ADT/SmallPtrSet.h"
Richard Smith9ca64612012-05-07 09:03:25 +000034#include "llvm/ADT/SmallString.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035#include <algorithm>
36
37namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000038using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000039
Nick Lewycky134af912013-02-07 05:08:22 +000040/// A convenience routine for creating a decayed reference to a function.
John Wiegley01296292011-04-08 18:41:53 +000041static ExprResult
Nick Lewycky134af912013-02-07 05:08:22 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
43 bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000044 SourceLocation Loc = SourceLocation(),
45 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith22262ab2013-05-04 06:44:46 +000046 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid6676412013-06-15 11:54:37 +000047 return ExprError();
48 // If FoundDecl is different from Fn (such as if one is a template
49 // and the other a specialization), make sure DiagnoseUseOfDecl is
50 // called on both.
51 // FIXME: This would be more comprehensively addressed by modifying
52 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
53 // being used.
54 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith22262ab2013-05-04 06:44:46 +000055 return ExprError();
John McCall113bee02012-03-10 09:33:50 +000056 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000057 VK_LValue, Loc, LocInfo);
58 if (HadMultipleCandidates)
59 DRE->setHadMultipleCandidates(true);
Nick Lewycky134af912013-02-07 05:08:22 +000060
61 S.MarkDeclRefReferenced(DRE);
Nick Lewycky134af912013-02-07 05:08:22 +000062
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000063 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000064 E = S.DefaultFunctionArrayConversion(E.take());
65 if (E.isInvalid())
66 return ExprError();
Benjamin Kramer62b95d82012-08-23 21:35:17 +000067 return E;
John McCall7decc9e2010-11-18 06:31:45 +000068}
69
John McCall5c32be02010-08-24 20:38:10 +000070static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
71 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000072 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000073 bool CStyle,
74 bool AllowObjCWritebackConversion);
Sam Panzer04390a62012-08-16 02:38:47 +000075
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000076static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
77 QualType &ToType,
78 bool InOverloadResolution,
79 StandardConversionSequence &SCS,
80 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000081static OverloadingResult
82IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
83 UserDefinedConversionSequence& User,
84 OverloadCandidateSet& Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +000085 bool AllowExplicit,
86 bool AllowObjCConversionOnExplicit);
John McCall5c32be02010-08-24 20:38:10 +000087
88
89static ImplicitConversionSequence::CompareKind
90CompareStandardConversionSequences(Sema &S,
91 const StandardConversionSequence& SCS1,
92 const StandardConversionSequence& SCS2);
93
94static ImplicitConversionSequence::CompareKind
95CompareQualificationConversions(Sema &S,
96 const StandardConversionSequence& SCS1,
97 const StandardConversionSequence& SCS2);
98
99static ImplicitConversionSequence::CompareKind
100CompareDerivedToBaseConversions(Sema &S,
101 const StandardConversionSequence& SCS1,
102 const StandardConversionSequence& SCS2);
103
104
105
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106/// GetConversionCategory - Retrieve the implicit conversion
107/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +0000108ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109GetConversionCategory(ImplicitConversionKind Kind) {
110 static const ImplicitConversionCategory
111 Category[(int)ICK_Num_Conversion_Kinds] = {
112 ICC_Identity,
113 ICC_Lvalue_Transformation,
114 ICC_Lvalue_Transformation,
115 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICC_Qualification_Adjustment,
118 ICC_Promotion,
119 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000120 ICC_Promotion,
121 ICC_Conversion,
122 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
126 ICC_Conversion,
127 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000128 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000129 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000130 ICC_Conversion,
131 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000132 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 ICC_Conversion
134 };
135 return Category[(int)Kind];
136}
137
138/// GetConversionRank - Retrieve the implicit conversion rank
139/// corresponding to the given implicit conversion kind.
140ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
141 static const ImplicitConversionRank
142 Rank[(int)ICK_Num_Conversion_Kinds] = {
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
146 ICR_Exact_Match,
147 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000148 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 ICR_Promotion,
150 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000151 ICR_Promotion,
152 ICR_Conversion,
153 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
157 ICR_Conversion,
158 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000159 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000160 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000161 ICR_Conversion,
162 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000163 ICR_Complex_Real_Conversion,
164 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000165 ICR_Conversion,
166 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 };
168 return Rank[(int)Kind];
169}
170
171/// GetImplicitConversionName - Return the name of this kind of
172/// implicit conversion.
173const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000174 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000175 "No conversion",
176 "Lvalue-to-rvalue",
177 "Array-to-pointer",
178 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000179 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000180 "Qualification",
181 "Integral promotion",
182 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000183 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000184 "Integral conversion",
185 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000186 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000187 "Floating-integral conversion",
188 "Pointer conversion",
189 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000190 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000191 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000192 "Derived-to-base conversion",
193 "Vector conversion",
194 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000195 "Complex-real conversion",
196 "Block Pointer conversion",
197 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000198 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000199 };
200 return Name[Kind];
201}
202
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000203/// StandardConversionSequence - Set the standard conversion
204/// sequence to the identity conversion.
205void StandardConversionSequence::setAsIdentityConversion() {
206 First = ICK_Identity;
207 Second = ICK_Identity;
208 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000209 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000210 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000211 ReferenceBinding = false;
212 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000213 IsLvalueReference = true;
214 BindsToFunctionLvalue = false;
215 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000216 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000217 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000218 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000219}
220
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// getRank - Retrieve the rank of this standard conversion sequence
222/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
223/// implicit conversions.
224ImplicitConversionRank StandardConversionSequence::getRank() const {
225 ImplicitConversionRank Rank = ICR_Exact_Match;
226 if (GetConversionRank(First) > Rank)
227 Rank = GetConversionRank(First);
228 if (GetConversionRank(Second) > Rank)
229 Rank = GetConversionRank(Second);
230 if (GetConversionRank(Third) > Rank)
231 Rank = GetConversionRank(Third);
232 return Rank;
233}
234
235/// isPointerConversionToBool - Determines whether this conversion is
236/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000237/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 // Note that FromType has not necessarily been transformed by the
241 // array-to-pointer or function-to-pointer implicit conversions, so
242 // check for their presence as well as checking whether FromType is
243 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000244 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000245 (getFromType()->isPointerType() ||
246 getFromType()->isObjCObjectPointerType() ||
247 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000248 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000249 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
250 return true;
251
252 return false;
253}
254
Douglas Gregor5c407d92008-10-23 00:40:37 +0000255/// isPointerConversionToVoidPointer - Determines whether this
256/// conversion is a conversion of a pointer to a void pointer. This is
257/// used as part of the ranking of standard conversion sequences (C++
258/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000259bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000260StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000261isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000262 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000263 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000264
265 // Note that FromType has not necessarily been transformed by the
266 // array-to-pointer implicit conversion, so check for its presence
267 // and redo the conversion to get a pointer.
268 if (First == ICK_Array_To_Pointer)
269 FromType = Context.getArrayDecayedType(FromType);
270
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000271 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000272 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000273 return ToPtrType->getPointeeType()->isVoidType();
274
275 return false;
276}
277
Richard Smith66e05fe2012-01-18 05:21:49 +0000278/// Skip any implicit casts which could be either part of a narrowing conversion
279/// or after one in an implicit conversion.
280static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
281 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
282 switch (ICE->getCastKind()) {
283 case CK_NoOp:
284 case CK_IntegralCast:
285 case CK_IntegralToBoolean:
286 case CK_IntegralToFloating:
287 case CK_FloatingToIntegral:
288 case CK_FloatingToBoolean:
289 case CK_FloatingCast:
290 Converted = ICE->getSubExpr();
291 continue;
292
293 default:
294 return Converted;
295 }
296 }
297
298 return Converted;
299}
300
301/// Check if this standard conversion sequence represents a narrowing
302/// conversion, according to C++11 [dcl.init.list]p7.
303///
304/// \param Ctx The AST context.
305/// \param Converted The result of applying this standard conversion sequence.
306/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
307/// value of the expression prior to the narrowing conversion.
Richard Smith5614ca72012-03-23 23:55:39 +0000308/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
309/// type of the expression prior to the narrowing conversion.
Richard Smith66e05fe2012-01-18 05:21:49 +0000310NarrowingKind
Richard Smithf8379a02012-01-18 23:55:52 +0000311StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
312 const Expr *Converted,
Richard Smith5614ca72012-03-23 23:55:39 +0000313 APValue &ConstantValue,
314 QualType &ConstantType) const {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000315 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith66e05fe2012-01-18 05:21:49 +0000316
317 // C++11 [dcl.init.list]p7:
318 // A narrowing conversion is an implicit conversion ...
319 QualType FromType = getToType(0);
320 QualType ToType = getToType(1);
321 switch (Second) {
322 // -- from a floating-point type to an integer type, or
323 //
324 // -- from an integer type or unscoped enumeration type to a floating-point
325 // type, except where the source is a constant expression and the actual
326 // value after conversion will fit into the target type and will produce
327 // the original value when converted back to the original type, or
328 case ICK_Floating_Integral:
329 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
330 return NK_Type_Narrowing;
331 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
332 llvm::APSInt IntConstantValue;
333 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
334 if (Initializer &&
335 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
336 // Convert the integer to the floating type.
337 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
338 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
339 llvm::APFloat::rmNearestTiesToEven);
340 // And back.
341 llvm::APSInt ConvertedValue = IntConstantValue;
342 bool ignored;
343 Result.convertToInteger(ConvertedValue,
344 llvm::APFloat::rmTowardZero, &ignored);
345 // If the resulting value is different, this was a narrowing conversion.
346 if (IntConstantValue != ConvertedValue) {
347 ConstantValue = APValue(IntConstantValue);
Richard Smith5614ca72012-03-23 23:55:39 +0000348 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000349 return NK_Constant_Narrowing;
350 }
351 } else {
352 // Variables are always narrowings.
353 return NK_Variable_Narrowing;
354 }
355 }
356 return NK_Not_Narrowing;
357
358 // -- from long double to double or float, or from double to float, except
359 // where the source is a constant expression and the actual value after
360 // conversion is within the range of values that can be represented (even
361 // if it cannot be represented exactly), or
362 case ICK_Floating_Conversion:
363 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
364 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
365 // FromType is larger than ToType.
366 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
367 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
368 // Constant!
369 assert(ConstantValue.isFloat());
370 llvm::APFloat FloatVal = ConstantValue.getFloat();
371 // Convert the source value into the target type.
372 bool ignored;
373 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
374 Ctx.getFloatTypeSemantics(ToType),
375 llvm::APFloat::rmNearestTiesToEven, &ignored);
376 // If there was no overflow, the source value is within the range of
377 // values that can be represented.
Richard Smith5614ca72012-03-23 23:55:39 +0000378 if (ConvertStatus & llvm::APFloat::opOverflow) {
379 ConstantType = Initializer->getType();
Richard Smith66e05fe2012-01-18 05:21:49 +0000380 return NK_Constant_Narrowing;
Richard Smith5614ca72012-03-23 23:55:39 +0000381 }
Richard Smith66e05fe2012-01-18 05:21:49 +0000382 } else {
383 return NK_Variable_Narrowing;
384 }
385 }
386 return NK_Not_Narrowing;
387
388 // -- from an integer type or unscoped enumeration type to an integer type
389 // that cannot represent all the values of the original type, except where
390 // the source is a constant expression and the actual value after
391 // conversion will fit into the target type and will produce the original
392 // value when converted back to the original type.
393 case ICK_Boolean_Conversion: // Bools are integers too.
394 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
395 // Boolean conversions can be from pointers and pointers to members
396 // [conv.bool], and those aren't considered narrowing conversions.
397 return NK_Not_Narrowing;
398 } // Otherwise, fall through to the integral case.
399 case ICK_Integral_Conversion: {
400 assert(FromType->isIntegralOrUnscopedEnumerationType());
401 assert(ToType->isIntegralOrUnscopedEnumerationType());
402 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
403 const unsigned FromWidth = Ctx.getIntWidth(FromType);
404 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
405 const unsigned ToWidth = Ctx.getIntWidth(ToType);
406
407 if (FromWidth > ToWidth ||
Richard Smith25a80d42012-06-13 01:07:41 +0000408 (FromWidth == ToWidth && FromSigned != ToSigned) ||
409 (FromSigned && !ToSigned)) {
Richard Smith66e05fe2012-01-18 05:21:49 +0000410 // Not all values of FromType can be represented in ToType.
411 llvm::APSInt InitializerValue;
412 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smith25a80d42012-06-13 01:07:41 +0000413 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
414 // Such conversions on variables are always narrowing.
415 return NK_Variable_Narrowing;
Richard Smith72cd8ea2012-06-19 21:28:35 +0000416 }
417 bool Narrowing = false;
418 if (FromWidth < ToWidth) {
Richard Smith25a80d42012-06-13 01:07:41 +0000419 // Negative -> unsigned is narrowing. Otherwise, more bits is never
420 // narrowing.
421 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith72cd8ea2012-06-19 21:28:35 +0000422 Narrowing = true;
Richard Smith25a80d42012-06-13 01:07:41 +0000423 } else {
Richard Smith66e05fe2012-01-18 05:21:49 +0000424 // Add a bit to the InitializerValue so we don't have to worry about
425 // signed vs. unsigned comparisons.
426 InitializerValue = InitializerValue.extend(
427 InitializerValue.getBitWidth() + 1);
428 // Convert the initializer to and from the target width and signed-ness.
429 llvm::APSInt ConvertedValue = InitializerValue;
430 ConvertedValue = ConvertedValue.trunc(ToWidth);
431 ConvertedValue.setIsSigned(ToSigned);
432 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
433 ConvertedValue.setIsSigned(InitializerValue.isSigned());
434 // If the result is different, this was a narrowing conversion.
Richard Smith72cd8ea2012-06-19 21:28:35 +0000435 if (ConvertedValue != InitializerValue)
436 Narrowing = true;
437 }
438 if (Narrowing) {
439 ConstantType = Initializer->getType();
440 ConstantValue = APValue(InitializerValue);
441 return NK_Constant_Narrowing;
Richard Smith66e05fe2012-01-18 05:21:49 +0000442 }
443 }
444 return NK_Not_Narrowing;
445 }
446
447 default:
448 // Other kinds of conversions are not narrowings.
449 return NK_Not_Narrowing;
450 }
451}
452
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000453/// dump - Print this standard conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000454/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000455void StandardConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000457 bool PrintedSomething = false;
458 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000459 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460 PrintedSomething = true;
461 }
462
463 if (Second != ICK_Identity) {
464 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000465 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000466 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000467 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000468
469 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000470 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000471 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000472 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000473 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000474 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000475 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000476 PrintedSomething = true;
477 }
478
479 if (Third != ICK_Identity) {
480 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000481 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000483 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000484 PrintedSomething = true;
485 }
486
487 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000488 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000489 }
490}
491
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000492/// dump - Print this user-defined conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000493/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000494void UserDefinedConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496 if (Before.First || Before.Second || Before.Third) {
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000497 Before.dump();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000498 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000500 if (ConversionFunction)
501 OS << '\'' << *ConversionFunction << '\'';
502 else
503 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000505 OS << " -> ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000506 After.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 }
508}
509
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000510/// dump - Print this implicit conversion sequence to standard
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000511/// error. Useful for debugging overloading issues.
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000512void ImplicitConversionSequence::dump() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000513 raw_ostream &OS = llvm::errs();
Richard Smitha93f1022013-09-06 22:30:28 +0000514 if (isStdInitializerListElement())
515 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516 switch (ConversionKind) {
517 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000518 OS << "Standard conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000519 Standard.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520 break;
521 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000522 OS << "User-defined conversion: ";
Douglas Gregor9f2ed472013-11-08 02:16:10 +0000523 UserDefined.dump();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000524 break;
525 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000526 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000527 break;
John McCall0d1da222010-01-12 00:44:57 +0000528 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000529 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000530 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000531 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000532 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533 break;
534 }
535
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000536 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537}
538
John McCall0d1da222010-01-12 00:44:57 +0000539void AmbiguousConversionSequence::construct() {
540 new (&conversions()) ConversionSet();
541}
542
543void AmbiguousConversionSequence::destruct() {
544 conversions().~ConversionSet();
545}
546
547void
548AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
549 FromTypePtr = O.FromTypePtr;
550 ToTypePtr = O.ToTypePtr;
551 new (&conversions()) ConversionSet(O.conversions());
552}
553
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000554namespace {
Larisse Voufo98b20f12013-07-19 23:00:19 +0000555 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000556 // template argument information.
557 struct DFIArguments {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000558 TemplateArgument FirstArg;
559 TemplateArgument SecondArg;
560 };
Larisse Voufo98b20f12013-07-19 23:00:19 +0000561 // Structure used by DeductionFailureInfo to store
Richard Smith44ecdbd2013-01-31 05:19:49 +0000562 // template parameter and template argument information.
563 struct DFIParamWithArguments : DFIArguments {
564 TemplateParameter Param;
565 };
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000566}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000567
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000568/// \brief Convert from Sema's representation of template deduction information
569/// to the form used in overload-candidate information.
Larisse Voufo98b20f12013-07-19 23:00:19 +0000570DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
571 Sema::TemplateDeductionResult TDK,
572 TemplateDeductionInfo &Info) {
573 DeductionFailureInfo Result;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000574 Result.Result = static_cast<unsigned>(TDK);
Richard Smith9ca64612012-05-07 09:03:25 +0000575 Result.HasDiagnostic = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000576 Result.Data = 0;
577 switch (TDK) {
578 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000579 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000580 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000581 case Sema::TDK_TooManyArguments:
582 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000583 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000584
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000585 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000586 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000587 Result.Data = Info.Param.getOpaqueValue();
588 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000589
Richard Smith44ecdbd2013-01-31 05:19:49 +0000590 case Sema::TDK_NonDeducedMismatch: {
591 // FIXME: Should allocate from normal heap so that we can free this later.
592 DFIArguments *Saved = new (Context) DFIArguments;
593 Saved->FirstArg = Info.FirstArg;
594 Saved->SecondArg = Info.SecondArg;
595 Result.Data = Saved;
596 break;
597 }
598
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000599 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000600 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000601 // FIXME: Should allocate from normal heap so that we can free this later.
602 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000603 Saved->Param = Info.Param;
604 Saved->FirstArg = Info.FirstArg;
605 Saved->SecondArg = Info.SecondArg;
606 Result.Data = Saved;
607 break;
608 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000609
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000610 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000611 Result.Data = Info.take();
Richard Smith9ca64612012-05-07 09:03:25 +0000612 if (Info.hasSFINAEDiagnostic()) {
613 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
614 SourceLocation(), PartialDiagnostic::NullDiagnostic());
615 Info.takeSFINAEDiagnostic(*Diag);
616 Result.HasDiagnostic = true;
617 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000618 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000619
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000620 case Sema::TDK_FailedOverloadResolution:
Richard Smith8c6eeb92013-01-31 04:03:12 +0000621 Result.Data = Info.Expression;
622 break;
623
Richard Smith44ecdbd2013-01-31 05:19:49 +0000624 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000625 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000626 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000627
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000628 return Result;
629}
John McCall0d1da222010-01-12 00:44:57 +0000630
Larisse Voufo98b20f12013-07-19 23:00:19 +0000631void DeductionFailureInfo::Destroy() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000632 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
633 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000634 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000635 case Sema::TDK_InstantiationDepth:
636 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000637 case Sema::TDK_TooManyArguments:
638 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000639 case Sema::TDK_InvalidExplicitArguments:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000640 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000641 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000642
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000643 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000644 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000645 case Sema::TDK_NonDeducedMismatch:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000646 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000647 Data = 0;
648 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000649
650 case Sema::TDK_SubstitutionFailure:
Richard Smith9ca64612012-05-07 09:03:25 +0000651 // FIXME: Destroy the template argument list?
Douglas Gregord09efd42010-05-08 20:07:26 +0000652 Data = 0;
Richard Smith9ca64612012-05-07 09:03:25 +0000653 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
654 Diag->~PartialDiagnosticAt();
655 HasDiagnostic = false;
656 }
Douglas Gregord09efd42010-05-08 20:07:26 +0000657 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000658
Douglas Gregor461761d2010-05-08 18:20:53 +0000659 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000660 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000661 break;
662 }
663}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000664
Larisse Voufo98b20f12013-07-19 23:00:19 +0000665PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smith9ca64612012-05-07 09:03:25 +0000666 if (HasDiagnostic)
667 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
668 return 0;
669}
670
Larisse Voufo98b20f12013-07-19 23:00:19 +0000671TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000672 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
673 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000674 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000675 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000676 case Sema::TDK_TooManyArguments:
677 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000678 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000679 case Sema::TDK_NonDeducedMismatch:
680 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000681 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000682
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000683 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000684 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000685 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000686
687 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000688 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000689 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000690
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000691 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000692 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000693 break;
694 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000695
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000696 return TemplateParameter();
697}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000698
Larisse Voufo98b20f12013-07-19 23:00:19 +0000699TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregord09efd42010-05-08 20:07:26 +0000700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith44ecdbd2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregord09efd42010-05-08 20:07:26 +0000713
Richard Smith44ecdbd2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
Richard Smith44ecdbd2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Larisse Voufo98b20f12013-07-19 23:00:19 +0000725const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000742
Douglas Gregor461761d2010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000749}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000750
Larisse Voufo98b20f12013-07-19 23:00:19 +0000751const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000752 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
753 case Sema::TDK_Success:
Douglas Gregorc5c01a62012-09-13 21:01:57 +0000754 case Sema::TDK_Invalid:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000755 case Sema::TDK_InstantiationDepth:
756 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000757 case Sema::TDK_TooManyArguments:
758 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000759 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000760 case Sema::TDK_SubstitutionFailure:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000761 case Sema::TDK_FailedOverloadResolution:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000762 return 0;
763
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000764 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000765 case Sema::TDK_Underqualified:
Richard Smith44ecdbd2013-01-31 05:19:49 +0000766 case Sema::TDK_NonDeducedMismatch:
767 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000768
Douglas Gregor461761d2010-05-08 18:20:53 +0000769 // Unhandled
Richard Smith44ecdbd2013-01-31 05:19:49 +0000770 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000771 break;
772 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000773
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000774 return 0;
775}
776
Larisse Voufo98b20f12013-07-19 23:00:19 +0000777Expr *DeductionFailureInfo::getExpr() {
Richard Smith8c6eeb92013-01-31 04:03:12 +0000778 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
779 Sema::TDK_FailedOverloadResolution)
780 return static_cast<Expr*>(Data);
781
782 return 0;
783}
784
Benjamin Kramer97e59492012-10-09 15:52:25 +0000785void OverloadCandidateSet::destroyCandidates() {
Richard Smith0bf93aa2012-07-18 23:52:59 +0000786 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer02b08432012-01-14 20:16:52 +0000787 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
788 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smith0bf93aa2012-07-18 23:52:59 +0000789 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
790 i->DeductionFailure.Destroy();
791 }
Benjamin Kramer97e59492012-10-09 15:52:25 +0000792}
793
794void OverloadCandidateSet::clear() {
795 destroyCandidates();
Benjamin Kramer0b9c5092012-01-14 19:31:39 +0000796 NumInlineSequences = 0;
Benjamin Kramerfb761ff2012-01-14 16:31:55 +0000797 Candidates.clear();
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000798 Functions.clear();
799}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000800
John McCall4124c492011-10-17 18:40:02 +0000801namespace {
802 class UnbridgedCastsSet {
803 struct Entry {
804 Expr **Addr;
805 Expr *Saved;
806 };
807 SmallVector<Entry, 2> Entries;
808
809 public:
810 void save(Sema &S, Expr *&E) {
811 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
812 Entry entry = { &E, E };
813 Entries.push_back(entry);
814 E = S.stripARCUnbridgedCast(E);
815 }
816
817 void restore() {
818 for (SmallVectorImpl<Entry>::iterator
819 i = Entries.begin(), e = Entries.end(); i != e; ++i)
820 *i->Addr = i->Saved;
821 }
822 };
823}
824
825/// checkPlaceholderForOverload - Do any interesting placeholder-like
826/// preprocessing on the given expression.
827///
828/// \param unbridgedCasts a collection to which to add unbridged casts;
829/// without this, they will be immediately diagnosed as errors
830///
831/// Return true on unrecoverable error.
832static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
833 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000834 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
835 // We can't handle overloaded expressions here because overload
836 // resolution might reasonably tweak them.
837 if (placeholder->getKind() == BuiltinType::Overload) return false;
838
839 // If the context potentially accepts unbridged ARC casts, strip
840 // the unbridged cast and add it to the collection for later restoration.
841 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
842 unbridgedCasts) {
843 unbridgedCasts->save(S, E);
844 return false;
845 }
846
847 // Go ahead and check everything else.
848 ExprResult result = S.CheckPlaceholderExpr(E);
849 if (result.isInvalid())
850 return true;
851
852 E = result.take();
853 return false;
854 }
855
856 // Nothing to do.
857 return false;
858}
859
860/// checkArgPlaceholdersForOverload - Check a set of call operands for
861/// placeholders.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000862static bool checkArgPlaceholdersForOverload(Sema &S,
863 MultiExprArg Args,
John McCall4124c492011-10-17 18:40:02 +0000864 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +0000865 for (unsigned i = 0, e = Args.size(); i != e; ++i)
866 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall4124c492011-10-17 18:40:02 +0000867 return true;
868
869 return false;
870}
871
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000872// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000873// overload of the declarations in Old. This routine returns false if
874// New and Old cannot be overloaded, e.g., if New has the same
875// signature as some function in Old (C++ 1.3.10) or if the Old
876// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000877// it does return false, MatchedDecl will point to the decl that New
878// cannot be overloaded with. This decl may be a UsingShadowDecl on
879// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000880//
881// Example: Given the following input:
882//
883// void f(int, float); // #1
884// void f(int, int); // #2
885// int f(int, int); // #3
886//
887// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000888// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000889//
John McCall3d988d92009-12-02 08:47:38 +0000890// When we process #2, Old contains only the FunctionDecl for #1. By
891// comparing the parameter types, we see that #1 and #2 are overloaded
892// (since they have different signatures), so this routine returns
893// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000894//
John McCall3d988d92009-12-02 08:47:38 +0000895// When we process #3, Old is an overload set containing #1 and #2. We
896// compare the signatures of #3 to #1 (they're overloaded, so we do
897// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
898// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000899// signature), IsOverload returns false and MatchedDecl will be set to
900// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000901//
902// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
903// into a class by a using declaration. The rules for whether to hide
904// shadow declarations ignore some properties which otherwise figure
905// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000906Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000907Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
908 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000909 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000910 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000911 NamedDecl *OldD = *I;
912
913 bool OldIsUsingDecl = false;
914 if (isa<UsingShadowDecl>(OldD)) {
915 OldIsUsingDecl = true;
916
917 // We can always introduce two using declarations into the same
918 // context, even if they have identical signatures.
919 if (NewIsUsingDecl) continue;
920
921 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
922 }
923
924 // If either declaration was introduced by a using declaration,
925 // we'll need to use slightly different rules for matching.
926 // Essentially, these rules are the normal rules, except that
927 // function templates hide function templates with different
928 // return types or template parameter lists.
929 bool UseMemberUsingDeclRules =
John McCallc70fca62013-04-03 21:19:47 +0000930 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
931 !New->getFriendObjectKind();
John McCalle9cccd82010-06-16 08:42:20 +0000932
John McCall3d988d92009-12-02 08:47:38 +0000933 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000934 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
935 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
936 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
937 continue;
938 }
939
John McCalldaa3d6b2009-12-09 03:35:25 +0000940 Match = *I;
941 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942 }
John McCall3d988d92009-12-02 08:47:38 +0000943 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000944 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
945 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
946 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
947 continue;
948 }
949
Rafael Espindola5bddd6a2013-04-15 12:49:13 +0000950 if (!shouldLinkPossiblyHiddenDecl(*I, New))
951 continue;
952
John McCalldaa3d6b2009-12-09 03:35:25 +0000953 Match = *I;
954 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000955 }
John McCalla8987a2942010-11-10 03:01:53 +0000956 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000957 // We can overload with these, which can show up when doing
958 // redeclaration checks for UsingDecls.
959 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000960 } else if (isa<TagDecl>(OldD)) {
961 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000962 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
963 // Optimistically assume that an unresolved using decl will
964 // overload; if it doesn't, we'll have to diagnose during
965 // template instantiation.
966 } else {
John McCall1f82f242009-11-18 22:49:29 +0000967 // (C++ 13p1):
968 // Only function declarations can be overloaded; object and type
969 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000970 Match = *I;
971 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000972 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000973 }
John McCall1f82f242009-11-18 22:49:29 +0000974
John McCalldaa3d6b2009-12-09 03:35:25 +0000975 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000976}
977
Richard Smithac974a32013-06-30 09:48:50 +0000978bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
979 bool UseUsingDeclRules) {
980 // C++ [basic.start.main]p2: This function shall not be overloaded.
981 if (New->isMain())
Rafael Espindola576127d2012-12-28 14:21:58 +0000982 return false;
Rafael Espindola7cf35ef2013-01-12 01:47:40 +0000983
David Majnemerc729b0b2013-09-16 22:44:20 +0000984 // MSVCRT user defined entry points cannot be overloaded.
985 if (New->isMSVCRTEntryPoint())
986 return false;
987
John McCall1f82f242009-11-18 22:49:29 +0000988 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
989 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
990
991 // C++ [temp.fct]p2:
992 // A function template can be overloaded with other function templates
993 // and with normal (non-template) functions.
994 if ((OldTemplate == 0) != (NewTemplate == 0))
995 return true;
996
997 // Is the function New an overload of the function Old?
Richard Smithac974a32013-06-30 09:48:50 +0000998 QualType OldQType = Context.getCanonicalType(Old->getType());
999 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall1f82f242009-11-18 22:49:29 +00001000
1001 // Compare the signatures (C++ 1.3.10) of the two functions to
1002 // determine whether they are overloads. If we find any mismatch
1003 // in the signature, they are overloads.
1004
1005 // If either of these functions is a K&R-style function (no
1006 // prototype), then we consider them to have matching signatures.
1007 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1008 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1009 return false;
1010
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001011 const FunctionProtoType *OldType = cast<FunctionProtoType>(OldQType);
1012 const FunctionProtoType *NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +00001013
1014 // The signature of a function includes the types of its
1015 // parameters (C++ 1.3.10), which includes the presence or absence
1016 // of the ellipsis; see C++ DR 357).
1017 if (OldQType != NewQType &&
1018 (OldType->getNumArgs() != NewType->getNumArgs() ||
1019 OldType->isVariadic() != NewType->isVariadic() ||
Richard Smithac974a32013-06-30 09:48:50 +00001020 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +00001021 return true;
1022
1023 // C++ [temp.over.link]p4:
1024 // The signature of a function template consists of its function
1025 // signature, its return type and its template parameter list. The names
1026 // of the template parameters are significant only for establishing the
1027 // relationship between the template parameters and the rest of the
1028 // signature.
1029 //
1030 // We check the return type and template parameter lists for function
1031 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +00001032 //
1033 // However, we don't consider either of these when deciding whether
1034 // a member introduced by a shadow declaration is hidden.
1035 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithac974a32013-06-30 09:48:50 +00001036 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1037 OldTemplate->getTemplateParameters(),
1038 false, TPL_TemplateMatch) ||
John McCall1f82f242009-11-18 22:49:29 +00001039 OldType->getResultType() != NewType->getResultType()))
1040 return true;
1041
1042 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +00001043 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +00001044 //
1045 // As part of this, also check whether one of the member functions
1046 // is static, in which case they are not overloads (C++
1047 // 13.1p2). While not part of the definition of the signature,
1048 // this check is important to determine whether these functions
1049 // can be overloaded.
Richard Smith574f4f62013-01-14 05:37:29 +00001050 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1051 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall1f82f242009-11-18 22:49:29 +00001052 if (OldMethod && NewMethod &&
Richard Smith574f4f62013-01-14 05:37:29 +00001053 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1054 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1055 if (!UseUsingDeclRules &&
1056 (OldMethod->getRefQualifier() == RQ_None ||
1057 NewMethod->getRefQualifier() == RQ_None)) {
1058 // C++0x [over.load]p2:
1059 // - Member function declarations with the same name and the same
1060 // parameter-type-list as well as member function template
1061 // declarations with the same name, the same parameter-type-list, and
1062 // the same template parameter lists cannot be overloaded if any of
1063 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithac974a32013-06-30 09:48:50 +00001064 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith574f4f62013-01-14 05:37:29 +00001065 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithac974a32013-06-30 09:48:50 +00001066 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith574f4f62013-01-14 05:37:29 +00001067 }
1068 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001069 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070
Richard Smith574f4f62013-01-14 05:37:29 +00001071 // We may not have applied the implicit const for a constexpr member
1072 // function yet (because we haven't yet resolved whether this is a static
1073 // or non-static member function). Add it now, on the assumption that this
1074 // is a redeclaration of OldMethod.
David Majnemer42350df2013-11-03 23:51:28 +00001075 unsigned OldQuals = OldMethod->getTypeQualifiers();
Richard Smith574f4f62013-01-14 05:37:29 +00001076 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithac974a32013-06-30 09:48:50 +00001077 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithe83b1d32013-06-25 18:46:26 +00001078 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith574f4f62013-01-14 05:37:29 +00001079 NewQuals |= Qualifiers::Const;
David Majnemer42350df2013-11-03 23:51:28 +00001080
1081 // We do not allow overloading based off of '__restrict'.
1082 OldQuals &= ~Qualifiers::Restrict;
1083 NewQuals &= ~Qualifiers::Restrict;
1084 if (OldQuals != NewQuals)
Richard Smith574f4f62013-01-14 05:37:29 +00001085 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +00001086 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001087
Nick Lewycky35a6ef42014-01-11 02:50:57 +00001088 // enable_if attributes are an order-sensitive part of the signature.
1089 for (specific_attr_iterator<EnableIfAttr>
1090 NewI = New->specific_attr_begin<EnableIfAttr>(),
1091 NewE = New->specific_attr_end<EnableIfAttr>(),
1092 OldI = Old->specific_attr_begin<EnableIfAttr>(),
1093 OldE = Old->specific_attr_end<EnableIfAttr>();
1094 NewI != NewE || OldI != OldE; ++NewI, ++OldI) {
1095 if (NewI == NewE || OldI == OldE)
1096 return true;
1097 llvm::FoldingSetNodeID NewID, OldID;
1098 NewI->getCond()->Profile(NewID, Context, true);
1099 OldI->getCond()->Profile(OldID, Context, true);
1100 if (!(NewID == OldID))
1101 return true;
1102 }
1103
John McCall1f82f242009-11-18 22:49:29 +00001104 // The signatures match; this is not an overload.
1105 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001106}
1107
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00001108/// \brief Checks availability of the function depending on the current
1109/// function context. Inside an unavailable function, unavailability is ignored.
1110///
1111/// \returns true if \arg FD is unavailable and current context is inside
1112/// an available function, false otherwise.
1113bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1114 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1115}
1116
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001117/// \brief Tries a user-defined conversion from From to ToType.
1118///
1119/// Produces an implicit conversion sequence for when a standard conversion
1120/// is not an option. See TryImplicitConversion for more information.
1121static ImplicitConversionSequence
1122TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1123 bool SuppressUserConversions,
1124 bool AllowExplicit,
1125 bool InOverloadResolution,
1126 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001127 bool AllowObjCWritebackConversion,
1128 bool AllowObjCConversionOnExplicit) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001129 ImplicitConversionSequence ICS;
1130
1131 if (SuppressUserConversions) {
1132 // We're not in the case above, so there is no conversion that
1133 // we can perform.
1134 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1135 return ICS;
1136 }
1137
1138 // Attempt user-defined conversion.
1139 OverloadCandidateSet Conversions(From->getExprLoc());
1140 OverloadingResult UserDefResult
1141 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001142 AllowExplicit, AllowObjCConversionOnExplicit);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001143
1144 if (UserDefResult == OR_Success) {
1145 ICS.setUserDefined();
1146 // C++ [over.ics.user]p4:
1147 // A conversion of an expression of class type to the same class
1148 // type is given Exact Match rank, and a conversion of an
1149 // expression of class type to a base class of that type is
1150 // given Conversion rank, in spite of the fact that a copy
1151 // constructor (i.e., a user-defined conversion function) is
1152 // called for those cases.
1153 if (CXXConstructorDecl *Constructor
1154 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1155 QualType FromCanon
1156 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1157 QualType ToCanon
1158 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1159 if (Constructor->isCopyConstructor() &&
1160 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1161 // Turn this into a "standard" conversion sequence, so that it
1162 // gets ranked with standard conversion sequences.
1163 ICS.setStandard();
1164 ICS.Standard.setAsIdentityConversion();
1165 ICS.Standard.setFromType(From->getType());
1166 ICS.Standard.setAllToTypes(ToType);
1167 ICS.Standard.CopyConstructor = Constructor;
1168 if (ToCanon != FromCanon)
1169 ICS.Standard.Second = ICK_Derived_To_Base;
1170 }
1171 }
1172
1173 // C++ [over.best.ics]p4:
1174 // However, when considering the argument of a user-defined
1175 // conversion function that is a candidate by 13.3.1.3 when
1176 // invoked for the copying of the temporary in the second step
1177 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1178 // 13.3.1.6 in all cases, only standard conversion sequences and
1179 // ellipsis conversion sequences are allowed.
1180 if (SuppressUserConversions && ICS.isUserDefined()) {
1181 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1182 }
1183 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1184 ICS.setAmbiguous();
1185 ICS.Ambiguous.setFromType(From->getType());
1186 ICS.Ambiguous.setToType(ToType);
1187 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1188 Cand != Conversions.end(); ++Cand)
1189 if (Cand->Viable)
1190 ICS.Ambiguous.addConversion(Cand->Function);
1191 } else {
1192 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1193 }
1194
1195 return ICS;
1196}
1197
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001198/// TryImplicitConversion - Attempt to perform an implicit conversion
1199/// from the given expression (Expr) to the given type (ToType). This
1200/// function returns an implicit conversion sequence that can be used
1201/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001202///
1203/// void f(float f);
1204/// void g(int i) { f(i); }
1205///
1206/// this routine would produce an implicit conversion sequence to
1207/// describe the initialization of f from i, which will be a standard
1208/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1209/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1210//
1211/// Note that this routine only determines how the conversion can be
1212/// performed; it does not actually perform the conversion. As such,
1213/// it will not produce any diagnostics if no conversion is available,
1214/// but will instead return an implicit conversion sequence of kind
1215/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +00001216///
1217/// If @p SuppressUserConversions, then user-defined conversions are
1218/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +00001219/// If @p AllowExplicit, then explicit user-defined conversions are
1220/// permitted.
John McCall31168b02011-06-15 23:02:42 +00001221///
1222/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1223/// writeback conversion, which allows __autoreleasing id* parameters to
1224/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +00001225static ImplicitConversionSequence
1226TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1227 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001228 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001229 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001230 bool CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001231 bool AllowObjCWritebackConversion,
1232 bool AllowObjCConversionOnExplicit) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001233 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +00001234 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00001235 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +00001236 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +00001237 return ICS;
1238 }
1239
David Blaikiebbafb8a2012-03-11 07:00:24 +00001240 if (!S.getLangOpts().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +00001241 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +00001242 return ICS;
1243 }
1244
Douglas Gregor836a7e82010-08-11 02:15:33 +00001245 // C++ [over.ics.user]p4:
1246 // A conversion of an expression of class type to the same class
1247 // type is given Exact Match rank, and a conversion of an
1248 // expression of class type to a base class of that type is
1249 // given Conversion rank, in spite of the fact that a copy/move
1250 // constructor (i.e., a user-defined conversion function) is
1251 // called for those cases.
1252 QualType FromType = From->getType();
1253 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001254 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1255 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001256 ICS.setStandard();
1257 ICS.Standard.setAsIdentityConversion();
1258 ICS.Standard.setFromType(FromType);
1259 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001260
Douglas Gregor5ab11652010-04-17 22:01:05 +00001261 // We don't actually check at this point whether there is a valid
1262 // copy/move constructor, since overloading just assumes that it
1263 // exists. When we actually perform initialization, we'll find the
1264 // appropriate constructor to copy the returned object, if needed.
1265 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001266
Douglas Gregor5ab11652010-04-17 22:01:05 +00001267 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +00001268 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001269 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270
Douglas Gregor836a7e82010-08-11 02:15:33 +00001271 return ICS;
1272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001273
Sebastian Redl6901c0d2011-12-22 18:58:38 +00001274 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1275 AllowExplicit, InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001276 AllowObjCWritebackConversion,
1277 AllowObjCConversionOnExplicit);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001278}
1279
John McCall31168b02011-06-15 23:02:42 +00001280ImplicitConversionSequence
1281Sema::TryImplicitConversion(Expr *From, QualType ToType,
1282 bool SuppressUserConversions,
1283 bool AllowExplicit,
1284 bool InOverloadResolution,
1285 bool CStyle,
1286 bool AllowObjCWritebackConversion) {
1287 return clang::TryImplicitConversion(*this, From, ToType,
1288 SuppressUserConversions, AllowExplicit,
1289 InOverloadResolution, CStyle,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001290 AllowObjCWritebackConversion,
1291 /*AllowObjCConversionOnExplicit=*/false);
John McCall5c32be02010-08-24 20:38:10 +00001292}
1293
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001294/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +00001295/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001296/// converted expression. Flavor is the kind of conversion we're
1297/// performing, used in the error message. If @p AllowExplicit,
1298/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +00001299ExprResult
1300Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +00001301 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001302 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +00001303 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001304}
1305
John Wiegley01296292011-04-08 18:41:53 +00001306ExprResult
1307Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001308 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001309 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +00001310 if (checkPlaceholderForOverload(*this, From))
1311 return ExprError();
1312
John McCall31168b02011-06-15 23:02:42 +00001313 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1314 bool AllowObjCWritebackConversion
David Blaikiebbafb8a2012-03-11 07:00:24 +00001315 = getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001316 (Action == AA_Passing || Action == AA_Sending);
Fariborz Jahanian381edf52013-12-16 22:54:37 +00001317 if (getLangOpts().ObjC1)
1318 CheckObjCBridgeRelatedConversions(From->getLocStart(),
1319 ToType, From->getType(), From);
John McCall5c32be02010-08-24 20:38:10 +00001320 ICS = clang::TryImplicitConversion(*this, From, ToType,
1321 /*SuppressUserConversions=*/false,
1322 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001323 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001324 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00001325 AllowObjCWritebackConversion,
1326 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001327 return PerformImplicitConversion(From, ToType, ICS, Action);
1328}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001329
1330/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001331/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001332bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1333 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001334 if (Context.hasSameUnqualifiedType(FromType, ToType))
1335 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001336
John McCall991eb4b2010-12-21 00:44:39 +00001337 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1338 // where F adds one of the following at most once:
1339 // - a pointer
1340 // - a member pointer
1341 // - a block pointer
1342 CanQualType CanTo = Context.getCanonicalType(ToType);
1343 CanQualType CanFrom = Context.getCanonicalType(FromType);
1344 Type::TypeClass TyClass = CanTo->getTypeClass();
1345 if (TyClass != CanFrom->getTypeClass()) return false;
1346 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1347 if (TyClass == Type::Pointer) {
1348 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1349 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1350 } else if (TyClass == Type::BlockPointer) {
1351 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1352 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1353 } else if (TyClass == Type::MemberPointer) {
1354 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1355 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1356 } else {
1357 return false;
1358 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001359
John McCall991eb4b2010-12-21 00:44:39 +00001360 TyClass = CanTo->getTypeClass();
1361 if (TyClass != CanFrom->getTypeClass()) return false;
1362 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1363 return false;
1364 }
1365
1366 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1367 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1368 if (!EInfo.getNoReturn()) return false;
1369
1370 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1371 assert(QualType(FromFn, 0).isCanonical());
1372 if (QualType(FromFn, 0) != CanTo) return false;
1373
1374 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001375 return true;
1376}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001377
Douglas Gregor46188682010-05-18 22:42:18 +00001378/// \brief Determine whether the conversion from FromType to ToType is a valid
1379/// vector conversion.
1380///
1381/// \param ICK Will be set to the vector conversion kind, if this is a vector
1382/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1384 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001385 // We need at least one of these types to be a vector type to have a vector
1386 // conversion.
1387 if (!ToType->isVectorType() && !FromType->isVectorType())
1388 return false;
1389
1390 // Identical types require no conversions.
1391 if (Context.hasSameUnqualifiedType(FromType, ToType))
1392 return false;
1393
1394 // There are no conversions between extended vector types, only identity.
1395 if (ToType->isExtVectorType()) {
1396 // There are no conversions between extended vector types other than the
1397 // identity conversion.
1398 if (FromType->isExtVectorType())
1399 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001400
Douglas Gregor46188682010-05-18 22:42:18 +00001401 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001402 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001403 ICK = ICK_Vector_Splat;
1404 return true;
1405 }
1406 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001407
1408 // We can perform the conversion between vector types in the following cases:
1409 // 1)vector types are equivalent AltiVec and GCC vector types
1410 // 2)lax vector conversions are permitted and the vector types are of the
1411 // same size
1412 if (ToType->isVectorType() && FromType->isVectorType()) {
1413 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikiebbafb8a2012-03-11 07:00:24 +00001414 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruth9c524c12010-08-08 05:02:51 +00001415 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001416 ICK = ICK_Vector_Conversion;
1417 return true;
1418 }
Douglas Gregor46188682010-05-18 22:42:18 +00001419 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001420
Douglas Gregor46188682010-05-18 22:42:18 +00001421 return false;
1422}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001423
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001424static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1425 bool InOverloadResolution,
1426 StandardConversionSequence &SCS,
1427 bool CStyle);
Douglas Gregorc79862f2012-04-12 17:51:55 +00001428
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001429/// IsStandardConversion - Determines whether there is a standard
1430/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1431/// expression From to the type ToType. Standard conversion sequences
1432/// only consider non-class types; for conversions that involve class
1433/// types, use TryImplicitConversion. If a conversion exists, SCS will
1434/// contain the standard conversion sequence required to perform this
1435/// conversion and this routine will return true. Otherwise, this
1436/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001437static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1438 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001439 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001440 bool CStyle,
1441 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001443
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001444 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001445 SCS.setAsIdentityConversion();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001446 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001447 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001448 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001449
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001450 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001451 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001452 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001453 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001454 return false;
1455
Mike Stump11289f42009-09-09 15:08:12 +00001456 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001457 }
1458
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459 // The first conversion can be an lvalue-to-rvalue conversion,
1460 // array-to-pointer conversion, or function-to-pointer conversion
1461 // (C++ 4p1).
1462
John McCall5c32be02010-08-24 20:38:10 +00001463 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001464 DeclAccessPair AccessPair;
1465 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001467 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001468 // We were able to resolve the address of the overloaded function,
1469 // so we can convert to the type of that function.
1470 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001471
1472 // we can sometimes resolve &foo<int> regardless of ToType, so check
1473 // if the type matches (identity) or we are converting to bool
1474 if (!S.Context.hasSameUnqualifiedType(
1475 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1476 QualType resultTy;
1477 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001478 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001479 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1480 // otherwise, only a boolean conversion is standard
1481 if (!ToType->isBooleanType())
1482 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001484
Chandler Carruthffce2452011-03-29 08:08:18 +00001485 // Check if the "from" expression is taking the address of an overloaded
1486 // function and recompute the FromType accordingly. Take advantage of the
1487 // fact that non-static member functions *must* have such an address-of
1488 // expression.
1489 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1490 if (Method && !Method->isStatic()) {
1491 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1492 "Non-unary operator on non-static member address");
1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1494 == UO_AddrOf &&
1495 "Non-address-of operator on non-static member address");
1496 const Type *ClassType
1497 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1498 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001499 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1500 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1501 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001502 "Non-address-of operator for overloaded function expression");
1503 FromType = S.Context.getPointerType(FromType);
1504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001505
Douglas Gregor980fb162010-04-29 18:24:40 +00001506 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001507 assert(S.Context.hasSameType(
1508 FromType,
1509 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001510 } else {
1511 return false;
1512 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001513 }
John McCall154a2fd2011-08-30 00:57:29 +00001514 // Lvalue-to-rvalue conversion (C++11 4.1):
1515 // A glvalue (3.10) of a non-function, non-array type T can
1516 // be converted to a prvalue.
1517 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001518 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001519 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001520 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001522
Douglas Gregorc79862f2012-04-12 17:51:55 +00001523 // C11 6.3.2.1p2:
1524 // ... if the lvalue has atomic type, the value has the non-atomic version
1525 // of the type of the lvalue ...
1526 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1527 FromType = Atomic->getValueType();
1528
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529 // If T is a non-class type, the type of the rvalue is the
1530 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001531 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1532 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001533 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001534 } else if (FromType->isArrayType()) {
1535 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001536 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001537
1538 // An lvalue or rvalue of type "array of N T" or "array of unknown
1539 // bound of T" can be converted to an rvalue of type "pointer to
1540 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001541 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001542
John McCall5c32be02010-08-24 20:38:10 +00001543 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00001544 // This conversion is deprecated in C++03 (D.4)
Douglas Gregore489a7d2010-02-28 18:30:25 +00001545 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001546
1547 // For the purpose of ranking in overload resolution
1548 // (13.3.3.1.1), this conversion is considered an
1549 // array-to-pointer conversion followed by a qualification
1550 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001551 SCS.Second = ICK_Identity;
1552 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001553 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001554 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001555 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 }
John McCall086a4642010-11-24 05:12:34 +00001557 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001558 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001559 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001560
1561 // An lvalue of function type T can be converted to an rvalue of
1562 // type "pointer to T." The result is a pointer to the
1563 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001564 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001565 } else {
1566 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001567 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001568 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001569 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001570
1571 // The second conversion can be an integral promotion, floating
1572 // point promotion, integral conversion, floating point conversion,
1573 // floating-integral conversion, pointer conversion,
1574 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001575 // For overloading in C, this can also be a "compatible-type"
1576 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001577 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001578 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001579 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580 // The unqualified versions of the types are the same: there's no
1581 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001582 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001583 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001584 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001585 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001586 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001587 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001588 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001589 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001590 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001591 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001592 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001593 SCS.Second = ICK_Complex_Promotion;
1594 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001595 } else if (ToType->isBooleanType() &&
1596 (FromType->isArithmeticType() ||
1597 FromType->isAnyPointerType() ||
1598 FromType->isBlockPointerType() ||
1599 FromType->isMemberPointerType() ||
1600 FromType->isNullPtrType())) {
1601 // Boolean conversions (C++ 4.12).
1602 SCS.Second = ICK_Boolean_Conversion;
1603 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001604 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001605 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001606 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001607 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001608 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001609 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001610 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001611 SCS.Second = ICK_Complex_Conversion;
1612 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001613 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1614 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001615 // Complex-real conversions (C99 6.3.1.7)
1616 SCS.Second = ICK_Complex_Real;
1617 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001618 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001619 // Floating point conversions (C++ 4.8).
1620 SCS.Second = ICK_Floating_Conversion;
1621 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001622 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001623 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001624 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001625 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001626 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001627 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001629 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001630 SCS.Second = ICK_Block_Pointer_Conversion;
1631 } else if (AllowObjCWritebackConversion &&
1632 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1633 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001634 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1635 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001636 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001637 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001638 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001639 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001641 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001642 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001643 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001644 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001645 SCS.Second = SecondICK;
1646 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001647 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001648 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001649 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001650 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001651 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001652 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001653 // Treat a conversion that strips "noreturn" as an identity conversion.
1654 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001655 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1656 InOverloadResolution,
1657 SCS, CStyle)) {
1658 SCS.Second = ICK_TransparentUnionConversion;
1659 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001660 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1661 CStyle)) {
1662 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001663 // appropriately.
1664 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001665 } else if (ToType->isEventT() &&
1666 From->isIntegerConstantExpr(S.getASTContext()) &&
1667 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1668 SCS.Second = ICK_Zero_Event_Conversion;
1669 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001670 } else {
1671 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001672 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001673 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001674 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001675
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001676 QualType CanonFrom;
1677 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001678 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001679 bool ObjCLifetimeConversion;
1680 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1681 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001682 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001683 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001684 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001685 CanonFrom = S.Context.getCanonicalType(FromType);
1686 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001687 } else {
1688 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001689 SCS.Third = ICK_Identity;
1690
Mike Stump11289f42009-09-09 15:08:12 +00001691 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001692 // [...] Any difference in top-level cv-qualification is
1693 // subsumed by the initialization itself and does not constitute
1694 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001695 CanonFrom = S.Context.getCanonicalType(FromType);
1696 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001698 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001699 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001700 FromType = ToType;
1701 CanonFrom = CanonTo;
1702 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001703 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001704 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001705
1706 // If we have not converted the argument type to the parameter type,
1707 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001708 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001709 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001710
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001711 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001712}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001713
1714static bool
1715IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1716 QualType &ToType,
1717 bool InOverloadResolution,
1718 StandardConversionSequence &SCS,
1719 bool CStyle) {
1720
1721 const RecordType *UT = ToType->getAsUnionType();
1722 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1723 return false;
1724 // The field to initialize within the transparent union.
1725 RecordDecl *UD = UT->getDecl();
1726 // It's compatible if the expression matches any of the fields.
1727 for (RecordDecl::field_iterator it = UD->field_begin(),
1728 itend = UD->field_end();
1729 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001730 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1731 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001732 ToType = it->getType();
1733 return true;
1734 }
1735 }
1736 return false;
1737}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001738
1739/// IsIntegralPromotion - Determines whether the conversion from the
1740/// expression From (whose potentially-adjusted type is FromType) to
1741/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1742/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001743bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001744 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001745 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001746 if (!To) {
1747 return false;
1748 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001749
1750 // An rvalue of type char, signed char, unsigned char, short int, or
1751 // unsigned short int can be converted to an rvalue of type int if
1752 // int can represent all the values of the source type; otherwise,
1753 // the source rvalue can be converted to an rvalue of type unsigned
1754 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001755 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1756 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757 if (// We can promote any signed, promotable integer type to an int
1758 (FromType->isSignedIntegerType() ||
1759 // We can promote any unsigned integer type whose size is
1760 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001761 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001762 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001763 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001764 }
1765
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001766 return To->getKind() == BuiltinType::UInt;
1767 }
1768
Richard Smithb9c5a602012-09-13 21:18:54 +00001769 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001770 // A prvalue of an unscoped enumeration type whose underlying type is not
1771 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1772 // following types that can represent all the values of the enumeration
1773 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1774 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001775 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001776 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001777 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001778 // with lowest integer conversion rank (4.13) greater than the rank of long
1779 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001780 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001781 // C++11 [conv.prom]p4:
1782 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1783 // can be converted to a prvalue of its underlying type. Moreover, if
1784 // integral promotion can be applied to its underlying type, a prvalue of an
1785 // unscoped enumeration type whose underlying type is fixed can also be
1786 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001787 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1788 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1789 // provided for a scoped enumeration.
1790 if (FromEnumType->getDecl()->isScoped())
1791 return false;
1792
Richard Smithb9c5a602012-09-13 21:18:54 +00001793 // We can perform an integral promotion to the underlying type of the enum,
1794 // even if that's not the promoted type.
1795 if (FromEnumType->getDecl()->isFixed()) {
1796 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1797 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1798 IsIntegralPromotion(From, Underlying, ToType);
1799 }
1800
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001801 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001802 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001803 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001804 return Context.hasSameUnqualifiedType(ToType,
1805 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001806 }
John McCall56774992009-12-09 09:09:27 +00001807
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001808 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001809 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1810 // to an rvalue a prvalue of the first of the following types that can
1811 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001812 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001813 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001814 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001815 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001816 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001817 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001818 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001819 // Determine whether the type we're converting from is signed or
1820 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001821 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001822 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824 // The types we'll try to promote to, in the appropriate
1825 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001826 QualType PromoteTypes[6] = {
1827 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001828 Context.LongTy, Context.UnsignedLongTy ,
1829 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001830 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001831 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001832 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1833 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001834 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001835 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1836 // We found the type that we can promote to. If this is the
1837 // type we wanted, we have a promotion. Otherwise, no
1838 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001839 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001840 }
1841 }
1842 }
1843
1844 // An rvalue for an integral bit-field (9.6) can be converted to an
1845 // rvalue of type int if int can represent all the values of the
1846 // bit-field; otherwise, it can be converted to unsigned int if
1847 // unsigned int can represent all the values of the bit-field. If
1848 // the bit-field is larger yet, no integral promotion applies to
1849 // it. If the bit-field has an enumerated type, it is treated as any
1850 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001851 // FIXME: We should delay checking of bit-fields until we actually perform the
1852 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001853 using llvm::APSInt;
1854 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001855 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001856 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001857 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001858 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1859 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1860 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001862 // Are we promoting to an int from a bitfield that fits in an int?
1863 if (BitWidth < ToSize ||
1864 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1865 return To->getKind() == BuiltinType::Int;
1866 }
Mike Stump11289f42009-09-09 15:08:12 +00001867
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001868 // Are we promoting to an unsigned int from an unsigned bitfield
1869 // that fits into an unsigned int?
1870 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1871 return To->getKind() == BuiltinType::UInt;
1872 }
Mike Stump11289f42009-09-09 15:08:12 +00001873
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001874 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001875 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001876 }
Mike Stump11289f42009-09-09 15:08:12 +00001877
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001878 // An rvalue of type bool can be converted to an rvalue of type int,
1879 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001880 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001881 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001882 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001883
1884 return false;
1885}
1886
1887/// IsFloatingPointPromotion - Determines whether the conversion from
1888/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1889/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001890bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001891 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1892 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001893 /// An rvalue of type float can be converted to an rvalue of type
1894 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001895 if (FromBuiltin->getKind() == BuiltinType::Float &&
1896 ToBuiltin->getKind() == BuiltinType::Double)
1897 return true;
1898
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001899 // C99 6.3.1.5p1:
1900 // When a float is promoted to double or long double, or a
1901 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001902 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001903 (FromBuiltin->getKind() == BuiltinType::Float ||
1904 FromBuiltin->getKind() == BuiltinType::Double) &&
1905 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1906 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001907
1908 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001909 if (!getLangOpts().NativeHalfType &&
1910 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001911 ToBuiltin->getKind() == BuiltinType::Float)
1912 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001913 }
1914
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001915 return false;
1916}
1917
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001918/// \brief Determine if a conversion is a complex promotion.
1919///
1920/// A complex promotion is defined as a complex -> complex conversion
1921/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001922/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001923bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001924 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001925 if (!FromComplex)
1926 return false;
1927
John McCall9dd450b2009-09-21 23:43:11 +00001928 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001929 if (!ToComplex)
1930 return false;
1931
1932 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001933 ToComplex->getElementType()) ||
1934 IsIntegralPromotion(0, FromComplex->getElementType(),
1935 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001936}
1937
Douglas Gregor237f96c2008-11-26 23:31:11 +00001938/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1939/// the pointer type FromPtr to a pointer to type ToPointee, with the
1940/// same type qualifiers as FromPtr has on its pointee type. ToType,
1941/// if non-empty, will be a pointer to ToType that may or may not have
1942/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001943///
Mike Stump11289f42009-09-09 15:08:12 +00001944static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001945BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001946 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001947 ASTContext &Context,
1948 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001949 assert((FromPtr->getTypeClass() == Type::Pointer ||
1950 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1951 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001952
John McCall31168b02011-06-15 23:02:42 +00001953 /// Conversions to 'id' subsume cv-qualifier conversions.
1954 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001955 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001956
1957 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001958 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001959 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001960 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001961
John McCall31168b02011-06-15 23:02:42 +00001962 if (StripObjCLifetime)
1963 Quals.removeObjCLifetime();
1964
Mike Stump11289f42009-09-09 15:08:12 +00001965 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001966 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001967 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001968 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001969 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001970
1971 // Build a pointer to ToPointee. It has the right qualifiers
1972 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001973 if (isa<ObjCObjectPointerType>(ToType))
1974 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001975 return Context.getPointerType(ToPointee);
1976 }
1977
1978 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001979 QualType QualifiedCanonToPointee
1980 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001981
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001982 if (isa<ObjCObjectPointerType>(ToType))
1983 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1984 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001985}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001986
Mike Stump11289f42009-09-09 15:08:12 +00001987static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001988 bool InOverloadResolution,
1989 ASTContext &Context) {
1990 // Handle value-dependent integral null pointer constants correctly.
1991 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1992 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001993 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001994 return !InOverloadResolution;
1995
Douglas Gregor56751b52009-09-25 04:25:58 +00001996 return Expr->isNullPointerConstant(Context,
1997 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1998 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001999}
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002001/// IsPointerConversion - Determines whether the conversion of the
2002/// expression From, which has the (possibly adjusted) type FromType,
2003/// can be converted to the type ToType via a pointer conversion (C++
2004/// 4.10). If so, returns true and places the converted type (that
2005/// might differ from ToType in its cv-qualifiers at some level) into
2006/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002007///
Douglas Gregora29dc052008-11-27 01:19:21 +00002008/// This routine also supports conversions to and from block pointers
2009/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2010/// pointers to interfaces. FIXME: Once we've determined the
2011/// appropriate overloading rules for Objective-C, we may want to
2012/// split the Objective-C checks into a different routine; however,
2013/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002014/// conversions, so for now they live here. IncompatibleObjC will be
2015/// set if the conversion is an allowed Objective-C conversion that
2016/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002017bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002018 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002019 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002020 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002021 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002022 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2023 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002024 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002025
Mike Stump11289f42009-09-09 15:08:12 +00002026 // Conversion from a null pointer constant to any Objective-C pointer type.
2027 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002028 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002029 ConvertedType = ToType;
2030 return true;
2031 }
2032
Douglas Gregor231d1c62008-11-27 00:15:41 +00002033 // Blocks: Block pointers can be converted to void*.
2034 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002035 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002036 ConvertedType = ToType;
2037 return true;
2038 }
2039 // Blocks: A null pointer constant can be converted to a block
2040 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002041 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002042 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002043 ConvertedType = ToType;
2044 return true;
2045 }
2046
Sebastian Redl576fd422009-05-10 18:38:11 +00002047 // If the left-hand-side is nullptr_t, the right side can be a null
2048 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002049 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002050 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002051 ConvertedType = ToType;
2052 return true;
2053 }
2054
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002055 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002056 if (!ToTypePtr)
2057 return false;
2058
2059 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002060 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002061 ConvertedType = ToType;
2062 return true;
2063 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002064
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002065 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002066 // , including objective-c pointers.
2067 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002068 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002069 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002070 ConvertedType = BuildSimilarlyQualifiedPointerType(
2071 FromType->getAs<ObjCObjectPointerType>(),
2072 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002073 ToType, Context);
2074 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002075 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002076 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002077 if (!FromTypePtr)
2078 return false;
2079
2080 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002081
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002082 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002083 // pointer conversion, so don't do all of the work below.
2084 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2085 return false;
2086
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002087 // An rvalue of type "pointer to cv T," where T is an object type,
2088 // can be converted to an rvalue of type "pointer to cv void" (C++
2089 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002090 if (FromPointeeType->isIncompleteOrObjectType() &&
2091 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002092 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002093 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002094 ToType, Context,
2095 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002096 return true;
2097 }
2098
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002099 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002100 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002101 ToPointeeType->isVoidType()) {
2102 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2103 ToPointeeType,
2104 ToType, Context);
2105 return true;
2106 }
2107
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002108 // When we're overloading in C, we allow a special kind of pointer
2109 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002110 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002111 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002112 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002113 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002114 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002115 return true;
2116 }
2117
Douglas Gregor5c407d92008-10-23 00:40:37 +00002118 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002119 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002120 // An rvalue of type "pointer to cv D," where D is a class type,
2121 // can be converted to an rvalue of type "pointer to cv B," where
2122 // B is a base class (clause 10) of D. If B is an inaccessible
2123 // (clause 11) or ambiguous (10.2) base class of D, a program that
2124 // necessitates this conversion is ill-formed. The result of the
2125 // conversion is a pointer to the base class sub-object of the
2126 // derived class object. The null pointer value is converted to
2127 // the null pointer value of the destination type.
2128 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002129 // Note that we do not check for ambiguity or inaccessibility
2130 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002131 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002132 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002133 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002134 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002135 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002137 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002138 ToType, Context);
2139 return true;
2140 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002141
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002142 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2143 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2144 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2145 ToPointeeType,
2146 ToType, Context);
2147 return true;
2148 }
2149
Douglas Gregora119f102008-12-19 19:13:09 +00002150 return false;
2151}
Douglas Gregoraec25842011-04-26 23:16:46 +00002152
2153/// \brief Adopt the given qualifiers for the given type.
2154static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2155 Qualifiers TQs = T.getQualifiers();
2156
2157 // Check whether qualifiers already match.
2158 if (TQs == Qs)
2159 return T;
2160
2161 if (Qs.compatiblyIncludes(TQs))
2162 return Context.getQualifiedType(T, Qs);
2163
2164 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2165}
Douglas Gregora119f102008-12-19 19:13:09 +00002166
2167/// isObjCPointerConversion - Determines whether this is an
2168/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2169/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002170bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002171 QualType& ConvertedType,
2172 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002173 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002174 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
Douglas Gregoraec25842011-04-26 23:16:46 +00002176 // The set of qualifiers on the type we're converting from.
2177 Qualifiers FromQualifiers = FromType.getQualifiers();
2178
Steve Naroff7cae42b2009-07-10 23:34:53 +00002179 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002180 const ObjCObjectPointerType* ToObjCPtr =
2181 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002182 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002183 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002184
Steve Naroff7cae42b2009-07-10 23:34:53 +00002185 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002186 // If the pointee types are the same (ignoring qualifications),
2187 // then this is not a pointer conversion.
2188 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2189 FromObjCPtr->getPointeeType()))
2190 return false;
2191
Douglas Gregoraec25842011-04-26 23:16:46 +00002192 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002193 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002194 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002195 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002196 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002197 return true;
2198 }
2199 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002200 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002201 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002202 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002203 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002204 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002205 return true;
2206 }
2207 // Objective C++: We're able to convert from a pointer to an
2208 // interface to a pointer to a different interface.
2209 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002210 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2211 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002212 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002213 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2214 FromObjCPtr->getPointeeType()))
2215 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002216 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002217 ToObjCPtr->getPointeeType(),
2218 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002219 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002220 return true;
2221 }
2222
2223 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2224 // Okay: this is some kind of implicit downcast of Objective-C
2225 // interfaces, which is permitted. However, we're going to
2226 // complain about it.
2227 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002228 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002229 ToObjCPtr->getPointeeType(),
2230 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002231 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002232 return true;
2233 }
Mike Stump11289f42009-09-09 15:08:12 +00002234 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002235 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002236 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002237 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002238 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002239 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002240 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002241 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002242 // to a block pointer type.
2243 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002244 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002245 return true;
2246 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002247 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002248 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002249 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002250 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002251 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002252 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002253 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002254 return true;
2255 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002256 else
Douglas Gregora119f102008-12-19 19:13:09 +00002257 return false;
2258
Douglas Gregor033f56d2008-12-23 00:53:59 +00002259 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002260 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002261 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002262 else if (const BlockPointerType *FromBlockPtr =
2263 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002264 FromPointeeType = FromBlockPtr->getPointeeType();
2265 else
Douglas Gregora119f102008-12-19 19:13:09 +00002266 return false;
2267
Douglas Gregora119f102008-12-19 19:13:09 +00002268 // If we have pointers to pointers, recursively check whether this
2269 // is an Objective-C conversion.
2270 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2271 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2272 IncompatibleObjC)) {
2273 // We always complain about this conversion.
2274 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002275 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002276 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002277 return true;
2278 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002279 // Allow conversion of pointee being objective-c pointer to another one;
2280 // as in I* to id.
2281 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2282 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2283 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2284 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002285
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002286 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002287 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002288 return true;
2289 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002290
Douglas Gregor033f56d2008-12-23 00:53:59 +00002291 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002292 // differences in the argument and result types are in Objective-C
2293 // pointer conversions. If so, we permit the conversion (but
2294 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002295 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002296 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002297 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002298 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002299 if (FromFunctionType && ToFunctionType) {
2300 // If the function types are exactly the same, this isn't an
2301 // Objective-C pointer conversion.
2302 if (Context.getCanonicalType(FromPointeeType)
2303 == Context.getCanonicalType(ToPointeeType))
2304 return false;
2305
2306 // Perform the quick checks that will tell us whether these
2307 // function types are obviously different.
2308 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2309 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2310 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2311 return false;
2312
2313 bool HasObjCConversion = false;
2314 if (Context.getCanonicalType(FromFunctionType->getResultType())
2315 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2316 // Okay, the types match exactly. Nothing to do.
2317 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2318 ToFunctionType->getResultType(),
2319 ConvertedType, IncompatibleObjC)) {
2320 // Okay, we have an Objective-C pointer conversion.
2321 HasObjCConversion = true;
2322 } else {
2323 // Function types are too different. Abort.
2324 return false;
2325 }
Mike Stump11289f42009-09-09 15:08:12 +00002326
Douglas Gregora119f102008-12-19 19:13:09 +00002327 // Check argument types.
2328 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2329 ArgIdx != NumArgs; ++ArgIdx) {
2330 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2331 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2332 if (Context.getCanonicalType(FromArgType)
2333 == Context.getCanonicalType(ToArgType)) {
2334 // Okay, the types match exactly. Nothing to do.
2335 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2336 ConvertedType, IncompatibleObjC)) {
2337 // Okay, we have an Objective-C pointer conversion.
2338 HasObjCConversion = true;
2339 } else {
2340 // Argument types are too different. Abort.
2341 return false;
2342 }
2343 }
2344
2345 if (HasObjCConversion) {
2346 // We had an Objective-C conversion. Allow this pointer
2347 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002348 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002349 IncompatibleObjC = true;
2350 return true;
2351 }
2352 }
2353
Sebastian Redl72b597d2009-01-25 19:43:20 +00002354 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002355}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002356
John McCall31168b02011-06-15 23:02:42 +00002357/// \brief Determine whether this is an Objective-C writeback conversion,
2358/// used for parameter passing when performing automatic reference counting.
2359///
2360/// \param FromType The type we're converting form.
2361///
2362/// \param ToType The type we're converting to.
2363///
2364/// \param ConvertedType The type that will be produced after applying
2365/// this conversion.
2366bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2367 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002368 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002369 Context.hasSameUnqualifiedType(FromType, ToType))
2370 return false;
2371
2372 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2373 QualType ToPointee;
2374 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2375 ToPointee = ToPointer->getPointeeType();
2376 else
2377 return false;
2378
2379 Qualifiers ToQuals = ToPointee.getQualifiers();
2380 if (!ToPointee->isObjCLifetimeType() ||
2381 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002382 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002383 return false;
2384
2385 // Argument must be a pointer to __strong to __weak.
2386 QualType FromPointee;
2387 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2388 FromPointee = FromPointer->getPointeeType();
2389 else
2390 return false;
2391
2392 Qualifiers FromQuals = FromPointee.getQualifiers();
2393 if (!FromPointee->isObjCLifetimeType() ||
2394 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2395 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2396 return false;
2397
2398 // Make sure that we have compatible qualifiers.
2399 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2400 if (!ToQuals.compatiblyIncludes(FromQuals))
2401 return false;
2402
2403 // Remove qualifiers from the pointee type we're converting from; they
2404 // aren't used in the compatibility check belong, and we'll be adding back
2405 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2406 FromPointee = FromPointee.getUnqualifiedType();
2407
2408 // The unqualified form of the pointee types must be compatible.
2409 ToPointee = ToPointee.getUnqualifiedType();
2410 bool IncompatibleObjC;
2411 if (Context.typesAreCompatible(FromPointee, ToPointee))
2412 FromPointee = ToPointee;
2413 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2414 IncompatibleObjC))
2415 return false;
2416
2417 /// \brief Construct the type we're converting to, which is a pointer to
2418 /// __autoreleasing pointee.
2419 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2420 ConvertedType = Context.getPointerType(FromPointee);
2421 return true;
2422}
2423
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002424bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2425 QualType& ConvertedType) {
2426 QualType ToPointeeType;
2427 if (const BlockPointerType *ToBlockPtr =
2428 ToType->getAs<BlockPointerType>())
2429 ToPointeeType = ToBlockPtr->getPointeeType();
2430 else
2431 return false;
2432
2433 QualType FromPointeeType;
2434 if (const BlockPointerType *FromBlockPtr =
2435 FromType->getAs<BlockPointerType>())
2436 FromPointeeType = FromBlockPtr->getPointeeType();
2437 else
2438 return false;
2439 // We have pointer to blocks, check whether the only
2440 // differences in the argument and result types are in Objective-C
2441 // pointer conversions. If so, we permit the conversion.
2442
2443 const FunctionProtoType *FromFunctionType
2444 = FromPointeeType->getAs<FunctionProtoType>();
2445 const FunctionProtoType *ToFunctionType
2446 = ToPointeeType->getAs<FunctionProtoType>();
2447
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002448 if (!FromFunctionType || !ToFunctionType)
2449 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002450
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002451 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002452 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002453
2454 // Perform the quick checks that will tell us whether these
2455 // function types are obviously different.
2456 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2457 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2458 return false;
2459
2460 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2461 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2462 if (FromEInfo != ToEInfo)
2463 return false;
2464
2465 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002466 if (Context.hasSameType(FromFunctionType->getResultType(),
2467 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002468 // Okay, the types match exactly. Nothing to do.
2469 } else {
2470 QualType RHS = FromFunctionType->getResultType();
2471 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002472 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002473 !RHS.hasQualifiers() && LHS.hasQualifiers())
2474 LHS = LHS.getUnqualifiedType();
2475
2476 if (Context.hasSameType(RHS,LHS)) {
2477 // OK exact match.
2478 } else if (isObjCPointerConversion(RHS, LHS,
2479 ConvertedType, IncompatibleObjC)) {
2480 if (IncompatibleObjC)
2481 return false;
2482 // Okay, we have an Objective-C pointer conversion.
2483 }
2484 else
2485 return false;
2486 }
2487
2488 // Check argument types.
2489 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2490 ArgIdx != NumArgs; ++ArgIdx) {
2491 IncompatibleObjC = false;
2492 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2493 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2494 if (Context.hasSameType(FromArgType, ToArgType)) {
2495 // Okay, the types match exactly. Nothing to do.
2496 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2497 ConvertedType, IncompatibleObjC)) {
2498 if (IncompatibleObjC)
2499 return false;
2500 // Okay, we have an Objective-C pointer conversion.
2501 } else
2502 // Argument types are too different. Abort.
2503 return false;
2504 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002505 if (LangOpts.ObjCAutoRefCount &&
2506 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2507 ToFunctionType))
2508 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002509
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002510 ConvertedType = ToType;
2511 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002512}
2513
Richard Trieucaff2472011-11-23 22:32:32 +00002514enum {
2515 ft_default,
2516 ft_different_class,
2517 ft_parameter_arity,
2518 ft_parameter_mismatch,
2519 ft_return_type,
2520 ft_qualifer_mismatch
2521};
2522
2523/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2524/// function types. Catches different number of parameter, mismatch in
2525/// parameter types, and different return types.
2526void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2527 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002528 // If either type is not valid, include no extra info.
2529 if (FromType.isNull() || ToType.isNull()) {
2530 PDiag << ft_default;
2531 return;
2532 }
2533
Richard Trieucaff2472011-11-23 22:32:32 +00002534 // Get the function type from the pointers.
2535 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2536 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2537 *ToMember = ToType->getAs<MemberPointerType>();
2538 if (FromMember->getClass() != ToMember->getClass()) {
2539 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2540 << QualType(FromMember->getClass(), 0);
2541 return;
2542 }
2543 FromType = FromMember->getPointeeType();
2544 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002545 }
2546
Richard Trieu96ed5b62011-12-13 23:19:45 +00002547 if (FromType->isPointerType())
2548 FromType = FromType->getPointeeType();
2549 if (ToType->isPointerType())
2550 ToType = ToType->getPointeeType();
2551
2552 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002553 FromType = FromType.getNonReferenceType();
2554 ToType = ToType.getNonReferenceType();
2555
Richard Trieucaff2472011-11-23 22:32:32 +00002556 // Don't print extra info for non-specialized template functions.
2557 if (FromType->isInstantiationDependentType() &&
2558 !FromType->getAs<TemplateSpecializationType>()) {
2559 PDiag << ft_default;
2560 return;
2561 }
2562
Richard Trieu96ed5b62011-12-13 23:19:45 +00002563 // No extra info for same types.
2564 if (Context.hasSameType(FromType, ToType)) {
2565 PDiag << ft_default;
2566 return;
2567 }
2568
Richard Trieucaff2472011-11-23 22:32:32 +00002569 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2570 *ToFunction = ToType->getAs<FunctionProtoType>();
2571
2572 // Both types need to be function types.
2573 if (!FromFunction || !ToFunction) {
2574 PDiag << ft_default;
2575 return;
2576 }
2577
2578 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2579 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2580 << FromFunction->getNumArgs();
2581 return;
2582 }
2583
2584 // Handle different parameter types.
2585 unsigned ArgPos;
2586 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2587 PDiag << ft_parameter_mismatch << ArgPos + 1
2588 << ToFunction->getArgType(ArgPos)
2589 << FromFunction->getArgType(ArgPos);
2590 return;
2591 }
2592
2593 // Handle different return type.
2594 if (!Context.hasSameType(FromFunction->getResultType(),
2595 ToFunction->getResultType())) {
2596 PDiag << ft_return_type << ToFunction->getResultType()
2597 << FromFunction->getResultType();
2598 return;
2599 }
2600
2601 unsigned FromQuals = FromFunction->getTypeQuals(),
2602 ToQuals = ToFunction->getTypeQuals();
2603 if (FromQuals != ToQuals) {
2604 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2605 return;
2606 }
2607
2608 // Unable to find a difference, so add no extra info.
2609 PDiag << ft_default;
2610}
2611
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002612/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002613/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002614/// they have same number of arguments. If the parameters are different,
2615/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002616bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002617 const FunctionProtoType *NewType,
2618 unsigned *ArgPos) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002619 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2620 N = NewType->arg_type_begin(),
2621 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002622 if (!Context.hasSameType(O->getUnqualifiedType(),
2623 N->getUnqualifiedType())) {
Larisse Voufo4154f462013-08-06 03:57:41 +00002624 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2625 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002626 }
2627 }
2628 return true;
2629}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002630
Douglas Gregor39c16d42008-10-24 04:54:22 +00002631/// CheckPointerConversion - Check the pointer conversion from the
2632/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002633/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002634/// conversions for which IsPointerConversion has already returned
2635/// true. It returns true and produces a diagnostic if there was an
2636/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002637bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002638 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002639 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002640 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002641 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002642 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002643
John McCall8cb679e2010-11-15 09:13:47 +00002644 Kind = CK_BitCast;
2645
David Blaikie1c7c8f72012-08-08 17:33:31 +00002646 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2647 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2648 Expr::NPCK_ZeroExpression) {
2649 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2650 DiagRuntimeBehavior(From->getExprLoc(), From,
2651 PDiag(diag::warn_impcast_bool_to_null_pointer)
2652 << ToType << From->getSourceRange());
2653 else if (!isUnevaluatedContext())
2654 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2655 << ToType << From->getSourceRange();
2656 }
John McCall9320b872011-09-09 05:25:32 +00002657 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2658 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002659 QualType FromPointeeType = FromPtrType->getPointeeType(),
2660 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002661
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002662 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2663 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002664 // We must have a derived-to-base conversion. Check an
2665 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002666 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2667 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002668 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002669 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002670 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002672 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002673 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002674 }
2675 }
John McCall9320b872011-09-09 05:25:32 +00002676 } else if (const ObjCObjectPointerType *ToPtrType =
2677 ToType->getAs<ObjCObjectPointerType>()) {
2678 if (const ObjCObjectPointerType *FromPtrType =
2679 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002680 // Objective-C++ conversions are always okay.
2681 // FIXME: We should have a different class of conversions for the
2682 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002683 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002684 return false;
John McCall9320b872011-09-09 05:25:32 +00002685 } else if (FromType->isBlockPointerType()) {
2686 Kind = CK_BlockPointerToObjCPointerCast;
2687 } else {
2688 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002689 }
John McCall9320b872011-09-09 05:25:32 +00002690 } else if (ToType->isBlockPointerType()) {
2691 if (!FromType->isBlockPointerType())
2692 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002693 }
John McCall8cb679e2010-11-15 09:13:47 +00002694
2695 // We shouldn't fall into this case unless it's valid for other
2696 // reasons.
2697 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2698 Kind = CK_NullToPointer;
2699
Douglas Gregor39c16d42008-10-24 04:54:22 +00002700 return false;
2701}
2702
Sebastian Redl72b597d2009-01-25 19:43:20 +00002703/// IsMemberPointerConversion - Determines whether the conversion of the
2704/// expression From, which has the (possibly adjusted) type FromType, can be
2705/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2706/// If so, returns true and places the converted type (that might differ from
2707/// ToType in its cv-qualifiers at some level) into ConvertedType.
2708bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002709 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002710 bool InOverloadResolution,
2711 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002712 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002713 if (!ToTypePtr)
2714 return false;
2715
2716 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002717 if (From->isNullPointerConstant(Context,
2718 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2719 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002720 ConvertedType = ToType;
2721 return true;
2722 }
2723
2724 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002725 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002726 if (!FromTypePtr)
2727 return false;
2728
2729 // A pointer to member of B can be converted to a pointer to member of D,
2730 // where D is derived from B (C++ 4.11p2).
2731 QualType FromClass(FromTypePtr->getClass(), 0);
2732 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002733
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002734 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002735 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002736 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002737 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2738 ToClass.getTypePtr());
2739 return true;
2740 }
2741
2742 return false;
2743}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002744
Sebastian Redl72b597d2009-01-25 19:43:20 +00002745/// CheckMemberPointerConversion - Check the member pointer conversion from the
2746/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002747/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002748/// for which IsMemberPointerConversion has already returned true. It returns
2749/// true and produces a diagnostic if there was an error, or returns false
2750/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002751bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002752 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002753 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002754 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002755 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002756 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002757 if (!FromPtrType) {
2758 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002759 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002760 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002761 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002762 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002763 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002764 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002765
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002766 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002767 assert(ToPtrType && "No member pointer cast has a target type "
2768 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002769
Sebastian Redled8f2002009-01-28 18:33:18 +00002770 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2771 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002772
Sebastian Redled8f2002009-01-28 18:33:18 +00002773 // FIXME: What about dependent types?
2774 assert(FromClass->isRecordType() && "Pointer into non-class.");
2775 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002776
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002777 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002778 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002779 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2780 assert(DerivationOkay &&
2781 "Should not have been called if derivation isn't OK.");
2782 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002783
Sebastian Redled8f2002009-01-28 18:33:18 +00002784 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2785 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002786 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2787 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2788 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2789 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002790 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002791
Douglas Gregor89ee6822009-02-28 01:32:25 +00002792 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002793 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2794 << FromClass << ToClass << QualType(VBase, 0)
2795 << From->getSourceRange();
2796 return true;
2797 }
2798
John McCall5b0829a2010-02-10 09:31:12 +00002799 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002800 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2801 Paths.front(),
2802 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002803
Anders Carlssond7923c62009-08-22 23:33:40 +00002804 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002805 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002806 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002807 return false;
2808}
2809
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002810/// Determine whether the lifetime conversion between the two given
2811/// qualifiers sets is nontrivial.
2812static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2813 Qualifiers ToQuals) {
2814 // Converting anything to const __unsafe_unretained is trivial.
2815 if (ToQuals.hasConst() &&
2816 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2817 return false;
2818
2819 return true;
2820}
2821
Douglas Gregor9a657932008-10-21 23:43:52 +00002822/// IsQualificationConversion - Determines whether the conversion from
2823/// an rvalue of type FromType to ToType is a qualification conversion
2824/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002825///
2826/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2827/// when the qualification conversion involves a change in the Objective-C
2828/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002829bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002830Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002831 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002832 FromType = Context.getCanonicalType(FromType);
2833 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002834 ObjCLifetimeConversion = false;
2835
Douglas Gregor9a657932008-10-21 23:43:52 +00002836 // If FromType and ToType are the same type, this is not a
2837 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002838 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002839 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002840
Douglas Gregor9a657932008-10-21 23:43:52 +00002841 // (C++ 4.4p4):
2842 // A conversion can add cv-qualifiers at levels other than the first
2843 // in multi-level pointers, subject to the following rules: [...]
2844 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002845 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002846 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002847 // Within each iteration of the loop, we check the qualifiers to
2848 // determine if this still looks like a qualification
2849 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002850 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002851 // until there are no more pointers or pointers-to-members left to
2852 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002853 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002854
Douglas Gregor90609aa2011-04-25 18:40:17 +00002855 Qualifiers FromQuals = FromType.getQualifiers();
2856 Qualifiers ToQuals = ToType.getQualifiers();
2857
John McCall31168b02011-06-15 23:02:42 +00002858 // Objective-C ARC:
2859 // Check Objective-C lifetime conversions.
2860 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2861 UnwrappedAnyPointer) {
2862 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002863 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2864 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002865 FromQuals.removeObjCLifetime();
2866 ToQuals.removeObjCLifetime();
2867 } else {
2868 // Qualification conversions cannot cast between different
2869 // Objective-C lifetime qualifiers.
2870 return false;
2871 }
2872 }
2873
Douglas Gregorf30053d2011-05-08 06:09:53 +00002874 // Allow addition/removal of GC attributes but not changing GC attributes.
2875 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2876 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2877 FromQuals.removeObjCGCAttr();
2878 ToQuals.removeObjCGCAttr();
2879 }
2880
Douglas Gregor9a657932008-10-21 23:43:52 +00002881 // -- for every j > 0, if const is in cv 1,j then const is in cv
2882 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002883 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002884 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002885
Douglas Gregor9a657932008-10-21 23:43:52 +00002886 // -- if the cv 1,j and cv 2,j are different, then const is in
2887 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002888 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002889 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002890 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002891
Douglas Gregor9a657932008-10-21 23:43:52 +00002892 // Keep track of whether all prior cv-qualifiers in the "to" type
2893 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002894 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002895 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002896 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002897
2898 // We are left with FromType and ToType being the pointee types
2899 // after unwrapping the original FromType and ToType the same number
2900 // of types. If we unwrapped any pointers, and if FromType and
2901 // ToType have the same unqualified type (since we checked
2902 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002903 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002904}
2905
Douglas Gregorc79862f2012-04-12 17:51:55 +00002906/// \brief - Determine whether this is a conversion from a scalar type to an
2907/// atomic type.
2908///
2909/// If successful, updates \c SCS's second and third steps in the conversion
2910/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002911static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2912 bool InOverloadResolution,
2913 StandardConversionSequence &SCS,
2914 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002915 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2916 if (!ToAtomic)
2917 return false;
2918
2919 StandardConversionSequence InnerSCS;
2920 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2921 InOverloadResolution, InnerSCS,
2922 CStyle, /*AllowObjCWritebackConversion=*/false))
2923 return false;
2924
2925 SCS.Second = InnerSCS.Second;
2926 SCS.setToType(1, InnerSCS.getToType(1));
2927 SCS.Third = InnerSCS.Third;
2928 SCS.QualificationIncludesObjCLifetime
2929 = InnerSCS.QualificationIncludesObjCLifetime;
2930 SCS.setToType(2, InnerSCS.getToType(2));
2931 return true;
2932}
2933
Sebastian Redle5417162012-03-27 18:33:03 +00002934static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2935 CXXConstructorDecl *Constructor,
2936 QualType Type) {
2937 const FunctionProtoType *CtorType =
2938 Constructor->getType()->getAs<FunctionProtoType>();
2939 if (CtorType->getNumArgs() > 0) {
2940 QualType FirstArg = CtorType->getArgType(0);
2941 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2942 return true;
2943 }
2944 return false;
2945}
2946
Sebastian Redl82ace982012-02-11 23:51:08 +00002947static OverloadingResult
2948IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2949 CXXRecordDecl *To,
2950 UserDefinedConversionSequence &User,
2951 OverloadCandidateSet &CandidateSet,
2952 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002953 DeclContext::lookup_result R = S.LookupConstructors(To);
2954 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002955 Con != ConEnd; ++Con) {
2956 NamedDecl *D = *Con;
2957 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2958
2959 // Find the constructor (which may be a template).
2960 CXXConstructorDecl *Constructor = 0;
2961 FunctionTemplateDecl *ConstructorTmpl
2962 = dyn_cast<FunctionTemplateDecl>(D);
2963 if (ConstructorTmpl)
2964 Constructor
2965 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2966 else
2967 Constructor = cast<CXXConstructorDecl>(D);
2968
2969 bool Usable = !Constructor->isInvalidDecl() &&
2970 S.isInitListConstructor(Constructor) &&
2971 (AllowExplicit || !Constructor->isExplicit());
2972 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002973 // If the first argument is (a reference to) the target type,
2974 // suppress conversions.
2975 bool SuppressUserConversions =
2976 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002977 if (ConstructorTmpl)
2978 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2979 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002980 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002981 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002982 else
2983 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002984 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002985 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002986 }
2987 }
2988
2989 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2990
2991 OverloadCandidateSet::iterator Best;
2992 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2993 case OR_Success: {
2994 // Record the standard conversion we used and the conversion function.
2995 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002996 QualType ThisType = Constructor->getThisType(S.Context);
2997 // Initializer lists don't have conversions as such.
2998 User.Before.setAsIdentityConversion();
2999 User.HadMultipleCandidates = HadMultipleCandidates;
3000 User.ConversionFunction = Constructor;
3001 User.FoundConversionFunction = Best->FoundDecl;
3002 User.After.setAsIdentityConversion();
3003 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3004 User.After.setAllToTypes(ToType);
3005 return OR_Success;
3006 }
3007
3008 case OR_No_Viable_Function:
3009 return OR_No_Viable_Function;
3010 case OR_Deleted:
3011 return OR_Deleted;
3012 case OR_Ambiguous:
3013 return OR_Ambiguous;
3014 }
3015
3016 llvm_unreachable("Invalid OverloadResult!");
3017}
3018
Douglas Gregor576e98c2009-01-30 23:27:23 +00003019/// Determines whether there is a user-defined conversion sequence
3020/// (C++ [over.ics.user]) that converts expression From to the type
3021/// ToType. If such a conversion exists, User will contain the
3022/// user-defined conversion sequence that performs such a conversion
3023/// and this routine will return true. Otherwise, this routine returns
3024/// false and User is unspecified.
3025///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003026/// \param AllowExplicit true if the conversion should consider C++0x
3027/// "explicit" conversion functions as well as non-explicit conversion
3028/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003029///
3030/// \param AllowObjCConversionOnExplicit true if the conversion should
3031/// allow an extra Objective-C pointer conversion on uses of explicit
3032/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003033static OverloadingResult
3034IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003035 UserDefinedConversionSequence &User,
3036 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003037 bool AllowExplicit,
3038 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003039 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003040
Douglas Gregor5ab11652010-04-17 22:01:05 +00003041 // Whether we will only visit constructors.
3042 bool ConstructorsOnly = false;
3043
3044 // If the type we are conversion to is a class type, enumerate its
3045 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003046 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003047 // C++ [over.match.ctor]p1:
3048 // When objects of class type are direct-initialized (8.5), or
3049 // copy-initialized from an expression of the same or a
3050 // derived class type (8.5), overload resolution selects the
3051 // constructor. [...] For copy-initialization, the candidate
3052 // functions are all the converting constructors (12.3.1) of
3053 // that class. The argument list is the expression-list within
3054 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003055 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003056 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003057 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003058 ConstructorsOnly = true;
3059
Benjamin Kramer90633e32012-11-23 17:04:52 +00003060 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003061 // RequireCompleteType may have returned true due to some invalid decl
3062 // during template instantiation, but ToType may be complete enough now
3063 // to try to recover.
3064 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003065 // We're not going to find any constructors.
3066 } else if (CXXRecordDecl *ToRecordDecl
3067 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003068
3069 Expr **Args = &From;
3070 unsigned NumArgs = 1;
3071 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003072 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003073 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003074 OverloadingResult Result = IsInitializerListConstructorConversion(
3075 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3076 if (Result != OR_No_Viable_Function)
3077 return Result;
3078 // Never mind.
3079 CandidateSet.clear();
3080
3081 // If we're list-initializing, we pass the individual elements as
3082 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003083 Args = InitList->getInits();
3084 NumArgs = InitList->getNumInits();
3085 ListInitializing = true;
3086 }
3087
David Blaikieff7d47a2012-12-19 00:45:41 +00003088 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3089 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003090 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003091 NamedDecl *D = *Con;
3092 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3093
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003094 // Find the constructor (which may be a template).
3095 CXXConstructorDecl *Constructor = 0;
3096 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003097 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003098 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003099 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003100 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3101 else
John McCalla0296f72010-03-19 07:35:19 +00003102 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003103
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003104 bool Usable = !Constructor->isInvalidDecl();
3105 if (ListInitializing)
3106 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3107 else
3108 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3109 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003110 bool SuppressUserConversions = !ConstructorsOnly;
3111 if (SuppressUserConversions && ListInitializing) {
3112 SuppressUserConversions = false;
3113 if (NumArgs == 1) {
3114 // If the first argument is (a reference to) the target type,
3115 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003116 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3117 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003118 }
3119 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003120 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003121 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3122 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003123 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003124 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003125 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003126 // Allow one user-defined conversion when user specifies a
3127 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003128 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003129 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003130 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003131 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003132 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003133 }
3134 }
3135
Douglas Gregor5ab11652010-04-17 22:01:05 +00003136 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003137 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003138 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003139 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003140 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003141 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003142 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003143 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3144 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003145 std::pair<CXXRecordDecl::conversion_iterator,
3146 CXXRecordDecl::conversion_iterator>
3147 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3148 for (CXXRecordDecl::conversion_iterator
3149 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003150 DeclAccessPair FoundDecl = I.getPair();
3151 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003152 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3153 if (isa<UsingShadowDecl>(D))
3154 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3155
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003156 CXXConversionDecl *Conv;
3157 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003158 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3159 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003160 else
John McCallda4458e2010-03-31 01:36:47 +00003161 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003162
3163 if (AllowExplicit || !Conv->isExplicit()) {
3164 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003165 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3166 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003167 CandidateSet,
3168 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003169 else
John McCall5c32be02010-08-24 20:38:10 +00003170 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003171 From, ToType, CandidateSet,
3172 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003173 }
3174 }
3175 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003176 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003177
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003178 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3179
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003180 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003181 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003182 case OR_Success:
3183 // Record the standard conversion we used and the conversion function.
3184 if (CXXConstructorDecl *Constructor
3185 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3186 // C++ [over.ics.user]p1:
3187 // If the user-defined conversion is specified by a
3188 // constructor (12.3.1), the initial standard conversion
3189 // sequence converts the source type to the type required by
3190 // the argument of the constructor.
3191 //
3192 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003193 if (isa<InitListExpr>(From)) {
3194 // Initializer lists don't have conversions as such.
3195 User.Before.setAsIdentityConversion();
3196 } else {
3197 if (Best->Conversions[0].isEllipsis())
3198 User.EllipsisConversion = true;
3199 else {
3200 User.Before = Best->Conversions[0].Standard;
3201 User.EllipsisConversion = false;
3202 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003203 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003204 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003205 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003206 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003207 User.After.setAsIdentityConversion();
3208 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3209 User.After.setAllToTypes(ToType);
3210 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003211 }
3212 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003213 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3214 // C++ [over.ics.user]p1:
3215 //
3216 // [...] If the user-defined conversion is specified by a
3217 // conversion function (12.3.2), the initial standard
3218 // conversion sequence converts the source type to the
3219 // implicit object parameter of the conversion function.
3220 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003221 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003222 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003223 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003224 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003225
John McCall5c32be02010-08-24 20:38:10 +00003226 // C++ [over.ics.user]p2:
3227 // The second standard conversion sequence converts the
3228 // result of the user-defined conversion to the target type
3229 // for the sequence. Since an implicit conversion sequence
3230 // is an initialization, the special rules for
3231 // initialization by user-defined conversion apply when
3232 // selecting the best user-defined conversion for a
3233 // user-defined conversion sequence (see 13.3.3 and
3234 // 13.3.3.1).
3235 User.After = Best->FinalConversion;
3236 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003237 }
David Blaikie8a40f702012-01-17 06:56:22 +00003238 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003239
John McCall5c32be02010-08-24 20:38:10 +00003240 case OR_No_Viable_Function:
3241 return OR_No_Viable_Function;
3242 case OR_Deleted:
3243 // No conversion here! We're done.
3244 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245
John McCall5c32be02010-08-24 20:38:10 +00003246 case OR_Ambiguous:
3247 return OR_Ambiguous;
3248 }
3249
David Blaikie8a40f702012-01-17 06:56:22 +00003250 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003251}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003252
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003253bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003254Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003255 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003256 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003257 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003258 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003259 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003260 if (OvResult == OR_Ambiguous)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003261 Diag(From->getLocStart(), diag::err_typecheck_ambiguous_condition)
3262 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003263 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003264 if (!RequireCompleteType(From->getLocStart(), ToType,
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003265 diag::err_typecheck_nonviable_condition_incomplete,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003266 From->getType(), From->getSourceRange()))
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003267 Diag(From->getLocStart(), diag::err_typecheck_nonviable_condition)
3268 << From->getType() << From->getSourceRange() << ToType;
3269 } else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003270 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003271 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003272 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003273}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003274
Douglas Gregor2837aa22012-02-22 17:32:19 +00003275/// \brief Compare the user-defined conversion functions or constructors
3276/// of two user-defined conversion sequences to determine whether any ordering
3277/// is possible.
3278static ImplicitConversionSequence::CompareKind
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003279compareConversionFunctions(Sema &S, FunctionDecl *Function1,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003280 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003281 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003282 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003283
Douglas Gregor2837aa22012-02-22 17:32:19 +00003284 // Objective-C++:
3285 // If both conversion functions are implicitly-declared conversions from
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003286 // a lambda closure type to a function pointer and a block pointer,
Douglas Gregor2837aa22012-02-22 17:32:19 +00003287 // respectively, always prefer the conversion to a function pointer,
3288 // because the function pointer is more lightweight and is more likely
3289 // to keep code working.
3290 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3291 if (!Conv1)
3292 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003293
Douglas Gregor2837aa22012-02-22 17:32:19 +00003294 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3295 if (!Conv2)
3296 return ImplicitConversionSequence::Indistinguishable;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003297
Douglas Gregor2837aa22012-02-22 17:32:19 +00003298 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3299 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3300 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3301 if (Block1 != Block2)
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003302 return Block1 ? ImplicitConversionSequence::Worse
3303 : ImplicitConversionSequence::Better;
Douglas Gregor2837aa22012-02-22 17:32:19 +00003304 }
3305
3306 return ImplicitConversionSequence::Indistinguishable;
3307}
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003308
3309static bool hasDeprecatedStringLiteralToCharPtrConversion(
3310 const ImplicitConversionSequence &ICS) {
3311 return (ICS.isStandard() && ICS.Standard.DeprecatedStringLiteralToCharPtr) ||
3312 (ICS.isUserDefined() &&
3313 ICS.UserDefined.Before.DeprecatedStringLiteralToCharPtr);
3314}
3315
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003316/// CompareImplicitConversionSequences - Compare two implicit
3317/// conversion sequences to determine whether one is better than the
3318/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003319static ImplicitConversionSequence::CompareKind
3320CompareImplicitConversionSequences(Sema &S,
3321 const ImplicitConversionSequence& ICS1,
3322 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003323{
3324 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3325 // conversion sequences (as defined in 13.3.3.1)
3326 // -- a standard conversion sequence (13.3.3.1.1) is a better
3327 // conversion sequence than a user-defined conversion sequence or
3328 // an ellipsis conversion sequence, and
3329 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3330 // conversion sequence than an ellipsis conversion sequence
3331 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003332 //
John McCall0d1da222010-01-12 00:44:57 +00003333 // C++0x [over.best.ics]p10:
3334 // For the purpose of ranking implicit conversion sequences as
3335 // described in 13.3.3.2, the ambiguous conversion sequence is
3336 // treated as a user-defined sequence that is indistinguishable
3337 // from any other user-defined conversion sequence.
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00003338
3339 // String literal to 'char *' conversion has been deprecated in C++03. It has
3340 // been removed from C++11. We still accept this conversion, if it happens at
3341 // the best viable function. Otherwise, this conversion is considered worse
3342 // than ellipsis conversion. Consider this as an extension; this is not in the
3343 // standard. For example:
3344 //
3345 // int &f(...); // #1
3346 // void f(char*); // #2
3347 // void g() { int &r = f("foo"); }
3348 //
3349 // In C++03, we pick #2 as the best viable function.
3350 // In C++11, we pick #1 as the best viable function, because ellipsis
3351 // conversion is better than string-literal to char* conversion (since there
3352 // is no such conversion in C++11). If there was no #1 at all or #1 couldn't
3353 // convert arguments, #2 would be the best viable function in C++11.
3354 // If the best viable function has this conversion, a warning will be issued
3355 // in C++03, or an ExtWarn (+SFINAE failure) will be issued in C++11.
3356
3357 if (S.getLangOpts().CPlusPlus11 && !S.getLangOpts().WritableStrings &&
3358 hasDeprecatedStringLiteralToCharPtrConversion(ICS1) !=
3359 hasDeprecatedStringLiteralToCharPtrConversion(ICS2))
3360 return hasDeprecatedStringLiteralToCharPtrConversion(ICS1)
3361 ? ImplicitConversionSequence::Worse
3362 : ImplicitConversionSequence::Better;
3363
Douglas Gregor5ab11652010-04-17 22:01:05 +00003364 if (ICS1.getKindRank() < ICS2.getKindRank())
3365 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003366 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003367 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003368
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003369 // The following checks require both conversion sequences to be of
3370 // the same kind.
3371 if (ICS1.getKind() != ICS2.getKind())
3372 return ImplicitConversionSequence::Indistinguishable;
3373
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003374 ImplicitConversionSequence::CompareKind Result =
3375 ImplicitConversionSequence::Indistinguishable;
3376
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003377 // Two implicit conversion sequences of the same form are
3378 // indistinguishable conversion sequences unless one of the
3379 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003380 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003381 Result = CompareStandardConversionSequences(S,
3382 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003383 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003384 // User-defined conversion sequence U1 is a better conversion
3385 // sequence than another user-defined conversion sequence U2 if
3386 // they contain the same user-defined conversion function or
3387 // constructor and if the second standard conversion sequence of
3388 // U1 is better than the second standard conversion sequence of
3389 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003390 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003391 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003392 Result = CompareStandardConversionSequences(S,
3393 ICS1.UserDefined.After,
3394 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003395 else
3396 Result = compareConversionFunctions(S,
3397 ICS1.UserDefined.ConversionFunction,
3398 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003399 }
3400
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003401 // List-initialization sequence L1 is a better conversion sequence than
3402 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3403 // for some X and L2 does not.
3404 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003405 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003406 if (ICS1.isStdInitializerListElement() &&
3407 !ICS2.isStdInitializerListElement())
3408 return ImplicitConversionSequence::Better;
3409 if (!ICS1.isStdInitializerListElement() &&
3410 ICS2.isStdInitializerListElement())
3411 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003412 }
3413
3414 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003415}
3416
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003417static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3418 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3419 Qualifiers Quals;
3420 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003421 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003423
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003424 return Context.hasSameUnqualifiedType(T1, T2);
3425}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003426
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003427// Per 13.3.3.2p3, compare the given standard conversion sequences to
3428// determine if one is a proper subset of the other.
3429static ImplicitConversionSequence::CompareKind
3430compareStandardConversionSubsets(ASTContext &Context,
3431 const StandardConversionSequence& SCS1,
3432 const StandardConversionSequence& SCS2) {
3433 ImplicitConversionSequence::CompareKind Result
3434 = ImplicitConversionSequence::Indistinguishable;
3435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003436 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003437 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003438 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3439 return ImplicitConversionSequence::Better;
3440 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3441 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003443 if (SCS1.Second != SCS2.Second) {
3444 if (SCS1.Second == ICK_Identity)
3445 Result = ImplicitConversionSequence::Better;
3446 else if (SCS2.Second == ICK_Identity)
3447 Result = ImplicitConversionSequence::Worse;
3448 else
3449 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003450 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003451 return ImplicitConversionSequence::Indistinguishable;
3452
3453 if (SCS1.Third == SCS2.Third) {
3454 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3455 : ImplicitConversionSequence::Indistinguishable;
3456 }
3457
3458 if (SCS1.Third == ICK_Identity)
3459 return Result == ImplicitConversionSequence::Worse
3460 ? ImplicitConversionSequence::Indistinguishable
3461 : ImplicitConversionSequence::Better;
3462
3463 if (SCS2.Third == ICK_Identity)
3464 return Result == ImplicitConversionSequence::Better
3465 ? ImplicitConversionSequence::Indistinguishable
3466 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003467
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003468 return ImplicitConversionSequence::Indistinguishable;
3469}
3470
Douglas Gregore696ebb2011-01-26 14:52:12 +00003471/// \brief Determine whether one of the given reference bindings is better
3472/// than the other based on what kind of bindings they are.
3473static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3474 const StandardConversionSequence &SCS2) {
3475 // C++0x [over.ics.rank]p3b4:
3476 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3477 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003479 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003481 // reference*.
3482 //
3483 // FIXME: Rvalue references. We're going rogue with the above edits,
3484 // because the semantics in the current C++0x working paper (N3225 at the
3485 // time of this writing) break the standard definition of std::forward
3486 // and std::reference_wrapper when dealing with references to functions.
3487 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003488 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3489 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3490 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003491
Douglas Gregore696ebb2011-01-26 14:52:12 +00003492 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3493 SCS2.IsLvalueReference) ||
3494 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3495 !SCS2.IsLvalueReference);
3496}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003497
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003498/// CompareStandardConversionSequences - Compare two standard
3499/// conversion sequences to determine whether one is better than the
3500/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003501static ImplicitConversionSequence::CompareKind
3502CompareStandardConversionSequences(Sema &S,
3503 const StandardConversionSequence& SCS1,
3504 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003505{
3506 // Standard conversion sequence S1 is a better conversion sequence
3507 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3508
3509 // -- S1 is a proper subsequence of S2 (comparing the conversion
3510 // sequences in the canonical form defined by 13.3.3.1.1,
3511 // excluding any Lvalue Transformation; the identity conversion
3512 // sequence is considered to be a subsequence of any
3513 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003514 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003515 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003516 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003517
3518 // -- the rank of S1 is better than the rank of S2 (by the rules
3519 // defined below), or, if not that,
3520 ImplicitConversionRank Rank1 = SCS1.getRank();
3521 ImplicitConversionRank Rank2 = SCS2.getRank();
3522 if (Rank1 < Rank2)
3523 return ImplicitConversionSequence::Better;
3524 else if (Rank2 < Rank1)
3525 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003526
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003527 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3528 // are indistinguishable unless one of the following rules
3529 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003530
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003531 // A conversion that is not a conversion of a pointer, or
3532 // pointer to member, to bool is better than another conversion
3533 // that is such a conversion.
3534 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3535 return SCS2.isPointerConversionToBool()
3536 ? ImplicitConversionSequence::Better
3537 : ImplicitConversionSequence::Worse;
3538
Douglas Gregor5c407d92008-10-23 00:40:37 +00003539 // C++ [over.ics.rank]p4b2:
3540 //
3541 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003542 // conversion of B* to A* is better than conversion of B* to
3543 // void*, and conversion of A* to void* is better than conversion
3544 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003545 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003546 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003547 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003548 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003549 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3550 // Exactly one of the conversion sequences is a conversion to
3551 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003552 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3553 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003554 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3555 // Neither conversion sequence converts to a void pointer; compare
3556 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003557 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003558 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003559 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003560 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3561 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003562 // Both conversion sequences are conversions to void
3563 // pointers. Compare the source types to determine if there's an
3564 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003565 QualType FromType1 = SCS1.getFromType();
3566 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003567
3568 // Adjust the types we're converting from via the array-to-pointer
3569 // conversion, if we need to.
3570 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003571 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003572 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003573 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003574
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003575 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3576 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003577
John McCall5c32be02010-08-24 20:38:10 +00003578 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003579 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003580 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003581 return ImplicitConversionSequence::Worse;
3582
3583 // Objective-C++: If one interface is more specific than the
3584 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003585 const ObjCObjectPointerType* FromObjCPtr1
3586 = FromType1->getAs<ObjCObjectPointerType>();
3587 const ObjCObjectPointerType* FromObjCPtr2
3588 = FromType2->getAs<ObjCObjectPointerType>();
3589 if (FromObjCPtr1 && FromObjCPtr2) {
3590 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3591 FromObjCPtr2);
3592 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3593 FromObjCPtr1);
3594 if (AssignLeft != AssignRight) {
3595 return AssignLeft? ImplicitConversionSequence::Better
3596 : ImplicitConversionSequence::Worse;
3597 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003598 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003599 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003600
3601 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3602 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003603 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003604 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003605 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003606
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003607 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003608 // Check for a better reference binding based on the kind of bindings.
3609 if (isBetterReferenceBindingKind(SCS1, SCS2))
3610 return ImplicitConversionSequence::Better;
3611 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3612 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Sebastian Redlb28b4072009-03-22 23:49:27 +00003614 // C++ [over.ics.rank]p3b4:
3615 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3616 // which the references refer are the same type except for
3617 // top-level cv-qualifiers, and the type to which the reference
3618 // initialized by S2 refers is more cv-qualified than the type
3619 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003620 QualType T1 = SCS1.getToType(2);
3621 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003622 T1 = S.Context.getCanonicalType(T1);
3623 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003624 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003625 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3626 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003627 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003628 // Objective-C++ ARC: If the references refer to objects with different
3629 // lifetimes, prefer bindings that don't change lifetime.
3630 if (SCS1.ObjCLifetimeConversionBinding !=
3631 SCS2.ObjCLifetimeConversionBinding) {
3632 return SCS1.ObjCLifetimeConversionBinding
3633 ? ImplicitConversionSequence::Worse
3634 : ImplicitConversionSequence::Better;
3635 }
3636
Chandler Carruth8e543b32010-12-12 08:17:55 +00003637 // If the type is an array type, promote the element qualifiers to the
3638 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003639 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003640 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003641 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003642 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003643 if (T2.isMoreQualifiedThan(T1))
3644 return ImplicitConversionSequence::Better;
3645 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003646 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003647 }
3648 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003649
Francois Pichet08d2fa02011-09-18 21:37:37 +00003650 // In Microsoft mode, prefer an integral conversion to a
3651 // floating-to-integral conversion if the integral conversion
3652 // is between types of the same size.
3653 // For example:
3654 // void f(float);
3655 // void f(int);
3656 // int main {
3657 // long a;
3658 // f(a);
3659 // }
3660 // Here, MSVC will call f(int) instead of generating a compile error
3661 // as clang will do in standard mode.
Alp Tokerbfa39342014-01-14 12:51:41 +00003662 if (S.getLangOpts().MSVCCompat && SCS1.Second == ICK_Integral_Conversion &&
3663 SCS2.Second == ICK_Floating_Integral &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003664 S.Context.getTypeSize(SCS1.getFromType()) ==
Alp Tokerbfa39342014-01-14 12:51:41 +00003665 S.Context.getTypeSize(SCS1.getToType(2)))
Francois Pichet08d2fa02011-09-18 21:37:37 +00003666 return ImplicitConversionSequence::Better;
3667
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003668 return ImplicitConversionSequence::Indistinguishable;
3669}
3670
3671/// CompareQualificationConversions - Compares two standard conversion
3672/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003673/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3674ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003675CompareQualificationConversions(Sema &S,
3676 const StandardConversionSequence& SCS1,
3677 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003678 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003679 // -- S1 and S2 differ only in their qualification conversion and
3680 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3681 // cv-qualification signature of type T1 is a proper subset of
3682 // the cv-qualification signature of type T2, and S1 is not the
3683 // deprecated string literal array-to-pointer conversion (4.2).
3684 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3685 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3686 return ImplicitConversionSequence::Indistinguishable;
3687
3688 // FIXME: the example in the standard doesn't use a qualification
3689 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003690 QualType T1 = SCS1.getToType(2);
3691 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003692 T1 = S.Context.getCanonicalType(T1);
3693 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003694 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003695 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3696 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003697
3698 // If the types are the same, we won't learn anything by unwrapped
3699 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003700 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003701 return ImplicitConversionSequence::Indistinguishable;
3702
Chandler Carruth607f38e2009-12-29 07:16:59 +00003703 // If the type is an array type, promote the element qualifiers to the type
3704 // for comparison.
3705 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003706 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003707 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003708 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003709
Mike Stump11289f42009-09-09 15:08:12 +00003710 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003711 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003712
3713 // Objective-C++ ARC:
3714 // Prefer qualification conversions not involving a change in lifetime
3715 // to qualification conversions that do not change lifetime.
3716 if (SCS1.QualificationIncludesObjCLifetime !=
3717 SCS2.QualificationIncludesObjCLifetime) {
3718 Result = SCS1.QualificationIncludesObjCLifetime
3719 ? ImplicitConversionSequence::Worse
3720 : ImplicitConversionSequence::Better;
3721 }
3722
John McCall5c32be02010-08-24 20:38:10 +00003723 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003724 // Within each iteration of the loop, we check the qualifiers to
3725 // determine if this still looks like a qualification
3726 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003727 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003728 // until there are no more pointers or pointers-to-members left
3729 // to unwrap. This essentially mimics what
3730 // IsQualificationConversion does, but here we're checking for a
3731 // strict subset of qualifiers.
3732 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3733 // The qualifiers are the same, so this doesn't tell us anything
3734 // about how the sequences rank.
3735 ;
3736 else if (T2.isMoreQualifiedThan(T1)) {
3737 // T1 has fewer qualifiers, so it could be the better sequence.
3738 if (Result == ImplicitConversionSequence::Worse)
3739 // Neither has qualifiers that are a subset of the other's
3740 // qualifiers.
3741 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003742
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003743 Result = ImplicitConversionSequence::Better;
3744 } else if (T1.isMoreQualifiedThan(T2)) {
3745 // T2 has fewer qualifiers, so it could be the better sequence.
3746 if (Result == ImplicitConversionSequence::Better)
3747 // Neither has qualifiers that are a subset of the other's
3748 // qualifiers.
3749 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003750
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003751 Result = ImplicitConversionSequence::Worse;
3752 } else {
3753 // Qualifiers are disjoint.
3754 return ImplicitConversionSequence::Indistinguishable;
3755 }
3756
3757 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003758 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003759 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003760 }
3761
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003762 // Check that the winning standard conversion sequence isn't using
3763 // the deprecated string literal array to pointer conversion.
3764 switch (Result) {
3765 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003766 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003767 Result = ImplicitConversionSequence::Indistinguishable;
3768 break;
3769
3770 case ImplicitConversionSequence::Indistinguishable:
3771 break;
3772
3773 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003774 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003775 Result = ImplicitConversionSequence::Indistinguishable;
3776 break;
3777 }
3778
3779 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003780}
3781
Douglas Gregor5c407d92008-10-23 00:40:37 +00003782/// CompareDerivedToBaseConversions - Compares two standard conversion
3783/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003784/// various kinds of derived-to-base conversions (C++
3785/// [over.ics.rank]p4b3). As part of these checks, we also look at
3786/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003787ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003788CompareDerivedToBaseConversions(Sema &S,
3789 const StandardConversionSequence& SCS1,
3790 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003791 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003792 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003793 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003794 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003795
3796 // Adjust the types we're converting from via the array-to-pointer
3797 // conversion, if we need to.
3798 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003799 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003800 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003801 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003802
3803 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003804 FromType1 = S.Context.getCanonicalType(FromType1);
3805 ToType1 = S.Context.getCanonicalType(ToType1);
3806 FromType2 = S.Context.getCanonicalType(FromType2);
3807 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003808
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003809 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003810 //
3811 // If class B is derived directly or indirectly from class A and
3812 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003813 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003814 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003815 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003816 SCS2.Second == ICK_Pointer_Conversion &&
3817 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3818 FromType1->isPointerType() && FromType2->isPointerType() &&
3819 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003820 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003821 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003822 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003823 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003824 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003825 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003826 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003827 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003828
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003829 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003830 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003831 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003832 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003833 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003834 return ImplicitConversionSequence::Worse;
3835 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003836
3837 // -- conversion of B* to A* is better than conversion of C* to A*,
3838 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003839 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003840 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003841 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003842 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003843 }
3844 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3845 SCS2.Second == ICK_Pointer_Conversion) {
3846 const ObjCObjectPointerType *FromPtr1
3847 = FromType1->getAs<ObjCObjectPointerType>();
3848 const ObjCObjectPointerType *FromPtr2
3849 = FromType2->getAs<ObjCObjectPointerType>();
3850 const ObjCObjectPointerType *ToPtr1
3851 = ToType1->getAs<ObjCObjectPointerType>();
3852 const ObjCObjectPointerType *ToPtr2
3853 = ToType2->getAs<ObjCObjectPointerType>();
3854
3855 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3856 // Apply the same conversion ranking rules for Objective-C pointer types
3857 // that we do for C++ pointers to class types. However, we employ the
3858 // Objective-C pseudo-subtyping relationship used for assignment of
3859 // Objective-C pointer types.
3860 bool FromAssignLeft
3861 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3862 bool FromAssignRight
3863 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3864 bool ToAssignLeft
3865 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3866 bool ToAssignRight
3867 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3868
3869 // A conversion to an a non-id object pointer type or qualified 'id'
3870 // type is better than a conversion to 'id'.
3871 if (ToPtr1->isObjCIdType() &&
3872 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3873 return ImplicitConversionSequence::Worse;
3874 if (ToPtr2->isObjCIdType() &&
3875 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3876 return ImplicitConversionSequence::Better;
3877
3878 // A conversion to a non-id object pointer type is better than a
3879 // conversion to a qualified 'id' type
3880 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3881 return ImplicitConversionSequence::Worse;
3882 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3883 return ImplicitConversionSequence::Better;
3884
3885 // A conversion to an a non-Class object pointer type or qualified 'Class'
3886 // type is better than a conversion to 'Class'.
3887 if (ToPtr1->isObjCClassType() &&
3888 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3889 return ImplicitConversionSequence::Worse;
3890 if (ToPtr2->isObjCClassType() &&
3891 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3892 return ImplicitConversionSequence::Better;
3893
3894 // A conversion to a non-Class object pointer type is better than a
3895 // conversion to a qualified 'Class' type.
3896 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3897 return ImplicitConversionSequence::Worse;
3898 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3899 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003900
Douglas Gregor058d3de2011-01-31 18:51:41 +00003901 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3902 if (S.Context.hasSameType(FromType1, FromType2) &&
3903 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3904 (ToAssignLeft != ToAssignRight))
3905 return ToAssignLeft? ImplicitConversionSequence::Worse
3906 : ImplicitConversionSequence::Better;
3907
3908 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3909 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3910 (FromAssignLeft != FromAssignRight))
3911 return FromAssignLeft? ImplicitConversionSequence::Better
3912 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003913 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003914 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003915
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003916 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003917 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3918 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3919 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003920 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003921 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003922 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003923 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003925 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003926 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003927 ToType2->getAs<MemberPointerType>();
3928 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3929 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3930 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3931 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3932 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3933 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3934 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3935 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003936 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003937 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003938 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003939 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003940 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003941 return ImplicitConversionSequence::Better;
3942 }
3943 // conversion of B::* to C::* is better than conversion of A::* to C::*
3944 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003945 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003946 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003947 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003948 return ImplicitConversionSequence::Worse;
3949 }
3950 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951
Douglas Gregor5ab11652010-04-17 22:01:05 +00003952 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003953 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003954 // -- binding of an expression of type C to a reference of type
3955 // B& is better than binding an expression of type C to a
3956 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003957 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3958 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3959 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003960 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003961 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003962 return ImplicitConversionSequence::Worse;
3963 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003964
Douglas Gregor2fe98832008-11-03 19:09:14 +00003965 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003966 // -- binding of an expression of type B to a reference of type
3967 // A& is better than binding an expression of type C to a
3968 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003969 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3970 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3971 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003972 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003973 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003974 return ImplicitConversionSequence::Worse;
3975 }
3976 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003977
Douglas Gregor5c407d92008-10-23 00:40:37 +00003978 return ImplicitConversionSequence::Indistinguishable;
3979}
3980
Douglas Gregor45bb4832013-03-26 23:36:30 +00003981/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3982/// C++ class.
3983static bool isTypeValid(QualType T) {
3984 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3985 return !Record->isInvalidDecl();
3986
3987 return true;
3988}
3989
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003990/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3991/// determine whether they are reference-related,
3992/// reference-compatible, reference-compatible with added
3993/// qualification, or incompatible, for use in C++ initialization by
3994/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3995/// type, and the first type (T1) is the pointee type of the reference
3996/// type being initialized.
3997Sema::ReferenceCompareResult
3998Sema::CompareReferenceRelationship(SourceLocation Loc,
3999 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004000 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004001 bool &ObjCConversion,
4002 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004003 assert(!OrigT1->isReferenceType() &&
4004 "T1 must be the pointee type of the reference type");
4005 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
4006
4007 QualType T1 = Context.getCanonicalType(OrigT1);
4008 QualType T2 = Context.getCanonicalType(OrigT2);
4009 Qualifiers T1Quals, T2Quals;
4010 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
4011 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
4012
4013 // C++ [dcl.init.ref]p4:
4014 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
4015 // reference-related to "cv2 T2" if T1 is the same type as T2, or
4016 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004017 DerivedToBase = false;
4018 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004019 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004020 if (UnqualT1 == UnqualT2) {
4021 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004022 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00004023 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
4024 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004025 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004026 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4027 UnqualT2->isObjCObjectOrInterfaceType() &&
4028 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4029 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004030 else
4031 return Ref_Incompatible;
4032
4033 // At this point, we know that T1 and T2 are reference-related (at
4034 // least).
4035
4036 // If the type is an array type, promote the element qualifiers to the type
4037 // for comparison.
4038 if (isa<ArrayType>(T1) && T1Quals)
4039 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4040 if (isa<ArrayType>(T2) && T2Quals)
4041 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4042
4043 // C++ [dcl.init.ref]p4:
4044 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4045 // reference-related to T2 and cv1 is the same cv-qualification
4046 // as, or greater cv-qualification than, cv2. For purposes of
4047 // overload resolution, cases for which cv1 is greater
4048 // cv-qualification than cv2 are identified as
4049 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004050 //
4051 // Note that we also require equivalence of Objective-C GC and address-space
4052 // qualifiers when performing these computations, so that e.g., an int in
4053 // address space 1 is not reference-compatible with an int in address
4054 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004055 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4056 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004057 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4058 ObjCLifetimeConversion = true;
4059
John McCall31168b02011-06-15 23:02:42 +00004060 T1Quals.removeObjCLifetime();
4061 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004062 }
4063
Douglas Gregord517d552011-04-28 17:56:11 +00004064 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004065 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004066 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004067 return Ref_Compatible_With_Added_Qualification;
4068 else
4069 return Ref_Related;
4070}
4071
Douglas Gregor836a7e82010-08-11 02:15:33 +00004072/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004073/// with DeclType. Return true if something definite is found.
4074static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004075FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4076 QualType DeclType, SourceLocation DeclLoc,
4077 Expr *Init, QualType T2, bool AllowRvalues,
4078 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004079 assert(T2->isRecordType() && "Can only find conversions of record types.");
4080 CXXRecordDecl *T2RecordDecl
4081 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4082
4083 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004084 std::pair<CXXRecordDecl::conversion_iterator,
4085 CXXRecordDecl::conversion_iterator>
4086 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4087 for (CXXRecordDecl::conversion_iterator
4088 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004089 NamedDecl *D = *I;
4090 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4091 if (isa<UsingShadowDecl>(D))
4092 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4093
4094 FunctionTemplateDecl *ConvTemplate
4095 = dyn_cast<FunctionTemplateDecl>(D);
4096 CXXConversionDecl *Conv;
4097 if (ConvTemplate)
4098 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4099 else
4100 Conv = cast<CXXConversionDecl>(D);
4101
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004103 // explicit conversions, skip it.
4104 if (!AllowExplicit && Conv->isExplicit())
4105 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106
Douglas Gregor836a7e82010-08-11 02:15:33 +00004107 if (AllowRvalues) {
4108 bool DerivedToBase = false;
4109 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004110 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004111
4112 // If we are initializing an rvalue reference, don't permit conversion
4113 // functions that return lvalues.
4114 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4115 const ReferenceType *RefType
4116 = Conv->getConversionType()->getAs<LValueReferenceType>();
4117 if (RefType && !RefType->getPointeeType()->isFunctionType())
4118 continue;
4119 }
4120
Douglas Gregor836a7e82010-08-11 02:15:33 +00004121 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004122 S.CompareReferenceRelationship(
4123 DeclLoc,
4124 Conv->getConversionType().getNonReferenceType()
4125 .getUnqualifiedType(),
4126 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004127 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004128 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004129 continue;
4130 } else {
4131 // If the conversion function doesn't return a reference type,
4132 // it can't be considered for this conversion. An rvalue reference
4133 // is only acceptable if its referencee is a function type.
4134
4135 const ReferenceType *RefType =
4136 Conv->getConversionType()->getAs<ReferenceType>();
4137 if (!RefType ||
4138 (!RefType->isLValueReferenceType() &&
4139 !RefType->getPointeeType()->isFunctionType()))
4140 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004141 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142
Douglas Gregor836a7e82010-08-11 02:15:33 +00004143 if (ConvTemplate)
4144 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004145 Init, DeclType, CandidateSet,
4146 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004147 else
4148 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004149 DeclType, CandidateSet,
4150 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004151 }
4152
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004153 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4154
Sebastian Redld92badf2010-06-30 18:13:39 +00004155 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004156 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004157 case OR_Success:
4158 // C++ [over.ics.ref]p1:
4159 //
4160 // [...] If the parameter binds directly to the result of
4161 // applying a conversion function to the argument
4162 // expression, the implicit conversion sequence is a
4163 // user-defined conversion sequence (13.3.3.1.2), with the
4164 // second standard conversion sequence either an identity
4165 // conversion or, if the conversion function returns an
4166 // entity of a type that is a derived class of the parameter
4167 // type, a derived-to-base Conversion.
4168 if (!Best->FinalConversion.DirectBinding)
4169 return false;
4170
4171 ICS.setUserDefined();
4172 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4173 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004174 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004175 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004176 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004177 ICS.UserDefined.EllipsisConversion = false;
4178 assert(ICS.UserDefined.After.ReferenceBinding &&
4179 ICS.UserDefined.After.DirectBinding &&
4180 "Expected a direct reference binding!");
4181 return true;
4182
4183 case OR_Ambiguous:
4184 ICS.setAmbiguous();
4185 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4186 Cand != CandidateSet.end(); ++Cand)
4187 if (Cand->Viable)
4188 ICS.Ambiguous.addConversion(Cand->Function);
4189 return true;
4190
4191 case OR_No_Viable_Function:
4192 case OR_Deleted:
4193 // There was no suitable conversion, or we found a deleted
4194 // conversion; continue with other checks.
4195 return false;
4196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004197
David Blaikie8a40f702012-01-17 06:56:22 +00004198 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004199}
4200
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004201/// \brief Compute an implicit conversion sequence for reference
4202/// initialization.
4203static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004204TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004205 SourceLocation DeclLoc,
4206 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004207 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004208 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4209
4210 // Most paths end in a failed conversion.
4211 ImplicitConversionSequence ICS;
4212 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4213
4214 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4215 QualType T2 = Init->getType();
4216
4217 // If the initializer is the address of an overloaded function, try
4218 // to resolve the overloaded function. If all goes well, T2 is the
4219 // type of the resulting function.
4220 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4221 DeclAccessPair Found;
4222 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4223 false, Found))
4224 T2 = Fn->getType();
4225 }
4226
4227 // Compute some basic properties of the types and the initializer.
4228 bool isRValRef = DeclType->isRValueReferenceType();
4229 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004230 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004231 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004232 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004233 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004234 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004235 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004236
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004237
Sebastian Redld92badf2010-06-30 18:13:39 +00004238 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004239 // A reference to type "cv1 T1" is initialized by an expression
4240 // of type "cv2 T2" as follows:
4241
Sebastian Redld92badf2010-06-30 18:13:39 +00004242 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004243 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004244 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4245 // reference-compatible with "cv2 T2," or
4246 //
4247 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4248 if (InitCategory.isLValue() &&
4249 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004250 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004251 // When a parameter of reference type binds directly (8.5.3)
4252 // to an argument expression, the implicit conversion sequence
4253 // is the identity conversion, unless the argument expression
4254 // has a type that is a derived class of the parameter type,
4255 // in which case the implicit conversion sequence is a
4256 // derived-to-base Conversion (13.3.3.1).
4257 ICS.setStandard();
4258 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004259 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4260 : ObjCConversion? ICK_Compatible_Conversion
4261 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004262 ICS.Standard.Third = ICK_Identity;
4263 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4264 ICS.Standard.setToType(0, T2);
4265 ICS.Standard.setToType(1, T1);
4266 ICS.Standard.setToType(2, T1);
4267 ICS.Standard.ReferenceBinding = true;
4268 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004269 ICS.Standard.IsLvalueReference = !isRValRef;
4270 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4271 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004272 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004273 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004274 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004275 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004276
Sebastian Redld92badf2010-06-30 18:13:39 +00004277 // Nothing more to do: the inaccessibility/ambiguity check for
4278 // derived-to-base conversions is suppressed when we're
4279 // computing the implicit conversion sequence (C++
4280 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004281 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004282 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004283
Sebastian Redld92badf2010-06-30 18:13:39 +00004284 // -- has a class type (i.e., T2 is a class type), where T1 is
4285 // not reference-related to T2, and can be implicitly
4286 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4287 // is reference-compatible with "cv3 T3" 92) (this
4288 // conversion is selected by enumerating the applicable
4289 // conversion functions (13.3.1.6) and choosing the best
4290 // one through overload resolution (13.3)),
4291 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004293 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004294 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4295 Init, T2, /*AllowRvalues=*/false,
4296 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004297 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004298 }
4299 }
4300
Sebastian Redld92badf2010-06-30 18:13:39 +00004301 // -- Otherwise, the reference shall be an lvalue reference to a
4302 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004303 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004305 // We actually handle one oddity of C++ [over.ics.ref] at this
4306 // point, which is that, due to p2 (which short-circuits reference
4307 // binding by only attempting a simple conversion for non-direct
4308 // bindings) and p3's strange wording, we allow a const volatile
4309 // reference to bind to an rvalue. Hence the check for the presence
4310 // of "const" rather than checking for "const" being the only
4311 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004312 // This is also the point where rvalue references and lvalue inits no longer
4313 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004314 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004315 return ICS;
4316
Douglas Gregorf143cd52011-01-24 16:14:37 +00004317 // -- If the initializer expression
4318 //
4319 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004320 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004321 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4322 (InitCategory.isXValue() ||
4323 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4324 (InitCategory.isLValue() && T2->isFunctionType()))) {
4325 ICS.setStandard();
4326 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004328 : ObjCConversion? ICK_Compatible_Conversion
4329 : ICK_Identity;
4330 ICS.Standard.Third = ICK_Identity;
4331 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4332 ICS.Standard.setToType(0, T2);
4333 ICS.Standard.setToType(1, T1);
4334 ICS.Standard.setToType(2, T1);
4335 ICS.Standard.ReferenceBinding = true;
4336 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4337 // binding unless we're binding to a class prvalue.
4338 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4339 // allow the use of rvalue references in C++98/03 for the benefit of
4340 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004341 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004342 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004343 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004344 ICS.Standard.IsLvalueReference = !isRValRef;
4345 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004346 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004347 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004348 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004349 ICS.Standard.CopyConstructor = 0;
Ismail Pazarbasi1121de32014-01-17 21:08:52 +00004350 ICS.Standard.DeprecatedStringLiteralToCharPtr = false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004351 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004352 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004353
Douglas Gregorf143cd52011-01-24 16:14:37 +00004354 // -- has a class type (i.e., T2 is a class type), where T1 is not
4355 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356 // an xvalue, class prvalue, or function lvalue of type
4357 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004358 // "cv3 T3",
4359 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004361 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004362 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004363 // class subobject).
4364 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004366 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4367 Init, T2, /*AllowRvalues=*/true,
4368 AllowExplicit)) {
4369 // In the second case, if the reference is an rvalue reference
4370 // and the second standard conversion sequence of the
4371 // user-defined conversion sequence includes an lvalue-to-rvalue
4372 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004373 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004374 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4375 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4376
Douglas Gregor95273c32011-01-21 16:36:05 +00004377 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004379
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004380 // -- Otherwise, a temporary of type "cv1 T1" is created and
4381 // initialized from the initializer expression using the
4382 // rules for a non-reference copy initialization (8.5). The
4383 // reference is then bound to the temporary. If T1 is
4384 // reference-related to T2, cv1 must be the same
4385 // cv-qualification as, or greater cv-qualification than,
4386 // cv2; otherwise, the program is ill-formed.
4387 if (RefRelationship == Sema::Ref_Related) {
4388 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4389 // we would be reference-compatible or reference-compatible with
4390 // added qualification. But that wasn't the case, so the reference
4391 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004392 //
4393 // Note that we only want to check address spaces and cvr-qualifiers here.
4394 // ObjC GC and lifetime qualifiers aren't important.
4395 Qualifiers T1Quals = T1.getQualifiers();
4396 Qualifiers T2Quals = T2.getQualifiers();
4397 T1Quals.removeObjCGCAttr();
4398 T1Quals.removeObjCLifetime();
4399 T2Quals.removeObjCGCAttr();
4400 T2Quals.removeObjCLifetime();
4401 if (!T1Quals.compatiblyIncludes(T2Quals))
4402 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004403 }
4404
4405 // If at least one of the types is a class type, the types are not
4406 // related, and we aren't allowed any user conversions, the
4407 // reference binding fails. This case is important for breaking
4408 // recursion, since TryImplicitConversion below will attempt to
4409 // create a temporary through the use of a copy constructor.
4410 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4411 (T1->isRecordType() || T2->isRecordType()))
4412 return ICS;
4413
Douglas Gregorcba72b12011-01-21 05:18:22 +00004414 // If T1 is reference-related to T2 and the reference is an rvalue
4415 // reference, the initializer expression shall not be an lvalue.
4416 if (RefRelationship >= Sema::Ref_Related &&
4417 isRValRef && Init->Classify(S.Context).isLValue())
4418 return ICS;
4419
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004420 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004421 // When a parameter of reference type is not bound directly to
4422 // an argument expression, the conversion sequence is the one
4423 // required to convert the argument expression to the
4424 // underlying type of the reference according to
4425 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4426 // to copy-initializing a temporary of the underlying type with
4427 // the argument expression. Any difference in top-level
4428 // cv-qualification is subsumed by the initialization itself
4429 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004430 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4431 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004432 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004433 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004434 /*AllowObjCWritebackConversion=*/false,
4435 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004436
4437 // Of course, that's still a reference binding.
4438 if (ICS.isStandard()) {
4439 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004440 ICS.Standard.IsLvalueReference = !isRValRef;
4441 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4442 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004443 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004444 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004445 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004446 // Don't allow rvalue references to bind to lvalues.
4447 if (DeclType->isRValueReferenceType()) {
4448 if (const ReferenceType *RefType
4449 = ICS.UserDefined.ConversionFunction->getResultType()
4450 ->getAs<LValueReferenceType>()) {
4451 if (!RefType->getPointeeType()->isFunctionType()) {
4452 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4453 DeclType);
4454 return ICS;
4455 }
4456 }
4457 }
4458
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004459 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004460 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4461 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4462 ICS.UserDefined.After.BindsToRvalue = true;
4463 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4464 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004465 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004466
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004467 return ICS;
4468}
4469
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004470static ImplicitConversionSequence
4471TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4472 bool SuppressUserConversions,
4473 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004474 bool AllowObjCWritebackConversion,
4475 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004476
4477/// TryListConversion - Try to copy-initialize a value of type ToType from the
4478/// initializer list From.
4479static ImplicitConversionSequence
4480TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4481 bool SuppressUserConversions,
4482 bool InOverloadResolution,
4483 bool AllowObjCWritebackConversion) {
4484 // C++11 [over.ics.list]p1:
4485 // When an argument is an initializer list, it is not an expression and
4486 // special rules apply for converting it to a parameter type.
4487
4488 ImplicitConversionSequence Result;
4489 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4490
Sebastian Redl09edce02012-01-23 22:09:39 +00004491 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004492 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004493 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004494 return Result;
4495
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004496 // C++11 [over.ics.list]p2:
4497 // If the parameter type is std::initializer_list<X> or "array of X" and
4498 // all the elements can be implicitly converted to X, the implicit
4499 // conversion sequence is the worst conversion necessary to convert an
4500 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004501 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004502 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004503 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004504 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004505 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004506 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004507 if (!X.isNull()) {
4508 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4509 Expr *Init = From->getInit(i);
4510 ImplicitConversionSequence ICS =
4511 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4512 InOverloadResolution,
4513 AllowObjCWritebackConversion);
4514 // If a single element isn't convertible, fail.
4515 if (ICS.isBad()) {
4516 Result = ICS;
4517 break;
4518 }
4519 // Otherwise, look for the worst conversion.
4520 if (Result.isBad() ||
4521 CompareImplicitConversionSequences(S, ICS, Result) ==
4522 ImplicitConversionSequence::Worse)
4523 Result = ICS;
4524 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004525
4526 // For an empty list, we won't have computed any conversion sequence.
4527 // Introduce the identity conversion sequence.
4528 if (From->getNumInits() == 0) {
4529 Result.setStandard();
4530 Result.Standard.setAsIdentityConversion();
4531 Result.Standard.setFromType(ToType);
4532 Result.Standard.setAllToTypes(ToType);
4533 }
4534
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004535 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004536 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004537 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004538
4539 // C++11 [over.ics.list]p3:
4540 // Otherwise, if the parameter is a non-aggregate class X and overload
4541 // resolution chooses a single best constructor [...] the implicit
4542 // conversion sequence is a user-defined conversion sequence. If multiple
4543 // constructors are viable but none is better than the others, the
4544 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004545 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4546 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004547 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4548 /*AllowExplicit=*/false,
4549 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004550 AllowObjCWritebackConversion,
4551 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004552 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004553
4554 // C++11 [over.ics.list]p4:
4555 // Otherwise, if the parameter has an aggregate type which can be
4556 // initialized from the initializer list [...] the implicit conversion
4557 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004558 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004559 // Type is an aggregate, argument is an init list. At this point it comes
4560 // down to checking whether the initialization works.
4561 // FIXME: Find out whether this parameter is consumed or not.
4562 InitializedEntity Entity =
4563 InitializedEntity::InitializeParameter(S.Context, ToType,
4564 /*Consumed=*/false);
4565 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4566 Result.setUserDefined();
4567 Result.UserDefined.Before.setAsIdentityConversion();
4568 // Initializer lists don't have a type.
4569 Result.UserDefined.Before.setFromType(QualType());
4570 Result.UserDefined.Before.setAllToTypes(QualType());
4571
4572 Result.UserDefined.After.setAsIdentityConversion();
4573 Result.UserDefined.After.setFromType(ToType);
4574 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004575 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004576 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004577 return Result;
4578 }
4579
4580 // C++11 [over.ics.list]p5:
4581 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004582 if (ToType->isReferenceType()) {
4583 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4584 // mention initializer lists in any way. So we go by what list-
4585 // initialization would do and try to extrapolate from that.
4586
4587 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4588
4589 // If the initializer list has a single element that is reference-related
4590 // to the parameter type, we initialize the reference from that.
4591 if (From->getNumInits() == 1) {
4592 Expr *Init = From->getInit(0);
4593
4594 QualType T2 = Init->getType();
4595
4596 // If the initializer is the address of an overloaded function, try
4597 // to resolve the overloaded function. If all goes well, T2 is the
4598 // type of the resulting function.
4599 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4600 DeclAccessPair Found;
4601 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4602 Init, ToType, false, Found))
4603 T2 = Fn->getType();
4604 }
4605
4606 // Compute some basic properties of the types and the initializer.
4607 bool dummy1 = false;
4608 bool dummy2 = false;
4609 bool dummy3 = false;
4610 Sema::ReferenceCompareResult RefRelationship
4611 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4612 dummy2, dummy3);
4613
Richard Smith4d2bbd72013-09-06 01:22:42 +00004614 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004615 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4616 SuppressUserConversions,
4617 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004618 }
Sebastian Redldf888642011-12-03 14:54:30 +00004619 }
4620
4621 // Otherwise, we bind the reference to a temporary created from the
4622 // initializer list.
4623 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4624 InOverloadResolution,
4625 AllowObjCWritebackConversion);
4626 if (Result.isFailure())
4627 return Result;
4628 assert(!Result.isEllipsis() &&
4629 "Sub-initialization cannot result in ellipsis conversion.");
4630
4631 // Can we even bind to a temporary?
4632 if (ToType->isRValueReferenceType() ||
4633 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4634 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4635 Result.UserDefined.After;
4636 SCS.ReferenceBinding = true;
4637 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4638 SCS.BindsToRvalue = true;
4639 SCS.BindsToFunctionLvalue = false;
4640 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4641 SCS.ObjCLifetimeConversionBinding = false;
4642 } else
4643 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4644 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004645 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004646 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004647
4648 // C++11 [over.ics.list]p6:
4649 // Otherwise, if the parameter type is not a class:
4650 if (!ToType->isRecordType()) {
4651 // - if the initializer list has one element, the implicit conversion
4652 // sequence is the one required to convert the element to the
4653 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004654 unsigned NumInits = From->getNumInits();
4655 if (NumInits == 1)
4656 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4657 SuppressUserConversions,
4658 InOverloadResolution,
4659 AllowObjCWritebackConversion);
4660 // - if the initializer list has no elements, the implicit conversion
4661 // sequence is the identity conversion.
4662 else if (NumInits == 0) {
4663 Result.setStandard();
4664 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004665 Result.Standard.setFromType(ToType);
4666 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004667 }
4668 return Result;
4669 }
4670
4671 // C++11 [over.ics.list]p7:
4672 // In all cases other than those enumerated above, no conversion is possible
4673 return Result;
4674}
4675
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004676/// TryCopyInitialization - Try to copy-initialize a value of type
4677/// ToType from the expression From. Return the implicit conversion
4678/// sequence required to pass this argument, which may be a bad
4679/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004680/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004681/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004682static ImplicitConversionSequence
4683TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004684 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004685 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004686 bool AllowObjCWritebackConversion,
4687 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004688 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4689 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4690 InOverloadResolution,AllowObjCWritebackConversion);
4691
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004692 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004693 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004694 /*FIXME:*/From->getLocStart(),
4695 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004696 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004697
John McCall5c32be02010-08-24 20:38:10 +00004698 return TryImplicitConversion(S, From, ToType,
4699 SuppressUserConversions,
4700 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004701 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004702 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004703 AllowObjCWritebackConversion,
4704 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004705}
4706
Anna Zaks1b068122011-07-28 19:46:48 +00004707static bool TryCopyInitialization(const CanQualType FromQTy,
4708 const CanQualType ToQTy,
4709 Sema &S,
4710 SourceLocation Loc,
4711 ExprValueKind FromVK) {
4712 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4713 ImplicitConversionSequence ICS =
4714 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4715
4716 return !ICS.isBad();
4717}
4718
Douglas Gregor436424c2008-11-18 23:14:02 +00004719/// TryObjectArgumentInitialization - Try to initialize the object
4720/// parameter of the given member function (@c Method) from the
4721/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004722static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004723TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004724 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004725 CXXMethodDecl *Method,
4726 CXXRecordDecl *ActingContext) {
4727 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004728 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4729 // const volatile object.
4730 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4731 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004732 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004733
4734 // Set up the conversion sequence as a "bad" conversion, to allow us
4735 // to exit early.
4736 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004737
4738 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004739 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004740 FromType = PT->getPointeeType();
4741
Douglas Gregor02824322011-01-26 19:30:28 +00004742 // When we had a pointer, it's implicitly dereferenced, so we
4743 // better have an lvalue.
4744 assert(FromClassification.isLValue());
4745 }
4746
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004747 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004748
Douglas Gregor02824322011-01-26 19:30:28 +00004749 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004751 // parameter is
4752 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004753 // - "lvalue reference to cv X" for functions declared without a
4754 // ref-qualifier or with the & ref-qualifier
4755 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004756 // ref-qualifier
4757 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004758 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004759 // cv-qualification on the member function declaration.
4760 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004762 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004763 // (C++ [over.match.funcs]p5). We perform a simplified version of
4764 // reference binding here, that allows class rvalues to bind to
4765 // non-constant references.
4766
Douglas Gregor02824322011-01-26 19:30:28 +00004767 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004768 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004769 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004770 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004771 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004772 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004773 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004774 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004775 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004776
4777 // Check that we have either the same type or a derived type. It
4778 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004779 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004780 ImplicitConversionKind SecondKind;
4781 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4782 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004783 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004784 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004785 else {
John McCall65eb8792010-02-25 01:37:24 +00004786 ICS.setBad(BadConversionSequence::unrelated_class,
4787 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004788 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004789 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004790
Douglas Gregor02824322011-01-26 19:30:28 +00004791 // Check the ref-qualifier.
4792 switch (Method->getRefQualifier()) {
4793 case RQ_None:
4794 // Do nothing; we don't care about lvalueness or rvalueness.
4795 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004796
Douglas Gregor02824322011-01-26 19:30:28 +00004797 case RQ_LValue:
4798 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4799 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004800 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004801 ImplicitParamType);
4802 return ICS;
4803 }
4804 break;
4805
4806 case RQ_RValue:
4807 if (!FromClassification.isRValue()) {
4808 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004809 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004810 ImplicitParamType);
4811 return ICS;
4812 }
4813 break;
4814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004815
Douglas Gregor436424c2008-11-18 23:14:02 +00004816 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004817 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004818 ICS.Standard.setAsIdentityConversion();
4819 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004820 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004821 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004822 ICS.Standard.ReferenceBinding = true;
4823 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004824 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004825 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004826 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4827 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4828 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004829 return ICS;
4830}
4831
4832/// PerformObjectArgumentInitialization - Perform initialization of
4833/// the implicit object parameter for the given Method with the given
4834/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004835ExprResult
4836Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004837 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004838 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004839 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004840 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004841 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004842 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004843
Douglas Gregor02824322011-01-26 19:30:28 +00004844 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004845 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004846 FromRecordType = PT->getPointeeType();
4847 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004848 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004849 } else {
4850 FromRecordType = From->getType();
4851 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004852 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004853 }
4854
John McCall6e9f8f62009-12-03 04:06:58 +00004855 // Note that we always use the true parent context when performing
4856 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004857 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004858 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4859 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004860 if (ICS.isBad()) {
4861 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4862 Qualifiers FromQs = FromRecordType.getQualifiers();
4863 Qualifiers ToQs = DestType.getQualifiers();
4864 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4865 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004866 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004867 diag::err_member_function_call_bad_cvr)
4868 << Method->getDeclName() << FromRecordType << (CVR - 1)
4869 << From->getSourceRange();
4870 Diag(Method->getLocation(), diag::note_previous_decl)
4871 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004872 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004873 }
4874 }
4875
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004876 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004877 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004878 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004879 }
Mike Stump11289f42009-09-09 15:08:12 +00004880
John Wiegley01296292011-04-08 18:41:53 +00004881 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4882 ExprResult FromRes =
4883 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4884 if (FromRes.isInvalid())
4885 return ExprError();
4886 From = FromRes.take();
4887 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004888
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004889 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004890 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004891 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004892 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004893}
4894
Douglas Gregor5fb53972009-01-14 15:45:31 +00004895/// TryContextuallyConvertToBool - Attempt to contextually convert the
4896/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004897static ImplicitConversionSequence
4898TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004899 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004900 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004901 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004902 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004903 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004904 /*AllowObjCWritebackConversion=*/false,
4905 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004906}
4907
4908/// PerformContextuallyConvertToBool - Perform a contextual conversion
4909/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004910ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004911 if (checkPlaceholderForOverload(*this, From))
4912 return ExprError();
4913
John McCall5c32be02010-08-24 20:38:10 +00004914 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004915 if (!ICS.isBad())
4916 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004917
Fariborz Jahanian76197412009-11-18 18:26:29 +00004918 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004919 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004920 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004921 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004922 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004923}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004924
Richard Smithf8379a02012-01-18 23:55:52 +00004925/// Check that the specified conversion is permitted in a converted constant
4926/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4927/// is acceptable.
4928static bool CheckConvertedConstantConversions(Sema &S,
4929 StandardConversionSequence &SCS) {
4930 // Since we know that the target type is an integral or unscoped enumeration
4931 // type, most conversion kinds are impossible. All possible First and Third
4932 // conversions are fine.
4933 switch (SCS.Second) {
4934 case ICK_Identity:
4935 case ICK_Integral_Promotion:
4936 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004937 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004938 return true;
4939
4940 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004941 // Conversion from an integral or unscoped enumeration type to bool is
4942 // classified as ICK_Boolean_Conversion, but it's also an integral
4943 // conversion, so it's permitted in a converted constant expression.
4944 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4945 SCS.getToType(2)->isBooleanType();
4946
Richard Smithf8379a02012-01-18 23:55:52 +00004947 case ICK_Floating_Integral:
4948 case ICK_Complex_Real:
4949 return false;
4950
4951 case ICK_Lvalue_To_Rvalue:
4952 case ICK_Array_To_Pointer:
4953 case ICK_Function_To_Pointer:
4954 case ICK_NoReturn_Adjustment:
4955 case ICK_Qualification:
4956 case ICK_Compatible_Conversion:
4957 case ICK_Vector_Conversion:
4958 case ICK_Vector_Splat:
4959 case ICK_Derived_To_Base:
4960 case ICK_Pointer_Conversion:
4961 case ICK_Pointer_Member:
4962 case ICK_Block_Pointer_Conversion:
4963 case ICK_Writeback_Conversion:
4964 case ICK_Floating_Promotion:
4965 case ICK_Complex_Promotion:
4966 case ICK_Complex_Conversion:
4967 case ICK_Floating_Conversion:
4968 case ICK_TransparentUnionConversion:
4969 llvm_unreachable("unexpected second conversion kind");
4970
4971 case ICK_Num_Conversion_Kinds:
4972 break;
4973 }
4974
4975 llvm_unreachable("unknown conversion kind");
4976}
4977
4978/// CheckConvertedConstantExpression - Check that the expression From is a
4979/// converted constant expression of type T, perform the conversion and produce
4980/// the converted expression, per C++11 [expr.const]p3.
4981ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4982 llvm::APSInt &Value,
4983 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004984 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004985 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4986
4987 if (checkPlaceholderForOverload(*this, From))
4988 return ExprError();
4989
4990 // C++11 [expr.const]p3 with proposed wording fixes:
4991 // A converted constant expression of type T is a core constant expression,
4992 // implicitly converted to a prvalue of type T, where the converted
4993 // expression is a literal constant expression and the implicit conversion
4994 // sequence contains only user-defined conversions, lvalue-to-rvalue
4995 // conversions, integral promotions, and integral conversions other than
4996 // narrowing conversions.
4997 ImplicitConversionSequence ICS =
4998 TryImplicitConversion(From, T,
4999 /*SuppressUserConversions=*/false,
5000 /*AllowExplicit=*/false,
5001 /*InOverloadResolution=*/false,
5002 /*CStyle=*/false,
5003 /*AllowObjcWritebackConversion=*/false);
5004 StandardConversionSequence *SCS = 0;
5005 switch (ICS.getKind()) {
5006 case ImplicitConversionSequence::StandardConversion:
5007 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005008 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005009 diag::err_typecheck_converted_constant_expression_disallowed)
5010 << From->getType() << From->getSourceRange() << T;
5011 SCS = &ICS.Standard;
5012 break;
5013 case ImplicitConversionSequence::UserDefinedConversion:
5014 // We are converting from class type to an integral or enumeration type, so
5015 // the Before sequence must be trivial.
5016 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005017 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005018 diag::err_typecheck_converted_constant_expression_disallowed)
5019 << From->getType() << From->getSourceRange() << T;
5020 SCS = &ICS.UserDefined.After;
5021 break;
5022 case ImplicitConversionSequence::AmbiguousConversion:
5023 case ImplicitConversionSequence::BadConversion:
5024 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005025 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00005026 diag::err_typecheck_converted_constant_expression)
5027 << From->getType() << From->getSourceRange() << T;
5028 return ExprError();
5029
5030 case ImplicitConversionSequence::EllipsisConversion:
5031 llvm_unreachable("ellipsis conversion in converted constant expression");
5032 }
5033
5034 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5035 if (Result.isInvalid())
5036 return Result;
5037
5038 // Check for a narrowing implicit conversion.
5039 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005040 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005041 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5042 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005043 case NK_Variable_Narrowing:
5044 // Implicit conversion to a narrower type, and the value is not a constant
5045 // expression. We'll diagnose this in a moment.
5046 case NK_Not_Narrowing:
5047 break;
5048
5049 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005050 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005051 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005052 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005053 break;
5054
5055 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005056 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005057 << CCE << /*Constant*/0 << From->getType() << T;
5058 break;
5059 }
5060
5061 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005062 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005063 Expr::EvalResult Eval;
5064 Eval.Diag = &Notes;
5065
Douglas Gregorebe2db72013-04-08 23:24:07 +00005066 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005067 // The expression can't be folded, so we can't keep it at this position in
5068 // the AST.
5069 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005070 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005071 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005072
5073 if (Notes.empty()) {
5074 // It's a constant expression.
5075 return Result;
5076 }
Richard Smithf8379a02012-01-18 23:55:52 +00005077 }
5078
5079 // It's not a constant expression. Produce an appropriate diagnostic.
5080 if (Notes.size() == 1 &&
5081 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5082 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5083 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005084 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005085 << CCE << From->getSourceRange();
5086 for (unsigned I = 0; I < Notes.size(); ++I)
5087 Diag(Notes[I].first, Notes[I].second);
5088 }
Richard Smith911e1422012-01-30 22:27:01 +00005089 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005090}
5091
John McCallfec112d2011-09-09 06:11:02 +00005092/// dropPointerConversions - If the given standard conversion sequence
5093/// involves any pointer conversions, remove them. This may change
5094/// the result type of the conversion sequence.
5095static void dropPointerConversion(StandardConversionSequence &SCS) {
5096 if (SCS.Second == ICK_Pointer_Conversion) {
5097 SCS.Second = ICK_Identity;
5098 SCS.Third = ICK_Identity;
5099 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5100 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005101}
John McCall5c32be02010-08-24 20:38:10 +00005102
John McCallfec112d2011-09-09 06:11:02 +00005103/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5104/// convert the expression From to an Objective-C pointer type.
5105static ImplicitConversionSequence
5106TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5107 // Do an implicit conversion to 'id'.
5108 QualType Ty = S.Context.getObjCIdType();
5109 ImplicitConversionSequence ICS
5110 = TryImplicitConversion(S, From, Ty,
5111 // FIXME: Are these flags correct?
5112 /*SuppressUserConversions=*/false,
5113 /*AllowExplicit=*/true,
5114 /*InOverloadResolution=*/false,
5115 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005116 /*AllowObjCWritebackConversion=*/false,
5117 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005118
5119 // Strip off any final conversions to 'id'.
5120 switch (ICS.getKind()) {
5121 case ImplicitConversionSequence::BadConversion:
5122 case ImplicitConversionSequence::AmbiguousConversion:
5123 case ImplicitConversionSequence::EllipsisConversion:
5124 break;
5125
5126 case ImplicitConversionSequence::UserDefinedConversion:
5127 dropPointerConversion(ICS.UserDefined.After);
5128 break;
5129
5130 case ImplicitConversionSequence::StandardConversion:
5131 dropPointerConversion(ICS.Standard);
5132 break;
5133 }
5134
5135 return ICS;
5136}
5137
5138/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5139/// conversion of the expression From to an Objective-C pointer type.
5140ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005141 if (checkPlaceholderForOverload(*this, From))
5142 return ExprError();
5143
John McCall8b07ec22010-05-15 11:32:37 +00005144 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005145 ImplicitConversionSequence ICS =
5146 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005147 if (!ICS.isBad())
5148 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005149 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005150}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005151
Richard Smith8dd34252012-02-04 07:07:42 +00005152/// Determine whether the provided type is an integral type, or an enumeration
5153/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005154bool Sema::ICEConvertDiagnoser::match(QualType T) {
5155 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5156 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005157}
5158
Larisse Voufo236bec22013-06-10 06:50:24 +00005159static ExprResult
5160diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5161 Sema::ContextualImplicitConverter &Converter,
5162 QualType T, UnresolvedSetImpl &ViableConversions) {
5163
5164 if (Converter.Suppress)
5165 return ExprError();
5166
5167 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5168 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5169 CXXConversionDecl *Conv =
5170 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5171 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5172 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5173 }
5174 return SemaRef.Owned(From);
5175}
5176
5177static bool
5178diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5179 Sema::ContextualImplicitConverter &Converter,
5180 QualType T, bool HadMultipleCandidates,
5181 UnresolvedSetImpl &ExplicitConversions) {
5182 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5183 DeclAccessPair Found = ExplicitConversions[0];
5184 CXXConversionDecl *Conversion =
5185 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5186
5187 // The user probably meant to invoke the given explicit
5188 // conversion; use it.
5189 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5190 std::string TypeStr;
5191 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5192
5193 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5194 << FixItHint::CreateInsertion(From->getLocStart(),
5195 "static_cast<" + TypeStr + ">(")
5196 << FixItHint::CreateInsertion(
5197 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5198 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5199
5200 // If we aren't in a SFINAE context, build a call to the
5201 // explicit conversion function.
5202 if (SemaRef.isSFINAEContext())
5203 return true;
5204
5205 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5206 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5207 HadMultipleCandidates);
5208 if (Result.isInvalid())
5209 return true;
5210 // Record usage of conversion in an implicit cast.
5211 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5212 CK_UserDefinedConversion, Result.get(), 0,
5213 Result.get()->getValueKind());
5214 }
5215 return false;
5216}
5217
5218static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5219 Sema::ContextualImplicitConverter &Converter,
5220 QualType T, bool HadMultipleCandidates,
5221 DeclAccessPair &Found) {
5222 CXXConversionDecl *Conversion =
5223 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5224 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5225
5226 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5227 if (!Converter.SuppressConversion) {
5228 if (SemaRef.isSFINAEContext())
5229 return true;
5230
5231 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5232 << From->getSourceRange();
5233 }
5234
5235 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5236 HadMultipleCandidates);
5237 if (Result.isInvalid())
5238 return true;
5239 // Record usage of conversion in an implicit cast.
5240 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5241 CK_UserDefinedConversion, Result.get(), 0,
5242 Result.get()->getValueKind());
5243 return false;
5244}
5245
5246static ExprResult finishContextualImplicitConversion(
5247 Sema &SemaRef, SourceLocation Loc, Expr *From,
5248 Sema::ContextualImplicitConverter &Converter) {
5249 if (!Converter.match(From->getType()) && !Converter.Suppress)
5250 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5251 << From->getSourceRange();
5252
5253 return SemaRef.DefaultLvalueConversion(From);
5254}
5255
5256static void
5257collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5258 UnresolvedSetImpl &ViableConversions,
5259 OverloadCandidateSet &CandidateSet) {
5260 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5261 DeclAccessPair FoundDecl = ViableConversions[I];
5262 NamedDecl *D = FoundDecl.getDecl();
5263 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5264 if (isa<UsingShadowDecl>(D))
5265 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5266
5267 CXXConversionDecl *Conv;
5268 FunctionTemplateDecl *ConvTemplate;
5269 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5270 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5271 else
5272 Conv = cast<CXXConversionDecl>(D);
5273
5274 if (ConvTemplate)
5275 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005276 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5277 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005278 else
5279 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005280 ToType, CandidateSet,
5281 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005282 }
5283}
5284
Richard Smithccc11812013-05-21 19:05:48 +00005285/// \brief Attempt to convert the given expression to a type which is accepted
5286/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005287///
Richard Smithccc11812013-05-21 19:05:48 +00005288/// This routine will attempt to convert an expression of class type to a
5289/// type accepted by the specified converter. In C++11 and before, the class
5290/// must have a single non-explicit conversion function converting to a matching
5291/// type. In C++1y, there can be multiple such conversion functions, but only
5292/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005293///
Douglas Gregor4799d032010-06-30 00:20:43 +00005294/// \param Loc The source location of the construct that requires the
5295/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005296///
James Dennett18348b62012-06-22 08:52:37 +00005297/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005298///
Richard Smithccc11812013-05-21 19:05:48 +00005299/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005300///
Douglas Gregor4799d032010-06-30 00:20:43 +00005301/// \returns The expression, converted to an integral or enumeration type if
5302/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005303ExprResult Sema::PerformContextualImplicitConversion(
5304 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005305 // We can't perform any more checking for type-dependent expressions.
5306 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005307 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005308
Eli Friedman1da70392012-01-26 00:26:18 +00005309 // Process placeholders immediately.
5310 if (From->hasPlaceholderType()) {
5311 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005312 if (result.isInvalid())
5313 return result;
Eli Friedman1da70392012-01-26 00:26:18 +00005314 From = result.take();
5315 }
5316
Richard Smithccc11812013-05-21 19:05:48 +00005317 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005318 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005319 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005320 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005321
5322 // FIXME: Check for missing '()' if T is a function type?
5323
Richard Smithccc11812013-05-21 19:05:48 +00005324 // We can only perform contextual implicit conversions on objects of class
5325 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005326 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005327 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005328 if (!Converter.Suppress)
5329 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005330 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005331 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005333 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005334 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005335 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005336 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005337
5338 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5339 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5340
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005341 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smithccc11812013-05-21 19:05:48 +00005342 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005343 }
Richard Smithccc11812013-05-21 19:05:48 +00005344 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005345
5346 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005347 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005348
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005349 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005350 UnresolvedSet<4>
5351 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005352 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005353 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005354 CXXRecordDecl::conversion_iterator> Conversions =
5355 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005356
Larisse Voufo236bec22013-06-10 06:50:24 +00005357 bool HadMultipleCandidates =
5358 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005359
Larisse Voufo236bec22013-06-10 06:50:24 +00005360 // To check that there is only one target type, in C++1y:
5361 QualType ToType;
5362 bool HasUniqueTargetType = true;
5363
5364 // Collect explicit or viable (potentially in C++1y) conversions.
5365 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5366 E = Conversions.second;
5367 I != E; ++I) {
5368 NamedDecl *D = (*I)->getUnderlyingDecl();
5369 CXXConversionDecl *Conversion;
5370 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5371 if (ConvTemplate) {
5372 if (getLangOpts().CPlusPlus1y)
5373 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5374 else
5375 continue; // C++11 does not consider conversion operator templates(?).
5376 } else
5377 Conversion = cast<CXXConversionDecl>(D);
5378
5379 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5380 "Conversion operator templates are considered potentially "
5381 "viable in C++1y");
5382
5383 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5384 if (Converter.match(CurToType) || ConvTemplate) {
5385
5386 if (Conversion->isExplicit()) {
5387 // FIXME: For C++1y, do we need this restriction?
5388 // cf. diagnoseNoViableConversion()
5389 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005390 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005391 } else {
5392 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5393 if (ToType.isNull())
5394 ToType = CurToType.getUnqualifiedType();
5395 else if (HasUniqueTargetType &&
5396 (CurToType.getUnqualifiedType() != ToType))
5397 HasUniqueTargetType = false;
5398 }
5399 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005400 }
Richard Smith8dd34252012-02-04 07:07:42 +00005401 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005402 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005403
Larisse Voufo236bec22013-06-10 06:50:24 +00005404 if (getLangOpts().CPlusPlus1y) {
5405 // C++1y [conv]p6:
5406 // ... An expression e of class type E appearing in such a context
5407 // is said to be contextually implicitly converted to a specified
5408 // type T and is well-formed if and only if e can be implicitly
5409 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005410 // for conversion functions whose return type is cv T or reference to
5411 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005412 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005413
Larisse Voufo236bec22013-06-10 06:50:24 +00005414 // If no unique T is found:
5415 if (ToType.isNull()) {
5416 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5417 HadMultipleCandidates,
5418 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005419 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005420 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005421 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005422
Larisse Voufo236bec22013-06-10 06:50:24 +00005423 // If more than one unique Ts are found:
5424 if (!HasUniqueTargetType)
5425 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5426 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005427
Larisse Voufo236bec22013-06-10 06:50:24 +00005428 // If one unique T is found:
5429 // First, build a candidate set from the previously recorded
5430 // potentially viable conversions.
5431 OverloadCandidateSet CandidateSet(Loc);
5432 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5433 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005434
Larisse Voufo236bec22013-06-10 06:50:24 +00005435 // Then, perform overload resolution over the candidate set.
5436 OverloadCandidateSet::iterator Best;
5437 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5438 case OR_Success: {
5439 // Apply this conversion.
5440 DeclAccessPair Found =
5441 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5442 if (recordConversion(*this, Loc, From, Converter, T,
5443 HadMultipleCandidates, Found))
5444 return ExprError();
5445 break;
5446 }
5447 case OR_Ambiguous:
5448 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5449 ViableConversions);
5450 case OR_No_Viable_Function:
5451 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5452 HadMultipleCandidates,
5453 ExplicitConversions))
5454 return ExprError();
5455 // fall through 'OR_Deleted' case.
5456 case OR_Deleted:
5457 // We'll complain below about a non-integral condition type.
5458 break;
5459 }
5460 } else {
5461 switch (ViableConversions.size()) {
5462 case 0: {
5463 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5464 HadMultipleCandidates,
5465 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005466 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005467
Larisse Voufo236bec22013-06-10 06:50:24 +00005468 // We'll complain below about a non-integral condition type.
5469 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005470 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005471 case 1: {
5472 // Apply this conversion.
5473 DeclAccessPair Found = ViableConversions[0];
5474 if (recordConversion(*this, Loc, From, Converter, T,
5475 HadMultipleCandidates, Found))
5476 return ExprError();
5477 break;
5478 }
5479 default:
5480 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5481 ViableConversions);
5482 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005483 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484
Larisse Voufo236bec22013-06-10 06:50:24 +00005485 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005486}
5487
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005488/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005489/// candidate functions, using the given function call arguments. If
5490/// @p SuppressUserConversions, then don't allow user-defined
5491/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005492///
James Dennett2a4d13c2012-06-15 07:13:21 +00005493/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005494/// based on an incomplete set of function arguments. This feature is used by
5495/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005496void
5497Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005498 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005499 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005500 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005501 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005502 bool PartialOverloading,
5503 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005504 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005505 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005506 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005507 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005508 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005509
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005511 if (!isa<CXXConstructorDecl>(Method)) {
5512 // If we get here, it's because we're calling a member function
5513 // that is named without a member access expression (e.g.,
5514 // "this->f") that was either written explicitly or created
5515 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005516 // function, e.g., X::f(). We use an empty type for the implied
5517 // object argument (C++ [over.call.func]p3), and the acting context
5518 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005519 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005520 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005521 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005522 return;
5523 }
5524 // We treat a constructor like a non-member function, since its object
5525 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005526 }
5527
Douglas Gregorff7028a2009-11-13 23:59:09 +00005528 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005529 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005530
Richard Smith8b86f2d2013-11-04 01:48:18 +00005531 // C++11 [class.copy]p11: [DR1402]
5532 // A defaulted move constructor that is defined as deleted is ignored by
5533 // overload resolution.
5534 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5535 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5536 Constructor->isMoveConstructor())
5537 return;
5538
Douglas Gregor27381f32009-11-23 12:27:39 +00005539 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005540 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005541
Richard Smith8b86f2d2013-11-04 01:48:18 +00005542 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005543 // C++ [class.copy]p3:
5544 // A member function template is never instantiated to perform the copy
5545 // of a class object to an object of its class type.
5546 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005547 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005548 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005549 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5550 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005551 return;
5552 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005553
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005554 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005555 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005556 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005557 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005558 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005559 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005560 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005561 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005562
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005563 unsigned NumArgsInProto = Proto->getNumArgs();
5564
5565 // (C++ 13.3.2p2): A candidate function having fewer than m
5566 // parameters is viable only if it has an ellipsis in its parameter
5567 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005568 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005569 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005570 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005571 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005572 return;
5573 }
5574
5575 // (C++ 13.3.2p2): A candidate function having more than m parameters
5576 // is viable only if the (m+1)st parameter has a default argument
5577 // (8.3.6). For the purposes of overload resolution, the
5578 // parameter list is truncated on the right, so that there are
5579 // exactly m parameters.
5580 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005581 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005582 // Not enough arguments.
5583 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005584 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005585 return;
5586 }
5587
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005588 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005589 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005590 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5591 if (CheckCUDATarget(Caller, Function)) {
5592 Candidate.Viable = false;
5593 Candidate.FailureKind = ovl_fail_bad_target;
5594 return;
5595 }
5596
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005597 // Determine the implicit conversion sequences for each of the
5598 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005599 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005600 if (ArgIdx < NumArgsInProto) {
5601 // (C++ 13.3.2p3): for F to be a viable function, there shall
5602 // exist for each argument an implicit conversion sequence
5603 // (13.3.3.1) that converts that argument to the corresponding
5604 // parameter of F.
5605 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005606 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005607 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005608 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005609 /*InOverloadResolution=*/true,
5610 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005611 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005612 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005613 if (Candidate.Conversions[ArgIdx].isBad()) {
5614 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005615 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005616 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005617 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005618 } else {
5619 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5620 // argument for which there is no corresponding parameter is
5621 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005622 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005623 }
5624 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005625
5626 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5627 Candidate.Viable = false;
5628 Candidate.FailureKind = ovl_fail_enable_if;
5629 Candidate.DeductionFailure.Data = FailedAttr;
5630 return;
5631 }
5632}
5633
5634static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5635
5636EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5637 bool MissingImplicitThis) {
5638 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5639 // we need to find the first failing one.
5640 if (!Function->hasAttrs())
5641 return 0;
5642 AttrVec Attrs = Function->getAttrs();
5643 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5644 IsNotEnableIfAttr);
5645 if (Attrs.begin() == E)
5646 return 0;
5647 std::reverse(Attrs.begin(), E);
5648
5649 SFINAETrap Trap(*this);
5650
5651 // Convert the arguments.
5652 SmallVector<Expr *, 16> ConvertedArgs;
5653 bool InitializationFailed = false;
5654 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5655 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5656 !cast<CXXMethodDecl>(Function)->isStatic()) {
5657 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5658 ExprResult R =
5659 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5660 Method, Method);
5661 if (R.isInvalid()) {
5662 InitializationFailed = true;
5663 break;
5664 }
5665 ConvertedArgs.push_back(R.take());
5666 } else {
5667 ExprResult R =
5668 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5669 Context,
5670 Function->getParamDecl(i)),
5671 SourceLocation(),
5672 Args[i]);
5673 if (R.isInvalid()) {
5674 InitializationFailed = true;
5675 break;
5676 }
5677 ConvertedArgs.push_back(R.take());
5678 }
5679 }
5680
5681 if (InitializationFailed || Trap.hasErrorOccurred())
5682 return cast<EnableIfAttr>(Attrs[0]);
5683
5684 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5685 APValue Result;
5686 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5687 if (!EIA->getCond()->EvaluateWithSubstitution(
5688 Result, Context, Function,
5689 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(),
5690 ConvertedArgs.size())) ||
5691 !Result.isInt() || !Result.getInt().getBoolValue()) {
5692 return EIA;
5693 }
5694 }
5695 return 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005696}
5697
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005698/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005699/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005700void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005701 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005702 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005703 bool SuppressUserConversions,
5704 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005705 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005706 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5707 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005708 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005709 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005710 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005711 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005712 Args.slice(1), CandidateSet,
5713 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005714 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005715 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005716 SuppressUserConversions);
5717 } else {
John McCalla0296f72010-03-19 07:35:19 +00005718 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005719 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5720 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005721 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005722 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005723 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005724 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005725 Args[0]->Classify(Context), Args.slice(1),
5726 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005727 else
John McCalla0296f72010-03-19 07:35:19 +00005728 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005729 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005730 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005731 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005732 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005733}
5734
John McCallf0f1cf02009-11-17 07:50:12 +00005735/// AddMethodCandidate - Adds a named decl (which is some kind of
5736/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005737void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005738 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005739 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005740 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005741 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005742 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005743 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005744 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005745
5746 if (isa<UsingShadowDecl>(Decl))
5747 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005748
John McCallf0f1cf02009-11-17 07:50:12 +00005749 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5750 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5751 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005752 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5753 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005754 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005755 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005756 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005757 } else {
John McCalla0296f72010-03-19 07:35:19 +00005758 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005759 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005760 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005761 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005762 }
5763}
5764
Douglas Gregor436424c2008-11-18 23:14:02 +00005765/// AddMethodCandidate - Adds the given C++ member function to the set
5766/// of candidate functions, using the given function call arguments
5767/// and the object argument (@c Object). For example, in a call
5768/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5769/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5770/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005771/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005772void
John McCalla0296f72010-03-19 07:35:19 +00005773Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005774 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005775 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005776 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005777 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005778 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005779 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005780 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005781 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005782 assert(!isa<CXXConstructorDecl>(Method) &&
5783 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005784
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005785 if (!CandidateSet.isNewCandidate(Method))
5786 return;
5787
Richard Smith8b86f2d2013-11-04 01:48:18 +00005788 // C++11 [class.copy]p23: [DR1402]
5789 // A defaulted move assignment operator that is defined as deleted is
5790 // ignored by overload resolution.
5791 if (Method->isDefaulted() && Method->isDeleted() &&
5792 Method->isMoveAssignmentOperator())
5793 return;
5794
Douglas Gregor27381f32009-11-23 12:27:39 +00005795 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005796 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005797
Douglas Gregor436424c2008-11-18 23:14:02 +00005798 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005799 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005800 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005801 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005802 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005803 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005804 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005805
5806 unsigned NumArgsInProto = Proto->getNumArgs();
5807
5808 // (C++ 13.3.2p2): A candidate function having fewer than m
5809 // parameters is viable only if it has an ellipsis in its parameter
5810 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005811 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005812 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005813 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005814 return;
5815 }
5816
5817 // (C++ 13.3.2p2): A candidate function having more than m parameters
5818 // is viable only if the (m+1)st parameter has a default argument
5819 // (8.3.6). For the purposes of overload resolution, the
5820 // parameter list is truncated on the right, so that there are
5821 // exactly m parameters.
5822 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005823 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005824 // Not enough arguments.
5825 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005826 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005827 return;
5828 }
5829
5830 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005831
John McCall6e9f8f62009-12-03 04:06:58 +00005832 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005833 // The implicit object argument is ignored.
5834 Candidate.IgnoreObjectArgument = true;
5835 else {
5836 // Determine the implicit conversion sequence for the object
5837 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005838 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005839 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5840 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005841 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005842 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005843 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005844 return;
5845 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005846 }
5847
5848 // Determine the implicit conversion sequences for each of the
5849 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005850 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005851 if (ArgIdx < NumArgsInProto) {
5852 // (C++ 13.3.2p3): for F to be a viable function, there shall
5853 // exist for each argument an implicit conversion sequence
5854 // (13.3.3.1) that converts that argument to the corresponding
5855 // parameter of F.
5856 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005857 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005858 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005859 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005860 /*InOverloadResolution=*/true,
5861 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005862 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005863 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005864 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005865 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005866 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005867 }
5868 } else {
5869 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5870 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005871 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005872 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005873 }
5874 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005875
5876 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5877 Candidate.Viable = false;
5878 Candidate.FailureKind = ovl_fail_enable_if;
5879 Candidate.DeductionFailure.Data = FailedAttr;
5880 return;
5881 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005882}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005883
Douglas Gregor97628d62009-08-21 00:16:32 +00005884/// \brief Add a C++ member function template as a candidate to the candidate
5885/// set, using template argument deduction to produce an appropriate member
5886/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005887void
Douglas Gregor97628d62009-08-21 00:16:32 +00005888Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005889 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005890 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005891 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005892 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005893 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005894 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005895 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005896 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005897 if (!CandidateSet.isNewCandidate(MethodTmpl))
5898 return;
5899
Douglas Gregor97628d62009-08-21 00:16:32 +00005900 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005901 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005902 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005903 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005904 // candidate functions in the usual way.113) A given name can refer to one
5905 // or more function templates and also to a set of overloaded non-template
5906 // functions. In such a case, the candidate functions generated from each
5907 // function template are combined with the set of non-template candidate
5908 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005909 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005910 FunctionDecl *Specialization = 0;
5911 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005912 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5913 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005914 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005915 Candidate.FoundDecl = FoundDecl;
5916 Candidate.Function = MethodTmpl->getTemplatedDecl();
5917 Candidate.Viable = false;
5918 Candidate.FailureKind = ovl_fail_bad_deduction;
5919 Candidate.IsSurrogate = false;
5920 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005921 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005922 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005923 Info);
5924 return;
5925 }
Mike Stump11289f42009-09-09 15:08:12 +00005926
Douglas Gregor97628d62009-08-21 00:16:32 +00005927 // Add the function template specialization produced by template argument
5928 // deduction as a candidate.
5929 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005930 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005931 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005932 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005933 ActingContext, ObjectType, ObjectClassification, Args,
5934 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005935}
5936
Douglas Gregor05155d82009-08-21 23:19:43 +00005937/// \brief Add a C++ function template specialization as a candidate
5938/// in the candidate set, using template argument deduction to produce
5939/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005940void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005941Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005942 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005943 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005944 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005945 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005946 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005947 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5948 return;
5949
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005950 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005951 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005952 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005953 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005954 // candidate functions in the usual way.113) A given name can refer to one
5955 // or more function templates and also to a set of overloaded non-template
5956 // functions. In such a case, the candidate functions generated from each
5957 // function template are combined with the set of non-template candidate
5958 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005959 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005960 FunctionDecl *Specialization = 0;
5961 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005962 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5963 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005964 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005965 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005966 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5967 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005968 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005969 Candidate.IsSurrogate = false;
5970 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005971 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005972 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005973 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005974 return;
5975 }
Mike Stump11289f42009-09-09 15:08:12 +00005976
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005977 // Add the function template specialization produced by template argument
5978 // deduction as a candidate.
5979 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005980 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005981 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005982}
Mike Stump11289f42009-09-09 15:08:12 +00005983
Douglas Gregor4b60a152013-11-07 22:34:54 +00005984/// Determine whether this is an allowable conversion from the result
5985/// of an explicit conversion operator to the expected type, per C++
5986/// [over.match.conv]p1 and [over.match.ref]p1.
5987///
5988/// \param ConvType The return type of the conversion function.
5989///
5990/// \param ToType The type we are converting to.
5991///
5992/// \param AllowObjCPointerConversion Allow a conversion from one
5993/// Objective-C pointer to another.
5994///
5995/// \returns true if the conversion is allowable, false otherwise.
5996static bool isAllowableExplicitConversion(Sema &S,
5997 QualType ConvType, QualType ToType,
5998 bool AllowObjCPointerConversion) {
5999 QualType ToNonRefType = ToType.getNonReferenceType();
6000
6001 // Easy case: the types are the same.
6002 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
6003 return true;
6004
6005 // Allow qualification conversions.
6006 bool ObjCLifetimeConversion;
6007 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
6008 ObjCLifetimeConversion))
6009 return true;
6010
6011 // If we're not allowed to consider Objective-C pointer conversions,
6012 // we're done.
6013 if (!AllowObjCPointerConversion)
6014 return false;
6015
6016 // Is this an Objective-C pointer conversion?
6017 bool IncompatibleObjC = false;
6018 QualType ConvertedType;
6019 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
6020 IncompatibleObjC);
6021}
6022
Douglas Gregora1f013e2008-11-07 22:36:19 +00006023/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00006024/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00006025/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00006026/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00006027/// (which may or may not be the same type as the type that the
6028/// conversion function produces).
6029void
6030Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006031 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006032 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006033 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006034 OverloadCandidateSet& CandidateSet,
6035 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006036 assert(!Conversion->getDescribedFunctionTemplate() &&
6037 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006038 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006039 if (!CandidateSet.isNewCandidate(Conversion))
6040 return;
6041
Richard Smith2a7d4812013-05-04 07:00:32 +00006042 // If the conversion function has an undeduced return type, trigger its
6043 // deduction now.
6044 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6045 if (DeduceReturnType(Conversion, From->getExprLoc()))
6046 return;
6047 ConvType = Conversion->getConversionType().getNonReferenceType();
6048 }
6049
Richard Smith089c3162013-09-21 21:55:46 +00006050 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6051 // operator is only a candidate if its return type is the target type or
6052 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006053 if (Conversion->isExplicit() &&
6054 !isAllowableExplicitConversion(*this, ConvType, ToType,
6055 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006056 return;
6057
Douglas Gregor27381f32009-11-23 12:27:39 +00006058 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006059 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006060
Douglas Gregora1f013e2008-11-07 22:36:19 +00006061 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006062 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006063 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006064 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006065 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006066 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006067 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006068 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006069 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006070 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006071 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006072
Douglas Gregor6affc782010-08-19 15:37:02 +00006073 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006074 // For conversion functions, the function is considered to be a member of
6075 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006076 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006077 //
6078 // Determine the implicit conversion sequence for the implicit
6079 // object parameter.
6080 QualType ImplicitParamType = From->getType();
6081 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6082 ImplicitParamType = FromPtrType->getPointeeType();
6083 CXXRecordDecl *ConversionContext
6084 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006085
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006086 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006087 = TryObjectArgumentInitialization(*this, From->getType(),
6088 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006089 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006090
John McCall0d1da222010-01-12 00:44:57 +00006091 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006092 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006093 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006094 return;
6095 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006096
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006097 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006098 // derived to base as such conversions are given Conversion Rank. They only
6099 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6100 QualType FromCanon
6101 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6102 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6103 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6104 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006105 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006106 return;
6107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006108
Douglas Gregora1f013e2008-11-07 22:36:19 +00006109 // To determine what the conversion from the result of calling the
6110 // conversion function to the type we're eventually trying to
6111 // convert to (ToType), we need to synthesize a call to the
6112 // conversion function and attempt copy initialization from it. This
6113 // makes sure that we get the right semantics with respect to
6114 // lvalues/rvalues and the type. Fortunately, we can allocate this
6115 // call on the stack and we don't need its arguments to be
6116 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006117 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006118 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006119 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6120 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006121 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006122 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006123
Richard Smith48d24642011-07-13 22:53:21 +00006124 QualType ConversionType = Conversion->getConversionType();
6125 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006126 Candidate.Viable = false;
6127 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6128 return;
6129 }
6130
Richard Smith48d24642011-07-13 22:53:21 +00006131 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006132
Mike Stump11289f42009-09-09 15:08:12 +00006133 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006134 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6135 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006136 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006137 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006138 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006139 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006140 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006141 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006142 /*InOverloadResolution=*/false,
6143 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006144
John McCall0d1da222010-01-12 00:44:57 +00006145 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006146 case ImplicitConversionSequence::StandardConversion:
6147 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006148
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006149 // C++ [over.ics.user]p3:
6150 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006151 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006152 // shall have exact match rank.
6153 if (Conversion->getPrimaryTemplate() &&
6154 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6155 Candidate.Viable = false;
6156 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006157 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006158 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006159
Douglas Gregorcba72b12011-01-21 05:18:22 +00006160 // C++0x [dcl.init.ref]p5:
6161 // In the second case, if the reference is an rvalue reference and
6162 // the second standard conversion sequence of the user-defined
6163 // conversion sequence includes an lvalue-to-rvalue conversion, the
6164 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006165 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006166 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6167 Candidate.Viable = false;
6168 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006169 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006170 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006171 break;
6172
6173 case ImplicitConversionSequence::BadConversion:
6174 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006175 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006176 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006177
6178 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006179 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006180 "Can only end up with a standard conversion sequence or failure");
6181 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006182
6183 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6184 Candidate.Viable = false;
6185 Candidate.FailureKind = ovl_fail_enable_if;
6186 Candidate.DeductionFailure.Data = FailedAttr;
6187 return;
6188 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006189}
6190
Douglas Gregor05155d82009-08-21 23:19:43 +00006191/// \brief Adds a conversion function template specialization
6192/// candidate to the overload set, using template argument deduction
6193/// to deduce the template arguments of the conversion function
6194/// template from the type that we are converting to (C++
6195/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006196void
Douglas Gregor05155d82009-08-21 23:19:43 +00006197Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006198 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006199 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006200 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006201 OverloadCandidateSet &CandidateSet,
6202 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006203 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6204 "Only conversion function templates permitted here");
6205
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006206 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6207 return;
6208
Craig Toppere6706e42012-09-19 02:26:47 +00006209 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00006210 CXXConversionDecl *Specialization = 0;
6211 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006212 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006213 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006214 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006215 Candidate.FoundDecl = FoundDecl;
6216 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6217 Candidate.Viable = false;
6218 Candidate.FailureKind = ovl_fail_bad_deduction;
6219 Candidate.IsSurrogate = false;
6220 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006221 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006222 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006223 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006224 return;
6225 }
Mike Stump11289f42009-09-09 15:08:12 +00006226
Douglas Gregor05155d82009-08-21 23:19:43 +00006227 // Add the conversion function template specialization produced by
6228 // template argument deduction as a candidate.
6229 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006230 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006231 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006232}
6233
Douglas Gregorab7897a2008-11-19 22:57:39 +00006234/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6235/// converts the given @c Object to a function pointer via the
6236/// conversion function @c Conversion, and then attempts to call it
6237/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6238/// the type of function that we'll eventually be calling.
6239void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006240 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006241 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006242 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006243 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006244 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006245 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006246 if (!CandidateSet.isNewCandidate(Conversion))
6247 return;
6248
Douglas Gregor27381f32009-11-23 12:27:39 +00006249 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006250 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006251
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006252 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006253 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006254 Candidate.Function = 0;
6255 Candidate.Surrogate = Conversion;
6256 Candidate.Viable = true;
6257 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006258 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006259 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006260
6261 // Determine the implicit conversion sequence for the implicit
6262 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006263 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006264 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006265 Object->Classify(Context),
6266 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006267 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006268 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006269 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006270 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006271 return;
6272 }
6273
6274 // The first conversion is actually a user-defined conversion whose
6275 // first conversion is ObjectInit's standard conversion (which is
6276 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006277 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006278 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006279 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006280 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006281 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006282 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006283 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006284 = Candidate.Conversions[0].UserDefined.Before;
6285 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6286
Mike Stump11289f42009-09-09 15:08:12 +00006287 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00006288 unsigned NumArgsInProto = Proto->getNumArgs();
6289
6290 // (C++ 13.3.2p2): A candidate function having fewer than m
6291 // parameters is viable only if it has an ellipsis in its parameter
6292 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006293 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006294 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006295 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006296 return;
6297 }
6298
6299 // Function types don't have any default arguments, so just check if
6300 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006301 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006302 // Not enough arguments.
6303 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006304 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006305 return;
6306 }
6307
6308 // Determine the implicit conversion sequences for each of the
6309 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006310 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006311 if (ArgIdx < NumArgsInProto) {
6312 // (C++ 13.3.2p3): for F to be a viable function, there shall
6313 // exist for each argument an implicit conversion sequence
6314 // (13.3.3.1) that converts that argument to the corresponding
6315 // parameter of F.
6316 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006317 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006318 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006319 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006320 /*InOverloadResolution=*/false,
6321 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006322 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006323 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006324 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006325 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006326 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006327 }
6328 } else {
6329 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6330 // argument for which there is no corresponding parameter is
6331 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006332 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006333 }
6334 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006335
6336 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6337 Candidate.Viable = false;
6338 Candidate.FailureKind = ovl_fail_enable_if;
6339 Candidate.DeductionFailure.Data = FailedAttr;
6340 return;
6341 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006342}
6343
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006344/// \brief Add overload candidates for overloaded operators that are
6345/// member functions.
6346///
6347/// Add the overloaded operator candidates that are member functions
6348/// for the operator Op that was used in an operator expression such
6349/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6350/// CandidateSet will store the added overload candidates. (C++
6351/// [over.match.oper]).
6352void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6353 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006354 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006355 OverloadCandidateSet& CandidateSet,
6356 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006357 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6358
6359 // C++ [over.match.oper]p3:
6360 // For a unary operator @ with an operand of a type whose
6361 // cv-unqualified version is T1, and for a binary operator @ with
6362 // a left operand of a type whose cv-unqualified version is T1 and
6363 // a right operand of a type whose cv-unqualified version is T2,
6364 // three sets of candidate functions, designated member
6365 // candidates, non-member candidates and built-in candidates, are
6366 // constructed as follows:
6367 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006368
Richard Smith0feaf0c2013-04-20 12:41:22 +00006369 // -- If T1 is a complete class type or a class currently being
6370 // defined, the set of member candidates is the result of the
6371 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6372 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006373 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006374 // Complete the type if it can be completed.
6375 RequireCompleteType(OpLoc, T1, 0);
6376 // If the type is neither complete nor being defined, bail out now.
6377 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006378 return;
Mike Stump11289f42009-09-09 15:08:12 +00006379
John McCall27b18f82009-11-17 02:14:36 +00006380 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6381 LookupQualifiedName(Operators, T1Rec->getDecl());
6382 Operators.suppressDiagnostics();
6383
Mike Stump11289f42009-09-09 15:08:12 +00006384 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006385 OperEnd = Operators.end();
6386 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006387 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006388 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006389 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006390 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006391 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006392 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006393 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006394}
6395
Douglas Gregora11693b2008-11-12 17:17:38 +00006396/// AddBuiltinCandidate - Add a candidate for a built-in
6397/// operator. ResultTy and ParamTys are the result and parameter types
6398/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006399/// arguments being passed to the candidate. IsAssignmentOperator
6400/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006401/// operator. NumContextualBoolArguments is the number of arguments
6402/// (at the beginning of the argument list) that will be contextually
6403/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006404void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006405 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006406 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006407 bool IsAssignmentOperator,
6408 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006409 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006410 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006411
Douglas Gregora11693b2008-11-12 17:17:38 +00006412 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006413 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00006414 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00006415 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006416 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006417 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006418 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006419 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006420 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6421
6422 // Determine the implicit conversion sequences for each of the
6423 // arguments.
6424 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006425 Candidate.ExplicitCallArguments = Args.size();
6426 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006427 // C++ [over.match.oper]p4:
6428 // For the built-in assignment operators, conversions of the
6429 // left operand are restricted as follows:
6430 // -- no temporaries are introduced to hold the left operand, and
6431 // -- no user-defined conversions are applied to the left
6432 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006433 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006434 //
6435 // We block these conversions by turning off user-defined
6436 // conversions, since that is the only way that initialization of
6437 // a reference to a non-class type can occur from something that
6438 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006439 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006440 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006441 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006442 Candidate.Conversions[ArgIdx]
6443 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006444 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006445 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006446 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006447 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006448 /*InOverloadResolution=*/false,
6449 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006450 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006451 }
John McCall0d1da222010-01-12 00:44:57 +00006452 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006453 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006454 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006455 break;
6456 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006457 }
6458}
6459
Craig Toppercd7b0332013-07-01 06:29:40 +00006460namespace {
6461
Douglas Gregora11693b2008-11-12 17:17:38 +00006462/// BuiltinCandidateTypeSet - A set of types that will be used for the
6463/// candidate operator functions for built-in operators (C++
6464/// [over.built]). The types are separated into pointer types and
6465/// enumeration types.
6466class BuiltinCandidateTypeSet {
6467 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006468 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006469
6470 /// PointerTypes - The set of pointer types that will be used in the
6471 /// built-in candidates.
6472 TypeSet PointerTypes;
6473
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006474 /// MemberPointerTypes - The set of member pointer types that will be
6475 /// used in the built-in candidates.
6476 TypeSet MemberPointerTypes;
6477
Douglas Gregora11693b2008-11-12 17:17:38 +00006478 /// EnumerationTypes - The set of enumeration types that will be
6479 /// used in the built-in candidates.
6480 TypeSet EnumerationTypes;
6481
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006482 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006483 /// candidates.
6484 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006485
6486 /// \brief A flag indicating non-record types are viable candidates
6487 bool HasNonRecordTypes;
6488
6489 /// \brief A flag indicating whether either arithmetic or enumeration types
6490 /// were present in the candidate set.
6491 bool HasArithmeticOrEnumeralTypes;
6492
Douglas Gregor80af3132011-05-21 23:15:46 +00006493 /// \brief A flag indicating whether the nullptr type was present in the
6494 /// candidate set.
6495 bool HasNullPtrType;
6496
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006497 /// Sema - The semantic analysis instance where we are building the
6498 /// candidate type set.
6499 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006500
Douglas Gregora11693b2008-11-12 17:17:38 +00006501 /// Context - The AST context in which we will build the type sets.
6502 ASTContext &Context;
6503
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006504 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6505 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006506 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006507
6508public:
6509 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006510 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006511
Mike Stump11289f42009-09-09 15:08:12 +00006512 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006513 : HasNonRecordTypes(false),
6514 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006515 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006516 SemaRef(SemaRef),
6517 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006518
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006519 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006520 SourceLocation Loc,
6521 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006522 bool AllowExplicitConversions,
6523 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006524
6525 /// pointer_begin - First pointer type found;
6526 iterator pointer_begin() { return PointerTypes.begin(); }
6527
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006528 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006529 iterator pointer_end() { return PointerTypes.end(); }
6530
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006531 /// member_pointer_begin - First member pointer type found;
6532 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6533
6534 /// member_pointer_end - Past the last member pointer type found;
6535 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6536
Douglas Gregora11693b2008-11-12 17:17:38 +00006537 /// enumeration_begin - First enumeration type found;
6538 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6539
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006540 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006541 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006542
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006543 iterator vector_begin() { return VectorTypes.begin(); }
6544 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006545
6546 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6547 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006548 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006549};
6550
Craig Toppercd7b0332013-07-01 06:29:40 +00006551} // end anonymous namespace
6552
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006553/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006554/// the set of pointer types along with any more-qualified variants of
6555/// that type. For example, if @p Ty is "int const *", this routine
6556/// will add "int const *", "int const volatile *", "int const
6557/// restrict *", and "int const volatile restrict *" to the set of
6558/// pointer types. Returns true if the add of @p Ty itself succeeded,
6559/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006560///
6561/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006562bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006563BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6564 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006565
Douglas Gregora11693b2008-11-12 17:17:38 +00006566 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006567 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006568 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006570 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006571 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006572 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006573 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006574 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6575 PointeeTy = PTy->getPointeeType();
6576 buildObjCPtr = true;
6577 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006578 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006579 }
6580
Sebastian Redl4990a632009-11-18 20:39:26 +00006581 // Don't add qualified variants of arrays. For one, they're not allowed
6582 // (the qualifier would sink to the element type), and for another, the
6583 // only overload situation where it matters is subscript or pointer +- int,
6584 // and those shouldn't have qualifier variants anyway.
6585 if (PointeeTy->isArrayType())
6586 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006587
John McCall8ccfcb52009-09-24 19:53:00 +00006588 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006589 bool hasVolatile = VisibleQuals.hasVolatile();
6590 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006591
John McCall8ccfcb52009-09-24 19:53:00 +00006592 // Iterate through all strict supersets of BaseCVR.
6593 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6594 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006595 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006596 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006597
6598 // Skip over restrict if no restrict found anywhere in the types, or if
6599 // the type cannot be restrict-qualified.
6600 if ((CVR & Qualifiers::Restrict) &&
6601 (!hasRestrict ||
6602 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6603 continue;
6604
6605 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006606 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006607
6608 // Build qualified pointer type.
6609 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006610 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006611 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006612 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006613 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6614
6615 // Insert qualified pointer type.
6616 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006617 }
6618
6619 return true;
6620}
6621
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006622/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6623/// to the set of pointer types along with any more-qualified variants of
6624/// that type. For example, if @p Ty is "int const *", this routine
6625/// will add "int const *", "int const volatile *", "int const
6626/// restrict *", and "int const volatile restrict *" to the set of
6627/// pointer types. Returns true if the add of @p Ty itself succeeded,
6628/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006629///
6630/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006631bool
6632BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6633 QualType Ty) {
6634 // Insert this type.
6635 if (!MemberPointerTypes.insert(Ty))
6636 return false;
6637
John McCall8ccfcb52009-09-24 19:53:00 +00006638 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6639 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006640
John McCall8ccfcb52009-09-24 19:53:00 +00006641 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006642 // Don't add qualified variants of arrays. For one, they're not allowed
6643 // (the qualifier would sink to the element type), and for another, the
6644 // only overload situation where it matters is subscript or pointer +- int,
6645 // and those shouldn't have qualifier variants anyway.
6646 if (PointeeTy->isArrayType())
6647 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006648 const Type *ClassTy = PointerTy->getClass();
6649
6650 // Iterate through all strict supersets of the pointee type's CVR
6651 // qualifiers.
6652 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6653 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6654 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006655
John McCall8ccfcb52009-09-24 19:53:00 +00006656 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006657 MemberPointerTypes.insert(
6658 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006659 }
6660
6661 return true;
6662}
6663
Douglas Gregora11693b2008-11-12 17:17:38 +00006664/// AddTypesConvertedFrom - Add each of the types to which the type @p
6665/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006666/// primarily interested in pointer types and enumeration types. We also
6667/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006668/// AllowUserConversions is true if we should look at the conversion
6669/// functions of a class type, and AllowExplicitConversions if we
6670/// should also include the explicit conversion functions of a class
6671/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006672void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006673BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006674 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006675 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006676 bool AllowExplicitConversions,
6677 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006678 // Only deal with canonical types.
6679 Ty = Context.getCanonicalType(Ty);
6680
6681 // Look through reference types; they aren't part of the type of an
6682 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006683 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006684 Ty = RefTy->getPointeeType();
6685
John McCall33ddac02011-01-19 10:06:00 +00006686 // If we're dealing with an array type, decay to the pointer.
6687 if (Ty->isArrayType())
6688 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6689
6690 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006691 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006692
Chandler Carruth00a38332010-12-13 01:44:01 +00006693 // Flag if we ever add a non-record type.
6694 const RecordType *TyRec = Ty->getAs<RecordType>();
6695 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6696
Chandler Carruth00a38332010-12-13 01:44:01 +00006697 // Flag if we encounter an arithmetic type.
6698 HasArithmeticOrEnumeralTypes =
6699 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6700
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006701 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6702 PointerTypes.insert(Ty);
6703 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006704 // Insert our type, and its more-qualified variants, into the set
6705 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006706 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006707 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006708 } else if (Ty->isMemberPointerType()) {
6709 // Member pointers are far easier, since the pointee can't be converted.
6710 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6711 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006712 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006713 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006714 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006715 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006716 // We treat vector types as arithmetic types in many contexts as an
6717 // extension.
6718 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006719 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006720 } else if (Ty->isNullPtrType()) {
6721 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006722 } else if (AllowUserConversions && TyRec) {
6723 // No conversion functions in incomplete types.
6724 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6725 return;
Mike Stump11289f42009-09-09 15:08:12 +00006726
Chandler Carruth00a38332010-12-13 01:44:01 +00006727 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006728 std::pair<CXXRecordDecl::conversion_iterator,
6729 CXXRecordDecl::conversion_iterator>
6730 Conversions = ClassDecl->getVisibleConversionFunctions();
6731 for (CXXRecordDecl::conversion_iterator
6732 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006733 NamedDecl *D = I.getDecl();
6734 if (isa<UsingShadowDecl>(D))
6735 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006736
Chandler Carruth00a38332010-12-13 01:44:01 +00006737 // Skip conversion function templates; they don't tell us anything
6738 // about which builtin types we can convert to.
6739 if (isa<FunctionTemplateDecl>(D))
6740 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006741
Chandler Carruth00a38332010-12-13 01:44:01 +00006742 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6743 if (AllowExplicitConversions || !Conv->isExplicit()) {
6744 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6745 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006746 }
6747 }
6748 }
6749}
6750
Douglas Gregor84605ae2009-08-24 13:43:27 +00006751/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6752/// the volatile- and non-volatile-qualified assignment operators for the
6753/// given type to the candidate set.
6754static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6755 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006756 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006757 OverloadCandidateSet &CandidateSet) {
6758 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006759
Douglas Gregor84605ae2009-08-24 13:43:27 +00006760 // T& operator=(T&, T)
6761 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6762 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006763 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006764 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006765
Douglas Gregor84605ae2009-08-24 13:43:27 +00006766 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6767 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006768 ParamTypes[0]
6769 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006770 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006771 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006772 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006773 }
6774}
Mike Stump11289f42009-09-09 15:08:12 +00006775
Sebastian Redl1054fae2009-10-25 17:03:50 +00006776/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6777/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006778static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6779 Qualifiers VRQuals;
6780 const RecordType *TyRec;
6781 if (const MemberPointerType *RHSMPType =
6782 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006783 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006784 else
6785 TyRec = ArgExpr->getType()->getAs<RecordType>();
6786 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006787 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006788 VRQuals.addVolatile();
6789 VRQuals.addRestrict();
6790 return VRQuals;
6791 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006792
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006793 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006794 if (!ClassDecl->hasDefinition())
6795 return VRQuals;
6796
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006797 std::pair<CXXRecordDecl::conversion_iterator,
6798 CXXRecordDecl::conversion_iterator>
6799 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006800
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006801 for (CXXRecordDecl::conversion_iterator
6802 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006803 NamedDecl *D = I.getDecl();
6804 if (isa<UsingShadowDecl>(D))
6805 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6806 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006807 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6808 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6809 CanTy = ResTypeRef->getPointeeType();
6810 // Need to go down the pointer/mempointer chain and add qualifiers
6811 // as see them.
6812 bool done = false;
6813 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006814 if (CanTy.isRestrictQualified())
6815 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006816 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6817 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006818 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006819 CanTy->getAs<MemberPointerType>())
6820 CanTy = ResTypeMPtr->getPointeeType();
6821 else
6822 done = true;
6823 if (CanTy.isVolatileQualified())
6824 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006825 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6826 return VRQuals;
6827 }
6828 }
6829 }
6830 return VRQuals;
6831}
John McCall52872982010-11-13 05:51:15 +00006832
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006833namespace {
John McCall52872982010-11-13 05:51:15 +00006834
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006835/// \brief Helper class to manage the addition of builtin operator overload
6836/// candidates. It provides shared state and utility methods used throughout
6837/// the process, as well as a helper method to add each group of builtin
6838/// operator overloads from the standard to a candidate set.
6839class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006840 // Common instance state available to all overload candidate addition methods.
6841 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006842 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006843 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006844 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006845 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006846 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006847
Chandler Carruthc6586e52010-12-12 10:35:00 +00006848 // Define some constants used to index and iterate over the arithemetic types
6849 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006850 // The "promoted arithmetic types" are the arithmetic
6851 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006852 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006853 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006854 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006855 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006856 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006857 LastPromotedArithmeticType = 11;
6858 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006859
Chandler Carruthc6586e52010-12-12 10:35:00 +00006860 /// \brief Get the canonical type for a given arithmetic type index.
6861 CanQualType getArithmeticType(unsigned index) {
6862 assert(index < NumArithmeticTypes);
6863 static CanQualType ASTContext::* const
6864 ArithmeticTypes[NumArithmeticTypes] = {
6865 // Start of promoted types.
6866 &ASTContext::FloatTy,
6867 &ASTContext::DoubleTy,
6868 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006869
Chandler Carruthc6586e52010-12-12 10:35:00 +00006870 // Start of integral types.
6871 &ASTContext::IntTy,
6872 &ASTContext::LongTy,
6873 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006874 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006875 &ASTContext::UnsignedIntTy,
6876 &ASTContext::UnsignedLongTy,
6877 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006878 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006879 // End of promoted types.
6880
6881 &ASTContext::BoolTy,
6882 &ASTContext::CharTy,
6883 &ASTContext::WCharTy,
6884 &ASTContext::Char16Ty,
6885 &ASTContext::Char32Ty,
6886 &ASTContext::SignedCharTy,
6887 &ASTContext::ShortTy,
6888 &ASTContext::UnsignedCharTy,
6889 &ASTContext::UnsignedShortTy,
6890 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006891 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006892 };
6893 return S.Context.*ArithmeticTypes[index];
6894 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006895
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006896 /// \brief Gets the canonical type resulting from the usual arithemetic
6897 /// converions for the given arithmetic types.
6898 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6899 // Accelerator table for performing the usual arithmetic conversions.
6900 // The rules are basically:
6901 // - if either is floating-point, use the wider floating-point
6902 // - if same signedness, use the higher rank
6903 // - if same size, use unsigned of the higher rank
6904 // - use the larger type
6905 // These rules, together with the axiom that higher ranks are
6906 // never smaller, are sufficient to precompute all of these results
6907 // *except* when dealing with signed types of higher rank.
6908 // (we could precompute SLL x UI for all known platforms, but it's
6909 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006910 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006911 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006912 Dep=-1,
6913 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006914 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006915 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006916 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006917/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6918/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6919/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6920/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6921/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6922/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6923/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6924/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6925/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6926/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6927/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006928 };
6929
6930 assert(L < LastPromotedArithmeticType);
6931 assert(R < LastPromotedArithmeticType);
6932 int Idx = ConversionsTable[L][R];
6933
6934 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006935 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006936
6937 // Slow path: we need to compare widths.
6938 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006939 CanQualType LT = getArithmeticType(L),
6940 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006941 unsigned LW = S.Context.getIntWidth(LT),
6942 RW = S.Context.getIntWidth(RT);
6943
6944 // If they're different widths, use the signed type.
6945 if (LW > RW) return LT;
6946 else if (LW < RW) return RT;
6947
6948 // Otherwise, use the unsigned type of the signed type's rank.
6949 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6950 assert(L == SLL || R == SLL);
6951 return S.Context.UnsignedLongLongTy;
6952 }
6953
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006954 /// \brief Helper method to factor out the common pattern of adding overloads
6955 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006956 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006957 bool HasVolatile,
6958 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006959 QualType ParamTypes[2] = {
6960 S.Context.getLValueReferenceType(CandidateTy),
6961 S.Context.IntTy
6962 };
6963
6964 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00006965 if (Args.size() == 1)
6966 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006967 else
Richard Smithe54c3072013-05-05 15:51:06 +00006968 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006969
6970 // Use a heuristic to reduce number of builtin candidates in the set:
6971 // add volatile version only if there are conversions to a volatile type.
6972 if (HasVolatile) {
6973 ParamTypes[0] =
6974 S.Context.getLValueReferenceType(
6975 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00006976 if (Args.size() == 1)
6977 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006978 else
Richard Smithe54c3072013-05-05 15:51:06 +00006979 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006980 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006981
6982 // Add restrict version only if there are conversions to a restrict type
6983 // and our candidate type is a non-restrict-qualified pointer.
6984 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6985 !CandidateTy.isRestrictQualified()) {
6986 ParamTypes[0]
6987 = S.Context.getLValueReferenceType(
6988 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00006989 if (Args.size() == 1)
6990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006991 else
Richard Smithe54c3072013-05-05 15:51:06 +00006992 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006993
6994 if (HasVolatile) {
6995 ParamTypes[0]
6996 = S.Context.getLValueReferenceType(
6997 S.Context.getCVRQualifiedType(CandidateTy,
6998 (Qualifiers::Volatile |
6999 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007000 if (Args.size() == 1)
7001 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007002 else
Richard Smithe54c3072013-05-05 15:51:06 +00007003 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007004 }
7005 }
7006
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007007 }
7008
7009public:
7010 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00007011 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007012 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007013 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007014 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007015 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00007016 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007017 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00007018 HasArithmeticOrEnumeralCandidateType(
7019 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007020 CandidateTypes(CandidateTypes),
7021 CandidateSet(CandidateSet) {
7022 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00007023 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007024 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007025 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007026 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007027 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007028 assert(getArithmeticType(FirstPromotedArithmeticType)
7029 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007030 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007031 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007032 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007033 "Invalid last promoted arithmetic type");
7034 }
7035
7036 // C++ [over.built]p3:
7037 //
7038 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7039 // is either volatile or empty, there exist candidate operator
7040 // functions of the form
7041 //
7042 // VQ T& operator++(VQ T&);
7043 // T operator++(VQ T&, int);
7044 //
7045 // C++ [over.built]p4:
7046 //
7047 // For every pair (T, VQ), where T is an arithmetic type other
7048 // than bool, and VQ is either volatile or empty, there exist
7049 // candidate operator functions of the form
7050 //
7051 // VQ T& operator--(VQ T&);
7052 // T operator--(VQ T&, int);
7053 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007054 if (!HasArithmeticOrEnumeralCandidateType)
7055 return;
7056
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007057 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7058 Arith < NumArithmeticTypes; ++Arith) {
7059 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007060 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007061 VisibleTypeConversionsQuals.hasVolatile(),
7062 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007063 }
7064 }
7065
7066 // C++ [over.built]p5:
7067 //
7068 // For every pair (T, VQ), where T is a cv-qualified or
7069 // cv-unqualified object type, and VQ is either volatile or
7070 // empty, there exist candidate operator functions of the form
7071 //
7072 // T*VQ& operator++(T*VQ&);
7073 // T*VQ& operator--(T*VQ&);
7074 // T* operator++(T*VQ&, int);
7075 // T* operator--(T*VQ&, int);
7076 void addPlusPlusMinusMinusPointerOverloads() {
7077 for (BuiltinCandidateTypeSet::iterator
7078 Ptr = CandidateTypes[0].pointer_begin(),
7079 PtrEnd = CandidateTypes[0].pointer_end();
7080 Ptr != PtrEnd; ++Ptr) {
7081 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007082 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007083 continue;
7084
7085 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007086 (!(*Ptr).isVolatileQualified() &&
7087 VisibleTypeConversionsQuals.hasVolatile()),
7088 (!(*Ptr).isRestrictQualified() &&
7089 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007090 }
7091 }
7092
7093 // C++ [over.built]p6:
7094 // For every cv-qualified or cv-unqualified object type T, there
7095 // exist candidate operator functions of the form
7096 //
7097 // T& operator*(T*);
7098 //
7099 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007100 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007101 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007102 // T& operator*(T*);
7103 void addUnaryStarPointerOverloads() {
7104 for (BuiltinCandidateTypeSet::iterator
7105 Ptr = CandidateTypes[0].pointer_begin(),
7106 PtrEnd = CandidateTypes[0].pointer_end();
7107 Ptr != PtrEnd; ++Ptr) {
7108 QualType ParamTy = *Ptr;
7109 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007110 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7111 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
Douglas Gregor02824322011-01-26 19:30:28 +00007113 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7114 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7115 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007117 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007118 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007119 }
7120 }
7121
7122 // C++ [over.built]p9:
7123 // For every promoted arithmetic type T, there exist candidate
7124 // operator functions of the form
7125 //
7126 // T operator+(T);
7127 // T operator-(T);
7128 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007129 if (!HasArithmeticOrEnumeralCandidateType)
7130 return;
7131
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007132 for (unsigned Arith = FirstPromotedArithmeticType;
7133 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007134 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007135 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007136 }
7137
7138 // Extension: We also add these operators for vector types.
7139 for (BuiltinCandidateTypeSet::iterator
7140 Vec = CandidateTypes[0].vector_begin(),
7141 VecEnd = CandidateTypes[0].vector_end();
7142 Vec != VecEnd; ++Vec) {
7143 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007144 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007145 }
7146 }
7147
7148 // C++ [over.built]p8:
7149 // For every type T, there exist candidate operator functions of
7150 // the form
7151 //
7152 // T* operator+(T*);
7153 void addUnaryPlusPointerOverloads() {
7154 for (BuiltinCandidateTypeSet::iterator
7155 Ptr = CandidateTypes[0].pointer_begin(),
7156 PtrEnd = CandidateTypes[0].pointer_end();
7157 Ptr != PtrEnd; ++Ptr) {
7158 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007159 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007160 }
7161 }
7162
7163 // C++ [over.built]p10:
7164 // For every promoted integral type T, there exist candidate
7165 // operator functions of the form
7166 //
7167 // T operator~(T);
7168 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007169 if (!HasArithmeticOrEnumeralCandidateType)
7170 return;
7171
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007172 for (unsigned Int = FirstPromotedIntegralType;
7173 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007174 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007175 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007176 }
7177
7178 // Extension: We also add this operator for vector types.
7179 for (BuiltinCandidateTypeSet::iterator
7180 Vec = CandidateTypes[0].vector_begin(),
7181 VecEnd = CandidateTypes[0].vector_end();
7182 Vec != VecEnd; ++Vec) {
7183 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007184 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007185 }
7186 }
7187
7188 // C++ [over.match.oper]p16:
7189 // For every pointer to member type T, there exist candidate operator
7190 // functions of the form
7191 //
7192 // bool operator==(T,T);
7193 // bool operator!=(T,T);
7194 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7195 /// Set of (canonical) types that we've already handled.
7196 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7197
Richard Smithe54c3072013-05-05 15:51:06 +00007198 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007199 for (BuiltinCandidateTypeSet::iterator
7200 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7201 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7202 MemPtr != MemPtrEnd;
7203 ++MemPtr) {
7204 // Don't add the same builtin candidate twice.
7205 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7206 continue;
7207
7208 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007209 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007210 }
7211 }
7212 }
7213
7214 // C++ [over.built]p15:
7215 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007216 // For every T, where T is an enumeration type, a pointer type, or
7217 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007218 //
7219 // bool operator<(T, T);
7220 // bool operator>(T, T);
7221 // bool operator<=(T, T);
7222 // bool operator>=(T, T);
7223 // bool operator==(T, T);
7224 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007225 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007226 // C++ [over.match.oper]p3:
7227 // [...]the built-in candidates include all of the candidate operator
7228 // functions defined in 13.6 that, compared to the given operator, [...]
7229 // do not have the same parameter-type-list as any non-template non-member
7230 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007231 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007232 // Note that in practice, this only affects enumeration types because there
7233 // aren't any built-in candidates of record type, and a user-defined operator
7234 // must have an operand of record or enumeration type. Also, the only other
7235 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007236 // cannot be overloaded for enumeration types, so this is the only place
7237 // where we must suppress candidates like this.
7238 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7239 UserDefinedBinaryOperators;
7240
Richard Smithe54c3072013-05-05 15:51:06 +00007241 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007242 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7243 CandidateTypes[ArgIdx].enumeration_end()) {
7244 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7245 CEnd = CandidateSet.end();
7246 C != CEnd; ++C) {
7247 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7248 continue;
7249
Eli Friedman14f082b2012-09-18 21:52:24 +00007250 if (C->Function->isFunctionTemplateSpecialization())
7251 continue;
7252
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007253 QualType FirstParamType =
7254 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7255 QualType SecondParamType =
7256 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7257
7258 // Skip if either parameter isn't of enumeral type.
7259 if (!FirstParamType->isEnumeralType() ||
7260 !SecondParamType->isEnumeralType())
7261 continue;
7262
7263 // Add this operator to the set of known user-defined operators.
7264 UserDefinedBinaryOperators.insert(
7265 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7266 S.Context.getCanonicalType(SecondParamType)));
7267 }
7268 }
7269 }
7270
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007271 /// Set of (canonical) types that we've already handled.
7272 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7273
Richard Smithe54c3072013-05-05 15:51:06 +00007274 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007275 for (BuiltinCandidateTypeSet::iterator
7276 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7277 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7278 Ptr != PtrEnd; ++Ptr) {
7279 // Don't add the same builtin candidate twice.
7280 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7281 continue;
7282
7283 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007284 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007285 }
7286 for (BuiltinCandidateTypeSet::iterator
7287 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7288 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7289 Enum != EnumEnd; ++Enum) {
7290 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7291
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007292 // Don't add the same builtin candidate twice, or if a user defined
7293 // candidate exists.
7294 if (!AddedTypes.insert(CanonType) ||
7295 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7296 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007297 continue;
7298
7299 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007300 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007301 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007302
7303 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7304 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7305 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007306 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007307 NullPtrTy))) {
7308 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007309 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007310 CandidateSet);
7311 }
7312 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007313 }
7314 }
7315
7316 // C++ [over.built]p13:
7317 //
7318 // For every cv-qualified or cv-unqualified object type T
7319 // there exist candidate operator functions of the form
7320 //
7321 // T* operator+(T*, ptrdiff_t);
7322 // T& operator[](T*, ptrdiff_t); [BELOW]
7323 // T* operator-(T*, ptrdiff_t);
7324 // T* operator+(ptrdiff_t, T*);
7325 // T& operator[](ptrdiff_t, T*); [BELOW]
7326 //
7327 // C++ [over.built]p14:
7328 //
7329 // For every T, where T is a pointer to object type, there
7330 // exist candidate operator functions of the form
7331 //
7332 // ptrdiff_t operator-(T, T);
7333 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7334 /// Set of (canonical) types that we've already handled.
7335 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7336
7337 for (int Arg = 0; Arg < 2; ++Arg) {
7338 QualType AsymetricParamTypes[2] = {
7339 S.Context.getPointerDiffType(),
7340 S.Context.getPointerDiffType(),
7341 };
7342 for (BuiltinCandidateTypeSet::iterator
7343 Ptr = CandidateTypes[Arg].pointer_begin(),
7344 PtrEnd = CandidateTypes[Arg].pointer_end();
7345 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007346 QualType PointeeTy = (*Ptr)->getPointeeType();
7347 if (!PointeeTy->isObjectType())
7348 continue;
7349
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007350 AsymetricParamTypes[Arg] = *Ptr;
7351 if (Arg == 0 || Op == OO_Plus) {
7352 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7353 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007354 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007355 }
7356 if (Op == OO_Minus) {
7357 // ptrdiff_t operator-(T, T);
7358 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7359 continue;
7360
7361 QualType ParamTypes[2] = { *Ptr, *Ptr };
7362 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007363 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007364 }
7365 }
7366 }
7367 }
7368
7369 // C++ [over.built]p12:
7370 //
7371 // For every pair of promoted arithmetic types L and R, there
7372 // exist candidate operator functions of the form
7373 //
7374 // LR operator*(L, R);
7375 // LR operator/(L, R);
7376 // LR operator+(L, R);
7377 // LR operator-(L, R);
7378 // bool operator<(L, R);
7379 // bool operator>(L, R);
7380 // bool operator<=(L, R);
7381 // bool operator>=(L, R);
7382 // bool operator==(L, R);
7383 // bool operator!=(L, R);
7384 //
7385 // where LR is the result of the usual arithmetic conversions
7386 // between types L and R.
7387 //
7388 // C++ [over.built]p24:
7389 //
7390 // For every pair of promoted arithmetic types L and R, there exist
7391 // candidate operator functions of the form
7392 //
7393 // LR operator?(bool, L, R);
7394 //
7395 // where LR is the result of the usual arithmetic conversions
7396 // between types L and R.
7397 // Our candidates ignore the first parameter.
7398 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007399 if (!HasArithmeticOrEnumeralCandidateType)
7400 return;
7401
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007402 for (unsigned Left = FirstPromotedArithmeticType;
7403 Left < LastPromotedArithmeticType; ++Left) {
7404 for (unsigned Right = FirstPromotedArithmeticType;
7405 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007406 QualType LandR[2] = { getArithmeticType(Left),
7407 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007408 QualType Result =
7409 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007410 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007411 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007412 }
7413 }
7414
7415 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7416 // conditional operator for vector types.
7417 for (BuiltinCandidateTypeSet::iterator
7418 Vec1 = CandidateTypes[0].vector_begin(),
7419 Vec1End = CandidateTypes[0].vector_end();
7420 Vec1 != Vec1End; ++Vec1) {
7421 for (BuiltinCandidateTypeSet::iterator
7422 Vec2 = CandidateTypes[1].vector_begin(),
7423 Vec2End = CandidateTypes[1].vector_end();
7424 Vec2 != Vec2End; ++Vec2) {
7425 QualType LandR[2] = { *Vec1, *Vec2 };
7426 QualType Result = S.Context.BoolTy;
7427 if (!isComparison) {
7428 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7429 Result = *Vec1;
7430 else
7431 Result = *Vec2;
7432 }
7433
Richard Smithe54c3072013-05-05 15:51:06 +00007434 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007435 }
7436 }
7437 }
7438
7439 // C++ [over.built]p17:
7440 //
7441 // For every pair of promoted integral types L and R, there
7442 // exist candidate operator functions of the form
7443 //
7444 // LR operator%(L, R);
7445 // LR operator&(L, R);
7446 // LR operator^(L, R);
7447 // LR operator|(L, R);
7448 // L operator<<(L, R);
7449 // L operator>>(L, R);
7450 //
7451 // where LR is the result of the usual arithmetic conversions
7452 // between types L and R.
7453 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007454 if (!HasArithmeticOrEnumeralCandidateType)
7455 return;
7456
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007457 for (unsigned Left = FirstPromotedIntegralType;
7458 Left < LastPromotedIntegralType; ++Left) {
7459 for (unsigned Right = FirstPromotedIntegralType;
7460 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007461 QualType LandR[2] = { getArithmeticType(Left),
7462 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007463 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7464 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007465 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007466 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007467 }
7468 }
7469 }
7470
7471 // C++ [over.built]p20:
7472 //
7473 // For every pair (T, VQ), where T is an enumeration or
7474 // pointer to member type and VQ is either volatile or
7475 // empty, there exist candidate operator functions of the form
7476 //
7477 // VQ T& operator=(VQ T&, T);
7478 void addAssignmentMemberPointerOrEnumeralOverloads() {
7479 /// Set of (canonical) types that we've already handled.
7480 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7481
7482 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7483 for (BuiltinCandidateTypeSet::iterator
7484 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7485 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7486 Enum != EnumEnd; ++Enum) {
7487 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7488 continue;
7489
Richard Smithe54c3072013-05-05 15:51:06 +00007490 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007491 }
7492
7493 for (BuiltinCandidateTypeSet::iterator
7494 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7495 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7496 MemPtr != MemPtrEnd; ++MemPtr) {
7497 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7498 continue;
7499
Richard Smithe54c3072013-05-05 15:51:06 +00007500 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007501 }
7502 }
7503 }
7504
7505 // C++ [over.built]p19:
7506 //
7507 // For every pair (T, VQ), where T is any type and VQ is either
7508 // volatile or empty, there exist candidate operator functions
7509 // of the form
7510 //
7511 // T*VQ& operator=(T*VQ&, T*);
7512 //
7513 // C++ [over.built]p21:
7514 //
7515 // For every pair (T, VQ), where T is a cv-qualified or
7516 // cv-unqualified object type and VQ is either volatile or
7517 // empty, there exist candidate operator functions of the form
7518 //
7519 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7520 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7521 void addAssignmentPointerOverloads(bool isEqualOp) {
7522 /// Set of (canonical) types that we've already handled.
7523 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7524
7525 for (BuiltinCandidateTypeSet::iterator
7526 Ptr = CandidateTypes[0].pointer_begin(),
7527 PtrEnd = CandidateTypes[0].pointer_end();
7528 Ptr != PtrEnd; ++Ptr) {
7529 // If this is operator=, keep track of the builtin candidates we added.
7530 if (isEqualOp)
7531 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007532 else if (!(*Ptr)->getPointeeType()->isObjectType())
7533 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007534
7535 // non-volatile version
7536 QualType ParamTypes[2] = {
7537 S.Context.getLValueReferenceType(*Ptr),
7538 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7539 };
Richard Smithe54c3072013-05-05 15:51:06 +00007540 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007541 /*IsAssigmentOperator=*/ isEqualOp);
7542
Douglas Gregor5bee2582012-06-04 00:15:09 +00007543 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7544 VisibleTypeConversionsQuals.hasVolatile();
7545 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007546 // volatile version
7547 ParamTypes[0] =
7548 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007549 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007550 /*IsAssigmentOperator=*/isEqualOp);
7551 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007552
7553 if (!(*Ptr).isRestrictQualified() &&
7554 VisibleTypeConversionsQuals.hasRestrict()) {
7555 // restrict version
7556 ParamTypes[0]
7557 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007558 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007559 /*IsAssigmentOperator=*/isEqualOp);
7560
7561 if (NeedVolatile) {
7562 // volatile restrict version
7563 ParamTypes[0]
7564 = S.Context.getLValueReferenceType(
7565 S.Context.getCVRQualifiedType(*Ptr,
7566 (Qualifiers::Volatile |
7567 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007568 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007569 /*IsAssigmentOperator=*/isEqualOp);
7570 }
7571 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007572 }
7573
7574 if (isEqualOp) {
7575 for (BuiltinCandidateTypeSet::iterator
7576 Ptr = CandidateTypes[1].pointer_begin(),
7577 PtrEnd = CandidateTypes[1].pointer_end();
7578 Ptr != PtrEnd; ++Ptr) {
7579 // Make sure we don't add the same candidate twice.
7580 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7581 continue;
7582
Chandler Carruth8e543b32010-12-12 08:17:55 +00007583 QualType ParamTypes[2] = {
7584 S.Context.getLValueReferenceType(*Ptr),
7585 *Ptr,
7586 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007587
7588 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007589 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007590 /*IsAssigmentOperator=*/true);
7591
Douglas Gregor5bee2582012-06-04 00:15:09 +00007592 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7593 VisibleTypeConversionsQuals.hasVolatile();
7594 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007595 // volatile version
7596 ParamTypes[0] =
7597 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007598 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7599 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007600 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007601
7602 if (!(*Ptr).isRestrictQualified() &&
7603 VisibleTypeConversionsQuals.hasRestrict()) {
7604 // restrict version
7605 ParamTypes[0]
7606 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007607 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7608 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007609
7610 if (NeedVolatile) {
7611 // volatile restrict version
7612 ParamTypes[0]
7613 = S.Context.getLValueReferenceType(
7614 S.Context.getCVRQualifiedType(*Ptr,
7615 (Qualifiers::Volatile |
7616 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007617 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7618 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007619 }
7620 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007621 }
7622 }
7623 }
7624
7625 // C++ [over.built]p18:
7626 //
7627 // For every triple (L, VQ, R), where L is an arithmetic type,
7628 // VQ is either volatile or empty, and R is a promoted
7629 // arithmetic type, there exist candidate operator functions of
7630 // the form
7631 //
7632 // VQ L& operator=(VQ L&, R);
7633 // VQ L& operator*=(VQ L&, R);
7634 // VQ L& operator/=(VQ L&, R);
7635 // VQ L& operator+=(VQ L&, R);
7636 // VQ L& operator-=(VQ L&, R);
7637 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007638 if (!HasArithmeticOrEnumeralCandidateType)
7639 return;
7640
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007641 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7642 for (unsigned Right = FirstPromotedArithmeticType;
7643 Right < LastPromotedArithmeticType; ++Right) {
7644 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007645 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007646
7647 // Add this built-in operator as a candidate (VQ is empty).
7648 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007649 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007650 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007651 /*IsAssigmentOperator=*/isEqualOp);
7652
7653 // Add this built-in operator as a candidate (VQ is 'volatile').
7654 if (VisibleTypeConversionsQuals.hasVolatile()) {
7655 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007656 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007657 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007658 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007659 /*IsAssigmentOperator=*/isEqualOp);
7660 }
7661 }
7662 }
7663
7664 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7665 for (BuiltinCandidateTypeSet::iterator
7666 Vec1 = CandidateTypes[0].vector_begin(),
7667 Vec1End = CandidateTypes[0].vector_end();
7668 Vec1 != Vec1End; ++Vec1) {
7669 for (BuiltinCandidateTypeSet::iterator
7670 Vec2 = CandidateTypes[1].vector_begin(),
7671 Vec2End = CandidateTypes[1].vector_end();
7672 Vec2 != Vec2End; ++Vec2) {
7673 QualType ParamTypes[2];
7674 ParamTypes[1] = *Vec2;
7675 // Add this built-in operator as a candidate (VQ is empty).
7676 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
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 // Add this built-in operator as a candidate (VQ is 'volatile').
7681 if (VisibleTypeConversionsQuals.hasVolatile()) {
7682 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7683 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007684 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007685 /*IsAssigmentOperator=*/isEqualOp);
7686 }
7687 }
7688 }
7689 }
7690
7691 // C++ [over.built]p22:
7692 //
7693 // For every triple (L, VQ, R), where L is an integral type, VQ
7694 // is either volatile or empty, and R is a promoted integral
7695 // type, there exist candidate operator functions of the form
7696 //
7697 // VQ L& operator%=(VQ L&, R);
7698 // VQ L& operator<<=(VQ L&, R);
7699 // VQ L& operator>>=(VQ L&, R);
7700 // VQ L& operator&=(VQ L&, R);
7701 // VQ L& operator^=(VQ L&, R);
7702 // VQ L& operator|=(VQ L&, R);
7703 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007704 if (!HasArithmeticOrEnumeralCandidateType)
7705 return;
7706
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007707 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7708 for (unsigned Right = FirstPromotedIntegralType;
7709 Right < LastPromotedIntegralType; ++Right) {
7710 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007711 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007712
7713 // Add this built-in operator as a candidate (VQ is empty).
7714 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007715 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007716 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007717 if (VisibleTypeConversionsQuals.hasVolatile()) {
7718 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007719 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007720 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7721 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007722 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007723 }
7724 }
7725 }
7726 }
7727
7728 // C++ [over.operator]p23:
7729 //
7730 // There also exist candidate operator functions of the form
7731 //
7732 // bool operator!(bool);
7733 // bool operator&&(bool, bool);
7734 // bool operator||(bool, bool);
7735 void addExclaimOverload() {
7736 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007737 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007738 /*IsAssignmentOperator=*/false,
7739 /*NumContextualBoolArguments=*/1);
7740 }
7741 void addAmpAmpOrPipePipeOverload() {
7742 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007743 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007744 /*IsAssignmentOperator=*/false,
7745 /*NumContextualBoolArguments=*/2);
7746 }
7747
7748 // C++ [over.built]p13:
7749 //
7750 // For every cv-qualified or cv-unqualified object type T there
7751 // exist candidate operator functions of the form
7752 //
7753 // T* operator+(T*, ptrdiff_t); [ABOVE]
7754 // T& operator[](T*, ptrdiff_t);
7755 // T* operator-(T*, ptrdiff_t); [ABOVE]
7756 // T* operator+(ptrdiff_t, T*); [ABOVE]
7757 // T& operator[](ptrdiff_t, T*);
7758 void addSubscriptOverloads() {
7759 for (BuiltinCandidateTypeSet::iterator
7760 Ptr = CandidateTypes[0].pointer_begin(),
7761 PtrEnd = CandidateTypes[0].pointer_end();
7762 Ptr != PtrEnd; ++Ptr) {
7763 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7764 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007765 if (!PointeeType->isObjectType())
7766 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007767
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007768 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7769
7770 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007771 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007772 }
7773
7774 for (BuiltinCandidateTypeSet::iterator
7775 Ptr = CandidateTypes[1].pointer_begin(),
7776 PtrEnd = CandidateTypes[1].pointer_end();
7777 Ptr != PtrEnd; ++Ptr) {
7778 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7779 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007780 if (!PointeeType->isObjectType())
7781 continue;
7782
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007783 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7784
7785 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007786 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007787 }
7788 }
7789
7790 // C++ [over.built]p11:
7791 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7792 // C1 is the same type as C2 or is a derived class of C2, T is an object
7793 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7794 // there exist candidate operator functions of the form
7795 //
7796 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7797 //
7798 // where CV12 is the union of CV1 and CV2.
7799 void addArrowStarOverloads() {
7800 for (BuiltinCandidateTypeSet::iterator
7801 Ptr = CandidateTypes[0].pointer_begin(),
7802 PtrEnd = CandidateTypes[0].pointer_end();
7803 Ptr != PtrEnd; ++Ptr) {
7804 QualType C1Ty = (*Ptr);
7805 QualType C1;
7806 QualifierCollector Q1;
7807 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7808 if (!isa<RecordType>(C1))
7809 continue;
7810 // heuristic to reduce number of builtin candidates in the set.
7811 // Add volatile/restrict version only if there are conversions to a
7812 // volatile/restrict type.
7813 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7814 continue;
7815 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7816 continue;
7817 for (BuiltinCandidateTypeSet::iterator
7818 MemPtr = CandidateTypes[1].member_pointer_begin(),
7819 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7820 MemPtr != MemPtrEnd; ++MemPtr) {
7821 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7822 QualType C2 = QualType(mptr->getClass(), 0);
7823 C2 = C2.getUnqualifiedType();
7824 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7825 break;
7826 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7827 // build CV12 T&
7828 QualType T = mptr->getPointeeType();
7829 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7830 T.isVolatileQualified())
7831 continue;
7832 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7833 T.isRestrictQualified())
7834 continue;
7835 T = Q1.apply(S.Context, T);
7836 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007837 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007838 }
7839 }
7840 }
7841
7842 // Note that we don't consider the first argument, since it has been
7843 // contextually converted to bool long ago. The candidates below are
7844 // therefore added as binary.
7845 //
7846 // C++ [over.built]p25:
7847 // For every type T, where T is a pointer, pointer-to-member, or scoped
7848 // enumeration type, there exist candidate operator functions of the form
7849 //
7850 // T operator?(bool, T, T);
7851 //
7852 void addConditionalOperatorOverloads() {
7853 /// Set of (canonical) types that we've already handled.
7854 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7855
7856 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7857 for (BuiltinCandidateTypeSet::iterator
7858 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7859 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7860 Ptr != PtrEnd; ++Ptr) {
7861 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7862 continue;
7863
7864 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007865 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007866 }
7867
7868 for (BuiltinCandidateTypeSet::iterator
7869 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7870 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7871 MemPtr != MemPtrEnd; ++MemPtr) {
7872 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7873 continue;
7874
7875 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007876 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007877 }
7878
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007879 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007880 for (BuiltinCandidateTypeSet::iterator
7881 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7882 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7883 Enum != EnumEnd; ++Enum) {
7884 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7885 continue;
7886
7887 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7888 continue;
7889
7890 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007891 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007892 }
7893 }
7894 }
7895 }
7896};
7897
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007898} // end anonymous namespace
7899
7900/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7901/// operator overloads to the candidate set (C++ [over.built]), based
7902/// on the operator @p Op and the arguments given. For example, if the
7903/// operator is a binary '+', this routine might add "int
7904/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00007905void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7906 SourceLocation OpLoc,
7907 ArrayRef<Expr *> Args,
7908 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007909 // Find all of the types that the arguments can convert to, but only
7910 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007911 // that make use of these types. Also record whether we encounter non-record
7912 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007913 Qualifiers VisibleTypeConversionsQuals;
7914 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00007915 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007916 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007917
7918 bool HasNonRecordCandidateType = false;
7919 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007920 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00007921 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007922 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7923 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7924 OpLoc,
7925 true,
7926 (Op == OO_Exclaim ||
7927 Op == OO_AmpAmp ||
7928 Op == OO_PipePipe),
7929 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007930 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7931 CandidateTypes[ArgIdx].hasNonRecordTypes();
7932 HasArithmeticOrEnumeralCandidateType =
7933 HasArithmeticOrEnumeralCandidateType ||
7934 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007935 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007936
Chandler Carruth00a38332010-12-13 01:44:01 +00007937 // Exit early when no non-record types have been added to the candidate set
7938 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007939 //
7940 // We can't exit early for !, ||, or &&, since there we have always have
7941 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007942 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007943 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007944 return;
7945
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007946 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007947 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007948 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007949 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007950 CandidateTypes, CandidateSet);
7951
7952 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007953 switch (Op) {
7954 case OO_None:
7955 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007956 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007957
Chandler Carruth5184de02010-12-12 08:51:33 +00007958 case OO_New:
7959 case OO_Delete:
7960 case OO_Array_New:
7961 case OO_Array_Delete:
7962 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007963 llvm_unreachable(
7964 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007965
7966 case OO_Comma:
7967 case OO_Arrow:
7968 // C++ [over.match.oper]p3:
7969 // -- For the operator ',', the unary operator '&', or the
7970 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007971 break;
7972
7973 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007974 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007975 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007976 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007977
7978 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007979 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007980 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007981 } else {
7982 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7983 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7984 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007985 break;
7986
Chandler Carruth5184de02010-12-12 08:51:33 +00007987 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007988 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007989 OpBuilder.addUnaryStarPointerOverloads();
7990 else
7991 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7992 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993
Chandler Carruth5184de02010-12-12 08:51:33 +00007994 case OO_Slash:
7995 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007996 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007997
7998 case OO_PlusPlus:
7999 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008000 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
8001 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00008002 break;
8003
Douglas Gregor84605ae2009-08-24 13:43:27 +00008004 case OO_EqualEqual:
8005 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008006 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008007 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00008008
Douglas Gregora11693b2008-11-12 17:17:38 +00008009 case OO_Less:
8010 case OO_Greater:
8011 case OO_LessEqual:
8012 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00008013 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00008014 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
8015 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008016
Douglas Gregora11693b2008-11-12 17:17:38 +00008017 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00008018 case OO_Caret:
8019 case OO_Pipe:
8020 case OO_LessLess:
8021 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008022 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00008023 break;
8024
Chandler Carruth5184de02010-12-12 08:51:33 +00008025 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00008026 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00008027 // C++ [over.match.oper]p3:
8028 // -- For the operator ',', the unary operator '&', or the
8029 // operator '->', the built-in candidates set is empty.
8030 break;
8031
8032 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8033 break;
8034
8035 case OO_Tilde:
8036 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8037 break;
8038
Douglas Gregora11693b2008-11-12 17:17:38 +00008039 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008040 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008041 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008042
8043 case OO_PlusEqual:
8044 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008045 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008046 // Fall through.
8047
8048 case OO_StarEqual:
8049 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008050 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008051 break;
8052
8053 case OO_PercentEqual:
8054 case OO_LessLessEqual:
8055 case OO_GreaterGreaterEqual:
8056 case OO_AmpEqual:
8057 case OO_CaretEqual:
8058 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008059 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008060 break;
8061
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008062 case OO_Exclaim:
8063 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008064 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008065
Douglas Gregora11693b2008-11-12 17:17:38 +00008066 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008067 case OO_PipePipe:
8068 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008069 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008070
8071 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008072 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008073 break;
8074
8075 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008076 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008077 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008078
8079 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008080 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008081 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8082 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008083 }
8084}
8085
Douglas Gregore254f902009-02-04 00:32:51 +00008086/// \brief Add function candidates found via argument-dependent lookup
8087/// to the set of overloading candidates.
8088///
8089/// This routine performs argument-dependent name lookup based on the
8090/// given function name (which may also be an operator name) and adds
8091/// all of the overload candidates found by ADL to the overload
8092/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008093void
Douglas Gregore254f902009-02-04 00:32:51 +00008094Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00008095 bool Operator, SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008096 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008097 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008098 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008099 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008100 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008101
John McCall91f61fc2010-01-26 06:04:06 +00008102 // FIXME: This approach for uniquing ADL results (and removing
8103 // redundant candidates from the set) relies on pointer-equality,
8104 // which means we need to key off the canonical decl. However,
8105 // always going back to the canonical decl might not get us the
8106 // right set of default arguments. What default arguments are
8107 // we supposed to consider on ADL candidates, anyway?
8108
Douglas Gregorcabea402009-09-22 15:41:20 +00008109 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00008110 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008111
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008112 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008113 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8114 CandEnd = CandidateSet.end();
8115 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008116 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008117 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008118 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008119 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008120 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008121
8122 // For each of the ADL candidates we found, add it to the overload
8123 // set.
John McCall8fe68082010-01-26 07:16:45 +00008124 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008125 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008126 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008127 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008128 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008129
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008130 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8131 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008132 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008133 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008134 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008135 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008136 }
Douglas Gregore254f902009-02-04 00:32:51 +00008137}
8138
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008139/// isBetterOverloadCandidate - Determines whether the first overload
8140/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008141bool
John McCall5c32be02010-08-24 20:38:10 +00008142isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008143 const OverloadCandidate &Cand1,
8144 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008145 SourceLocation Loc,
8146 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008147 // Define viable functions to be better candidates than non-viable
8148 // functions.
8149 if (!Cand2.Viable)
8150 return Cand1.Viable;
8151 else if (!Cand1.Viable)
8152 return false;
8153
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008154 // C++ [over.match.best]p1:
8155 //
8156 // -- if F is a static member function, ICS1(F) is defined such
8157 // that ICS1(F) is neither better nor worse than ICS1(G) for
8158 // any function G, and, symmetrically, ICS1(G) is neither
8159 // better nor worse than ICS1(F).
8160 unsigned StartArg = 0;
8161 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8162 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008163
Douglas Gregord3cb3562009-07-07 23:38:56 +00008164 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008165 // A viable function F1 is defined to be a better function than another
8166 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008167 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008168 unsigned NumArgs = Cand1.NumConversions;
8169 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008170 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008171 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008172 switch (CompareImplicitConversionSequences(S,
8173 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008174 Cand2.Conversions[ArgIdx])) {
8175 case ImplicitConversionSequence::Better:
8176 // Cand1 has a better conversion sequence.
8177 HasBetterConversion = true;
8178 break;
8179
8180 case ImplicitConversionSequence::Worse:
8181 // Cand1 can't be better than Cand2.
8182 return false;
8183
8184 case ImplicitConversionSequence::Indistinguishable:
8185 // Do nothing.
8186 break;
8187 }
8188 }
8189
Mike Stump11289f42009-09-09 15:08:12 +00008190 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008191 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008192 if (HasBetterConversion)
8193 return true;
8194
Mike Stump11289f42009-09-09 15:08:12 +00008195 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00008196 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00008197 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00008198 Cand2.Function && Cand2.Function->getPrimaryTemplate())
8199 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008200
8201 // -- F1 and F2 are function template specializations, and the function
8202 // template for F1 is more specialized than the template for F2
8203 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00008204 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00008205 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00008206 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00008207 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00008208 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8209 Cand2.Function->getPrimaryTemplate(),
8210 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008211 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00008212 : TPOC_Call,
Richard Smithe5b52202013-09-11 00:52:39 +00008213 Cand1.ExplicitCallArguments,
8214 Cand2.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00008215 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00008216 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008217
Douglas Gregora1f013e2008-11-07 22:36:19 +00008218 // -- the context is an initialization by user-defined conversion
8219 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8220 // from the return type of F1 to the destination type (i.e.,
8221 // the type of the entity being initialized) is a better
8222 // conversion sequence than the standard conversion sequence
8223 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008224 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008225 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008226 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008227 // First check whether we prefer one of the conversion functions over the
8228 // other. This only distinguishes the results in non-standard, extension
8229 // cases such as the conversion from a lambda closure type to a function
8230 // pointer or block.
8231 ImplicitConversionSequence::CompareKind FuncResult
8232 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8233 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8234 return FuncResult;
8235
John McCall5c32be02010-08-24 20:38:10 +00008236 switch (CompareStandardConversionSequences(S,
8237 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00008238 Cand2.FinalConversion)) {
8239 case ImplicitConversionSequence::Better:
8240 // Cand1 has a better conversion sequence.
8241 return true;
8242
8243 case ImplicitConversionSequence::Worse:
8244 // Cand1 can't be better than Cand2.
8245 return false;
8246
8247 case ImplicitConversionSequence::Indistinguishable:
8248 // Do nothing
8249 break;
8250 }
8251 }
8252
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008253 // Check for enable_if value-based overload resolution.
8254 if (Cand1.Function && Cand2.Function &&
8255 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8256 Cand2.Function->hasAttr<EnableIfAttr>())) {
8257 // FIXME: The next several lines are just
8258 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8259 // instead of reverse order which is how they're stored in the AST.
8260 AttrVec Cand1Attrs;
8261 AttrVec::iterator Cand1E = Cand1Attrs.end();
8262 if (Cand1.Function->hasAttrs()) {
8263 Cand1Attrs = Cand1.Function->getAttrs();
8264 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8265 IsNotEnableIfAttr);
8266 std::reverse(Cand1Attrs.begin(), Cand1E);
8267 }
8268
8269 AttrVec Cand2Attrs;
8270 AttrVec::iterator Cand2E = Cand2Attrs.end();
8271 if (Cand2.Function->hasAttrs()) {
8272 Cand2Attrs = Cand2.Function->getAttrs();
8273 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8274 IsNotEnableIfAttr);
8275 std::reverse(Cand2Attrs.begin(), Cand2E);
8276 }
8277 for (AttrVec::iterator
8278 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin();
8279 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) {
8280 if (Cand1I == Cand1E)
8281 return false;
8282 if (Cand2I == Cand2E)
8283 return true;
8284 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8285 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID,
8286 S.getASTContext(), true);
8287 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID,
8288 S.getASTContext(), true);
8289 if (!(Cand1ID == Cand2ID))
8290 return false;
8291 }
8292 }
8293
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008294 return false;
8295}
8296
Mike Stump11289f42009-09-09 15:08:12 +00008297/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008298/// within an overload candidate set.
8299///
James Dennettffad8b72012-06-22 08:10:18 +00008300/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008301/// which overload resolution occurs.
8302///
James Dennettffad8b72012-06-22 08:10:18 +00008303/// \param Best If overload resolution was successful or found a deleted
8304/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008305///
8306/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008307OverloadingResult
8308OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008309 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008310 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008311 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008312 Best = end();
8313 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8314 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008315 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008316 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008317 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008318 }
8319
8320 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008321 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008322 return OR_No_Viable_Function;
8323
8324 // Make sure that this function is better than every other viable
8325 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008326 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008327 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008328 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008329 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008330 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008331 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008332 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008333 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008334 }
Mike Stump11289f42009-09-09 15:08:12 +00008335
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008336 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008337 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008338 (Best->Function->isDeleted() ||
8339 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008340 return OR_Deleted;
8341
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008342 return OR_Success;
8343}
8344
John McCall53262c92010-01-12 02:15:36 +00008345namespace {
8346
8347enum OverloadCandidateKind {
8348 oc_function,
8349 oc_method,
8350 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008351 oc_function_template,
8352 oc_method_template,
8353 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008354 oc_implicit_default_constructor,
8355 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008356 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008357 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008358 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008359 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008360};
8361
John McCalle1ac8d12010-01-13 00:25:19 +00008362OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8363 FunctionDecl *Fn,
8364 std::string &Description) {
8365 bool isTemplate = false;
8366
8367 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8368 isTemplate = true;
8369 Description = S.getTemplateArgumentBindingsText(
8370 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8371 }
John McCallfd0b2f82010-01-06 09:43:14 +00008372
8373 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008374 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008375 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008376
Sebastian Redl08905022011-02-05 19:23:19 +00008377 if (Ctor->getInheritedConstructor())
8378 return oc_implicit_inherited_constructor;
8379
Alexis Hunt119c10e2011-05-25 23:16:36 +00008380 if (Ctor->isDefaultConstructor())
8381 return oc_implicit_default_constructor;
8382
8383 if (Ctor->isMoveConstructor())
8384 return oc_implicit_move_constructor;
8385
8386 assert(Ctor->isCopyConstructor() &&
8387 "unexpected sort of implicit constructor");
8388 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008389 }
8390
8391 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8392 // This actually gets spelled 'candidate function' for now, but
8393 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008394 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008395 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008396
Alexis Hunt119c10e2011-05-25 23:16:36 +00008397 if (Meth->isMoveAssignmentOperator())
8398 return oc_implicit_move_assignment;
8399
Douglas Gregor12695102012-02-10 08:36:38 +00008400 if (Meth->isCopyAssignmentOperator())
8401 return oc_implicit_copy_assignment;
8402
8403 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8404 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008405 }
8406
John McCalle1ac8d12010-01-13 00:25:19 +00008407 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008408}
8409
Larisse Voufo98b20f12013-07-19 23:00:19 +00008410void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008411 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8412 if (!Ctor) return;
8413
8414 Ctor = Ctor->getInheritedConstructor();
8415 if (!Ctor) return;
8416
8417 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8418}
8419
John McCall53262c92010-01-12 02:15:36 +00008420} // end anonymous namespace
8421
8422// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008423void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008424 std::string FnDesc;
8425 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008426 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8427 << (unsigned) K << FnDesc;
8428 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8429 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008430 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008431}
8432
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008433// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008434// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008435void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008436 assert(OverloadedExpr->getType() == Context.OverloadTy);
8437
8438 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8439 OverloadExpr *OvlExpr = Ovl.Expression;
8440
8441 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8442 IEnd = OvlExpr->decls_end();
8443 I != IEnd; ++I) {
8444 if (FunctionTemplateDecl *FunTmpl =
8445 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008446 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008447 } else if (FunctionDecl *Fun
8448 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008449 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008450 }
8451 }
8452}
8453
John McCall0d1da222010-01-12 00:44:57 +00008454/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8455/// "lead" diagnostic; it will be given two arguments, the source and
8456/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008457void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8458 Sema &S,
8459 SourceLocation CaretLoc,
8460 const PartialDiagnostic &PDiag) const {
8461 S.Diag(CaretLoc, PDiag)
8462 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008463 // FIXME: The note limiting machinery is borrowed from
8464 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8465 // refactoring here.
8466 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8467 unsigned CandsShown = 0;
8468 AmbiguousConversionSequence::const_iterator I, E;
8469 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8470 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8471 break;
8472 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008473 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008474 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008475 if (I != E)
8476 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008477}
8478
John McCall0d1da222010-01-12 00:44:57 +00008479namespace {
8480
John McCall6a61b522010-01-13 09:16:55 +00008481void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8482 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8483 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008484 assert(Cand->Function && "for now, candidate must be a function");
8485 FunctionDecl *Fn = Cand->Function;
8486
8487 // There's a conversion slot for the object argument if this is a
8488 // non-constructor method. Note that 'I' corresponds the
8489 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008490 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008491 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008492 if (I == 0)
8493 isObjectArgument = true;
8494 else
8495 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008496 }
8497
John McCalle1ac8d12010-01-13 00:25:19 +00008498 std::string FnDesc;
8499 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8500
John McCall6a61b522010-01-13 09:16:55 +00008501 Expr *FromExpr = Conv.Bad.FromExpr;
8502 QualType FromTy = Conv.Bad.getFromType();
8503 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008504
John McCallfb7ad0f2010-02-02 02:42:52 +00008505 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008506 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008507 Expr *E = FromExpr->IgnoreParens();
8508 if (isa<UnaryOperator>(E))
8509 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008510 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008511
8512 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8513 << (unsigned) FnKind << FnDesc
8514 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8515 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008516 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008517 return;
8518 }
8519
John McCall6d174642010-01-23 08:10:49 +00008520 // Do some hand-waving analysis to see if the non-viability is due
8521 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008522 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8523 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8524 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8525 CToTy = RT->getPointeeType();
8526 else {
8527 // TODO: detect and diagnose the full richness of const mismatches.
8528 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8529 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8530 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8531 }
8532
8533 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8534 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008535 Qualifiers FromQs = CFromTy.getQualifiers();
8536 Qualifiers ToQs = CToTy.getQualifiers();
8537
8538 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8539 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8540 << (unsigned) FnKind << FnDesc
8541 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8542 << FromTy
8543 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8544 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008545 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008546 return;
8547 }
8548
John McCall31168b02011-06-15 23:02:42 +00008549 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008550 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008551 << (unsigned) FnKind << FnDesc
8552 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8553 << FromTy
8554 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8555 << (unsigned) isObjectArgument << I+1;
8556 MaybeEmitInheritedConstructorNote(S, Fn);
8557 return;
8558 }
8559
Douglas Gregoraec25842011-04-26 23:16:46 +00008560 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8561 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8562 << (unsigned) FnKind << FnDesc
8563 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8564 << FromTy
8565 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8566 << (unsigned) isObjectArgument << I+1;
8567 MaybeEmitInheritedConstructorNote(S, Fn);
8568 return;
8569 }
8570
John McCall47000992010-01-14 03:28:57 +00008571 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8572 assert(CVR && "unexpected qualifiers mismatch");
8573
8574 if (isObjectArgument) {
8575 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8576 << (unsigned) FnKind << FnDesc
8577 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8578 << FromTy << (CVR - 1);
8579 } else {
8580 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8581 << (unsigned) FnKind << FnDesc
8582 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8583 << FromTy << (CVR - 1) << I+1;
8584 }
Sebastian Redl08905022011-02-05 19:23:19 +00008585 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008586 return;
8587 }
8588
Sebastian Redla72462c2011-09-24 17:48:32 +00008589 // Special diagnostic for failure to convert an initializer list, since
8590 // telling the user that it has type void is not useful.
8591 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8592 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8593 << (unsigned) FnKind << FnDesc
8594 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8595 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8596 MaybeEmitInheritedConstructorNote(S, Fn);
8597 return;
8598 }
8599
John McCall6d174642010-01-23 08:10:49 +00008600 // Diagnose references or pointers to incomplete types differently,
8601 // since it's far from impossible that the incompleteness triggered
8602 // the failure.
8603 QualType TempFromTy = FromTy.getNonReferenceType();
8604 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8605 TempFromTy = PTy->getPointeeType();
8606 if (TempFromTy->isIncompleteType()) {
8607 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8608 << (unsigned) FnKind << FnDesc
8609 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8610 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008611 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008612 return;
8613 }
8614
Douglas Gregor56f2e342010-06-30 23:01:39 +00008615 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008616 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008617 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8618 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8619 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8620 FromPtrTy->getPointeeType()) &&
8621 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8622 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008623 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008624 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008625 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008626 }
8627 } else if (const ObjCObjectPointerType *FromPtrTy
8628 = FromTy->getAs<ObjCObjectPointerType>()) {
8629 if (const ObjCObjectPointerType *ToPtrTy
8630 = ToTy->getAs<ObjCObjectPointerType>())
8631 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8632 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8633 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8634 FromPtrTy->getPointeeType()) &&
8635 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008636 BaseToDerivedConversion = 2;
8637 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008638 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8639 !FromTy->isIncompleteType() &&
8640 !ToRefTy->getPointeeType()->isIncompleteType() &&
8641 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8642 BaseToDerivedConversion = 3;
8643 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8644 ToTy.getNonReferenceType().getCanonicalType() ==
8645 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8647 << (unsigned) FnKind << FnDesc
8648 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8649 << (unsigned) isObjectArgument << I + 1;
8650 MaybeEmitInheritedConstructorNote(S, Fn);
8651 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008652 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008653 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008654
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008655 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008656 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008657 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008658 << (unsigned) FnKind << FnDesc
8659 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008660 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008661 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008662 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008663 return;
8664 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008665
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008666 if (isa<ObjCObjectPointerType>(CFromTy) &&
8667 isa<PointerType>(CToTy)) {
8668 Qualifiers FromQs = CFromTy.getQualifiers();
8669 Qualifiers ToQs = CToTy.getQualifiers();
8670 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8671 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8672 << (unsigned) FnKind << FnDesc
8673 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8674 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8675 MaybeEmitInheritedConstructorNote(S, Fn);
8676 return;
8677 }
8678 }
8679
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008680 // Emit the generic diagnostic and, optionally, add the hints to it.
8681 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8682 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008683 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008684 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8685 << (unsigned) (Cand->Fix.Kind);
8686
8687 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008688 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8689 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008690 FDiag << *HI;
8691 S.Diag(Fn->getLocation(), FDiag);
8692
Sebastian Redl08905022011-02-05 19:23:19 +00008693 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008694}
8695
Larisse Voufo98b20f12013-07-19 23:00:19 +00008696/// Additional arity mismatch diagnosis specific to a function overload
8697/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8698/// over a candidate in any candidate set.
8699bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8700 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008701 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008702 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008703
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008704 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008705 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008706 // right number of arguments, because only overloaded operators have
8707 // the weird behavior of overloading member and non-member functions.
8708 // Just don't report anything.
8709 if (Fn->isInvalidDecl() &&
8710 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008711 return true;
8712
8713 if (NumArgs < MinParams) {
8714 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8715 (Cand->FailureKind == ovl_fail_bad_deduction &&
8716 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8717 } else {
8718 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8719 (Cand->FailureKind == ovl_fail_bad_deduction &&
8720 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8721 }
8722
8723 return false;
8724}
8725
8726/// General arity mismatch diagnosis over a candidate in a candidate set.
8727void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8728 assert(isa<FunctionDecl>(D) &&
8729 "The templated declaration should at least be a function"
8730 " when diagnosing bad template argument deduction due to too many"
8731 " or too few arguments");
8732
8733 FunctionDecl *Fn = cast<FunctionDecl>(D);
8734
8735 // TODO: treat calls to a missing default constructor as a special case
8736 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8737 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008738
John McCall6a61b522010-01-13 09:16:55 +00008739 // at least / at most / exactly
8740 unsigned mode, modeCount;
8741 if (NumFormalArgs < MinParams) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008742 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008743 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008744 mode = 0; // "at least"
8745 else
8746 mode = 2; // "exactly"
8747 modeCount = MinParams;
8748 } else {
John McCall6a61b522010-01-13 09:16:55 +00008749 if (MinParams != FnTy->getNumArgs())
8750 mode = 1; // "at most"
8751 else
8752 mode = 2; // "exactly"
8753 modeCount = FnTy->getNumArgs();
8754 }
8755
8756 std::string Description;
8757 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8758
Richard Smith10ff50d2012-05-11 05:16:41 +00008759 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8760 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8761 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8762 << Fn->getParamDecl(0) << NumFormalArgs;
8763 else
8764 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8765 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8766 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008767 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008768}
8769
Larisse Voufo98b20f12013-07-19 23:00:19 +00008770/// Arity mismatch diagnosis specific to a function overload candidate.
8771void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8772 unsigned NumFormalArgs) {
8773 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8774 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8775}
Larisse Voufo47c08452013-07-19 22:53:23 +00008776
Larisse Voufo98b20f12013-07-19 23:00:19 +00008777TemplateDecl *getDescribedTemplate(Decl *Templated) {
8778 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8779 return FD->getDescribedFunctionTemplate();
8780 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8781 return RD->getDescribedClassTemplate();
8782
8783 llvm_unreachable("Unsupported: Getting the described template declaration"
8784 " for bad deduction diagnosis");
8785}
8786
8787/// Diagnose a failed template-argument deduction.
8788void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8789 DeductionFailureInfo &DeductionFailure,
8790 unsigned NumArgs) {
8791 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008792 NamedDecl *ParamD;
8793 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8794 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8795 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008796 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008797 case Sema::TDK_Success:
8798 llvm_unreachable("TDK_success while diagnosing bad deduction");
8799
8800 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008801 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008802 S.Diag(Templated->getLocation(),
8803 diag::note_ovl_candidate_incomplete_deduction)
8804 << ParamD->getDeclName();
8805 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008806 return;
8807 }
8808
John McCall42d7d192010-08-05 09:05:08 +00008809 case Sema::TDK_Underqualified: {
8810 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8811 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8812
Larisse Voufo98b20f12013-07-19 23:00:19 +00008813 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008814
8815 // Param will have been canonicalized, but it should just be a
8816 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008817 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008818 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008819 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008820 assert(S.Context.hasSameType(Param, NonCanonParam));
8821
8822 // Arg has also been canonicalized, but there's nothing we can do
8823 // about that. It also doesn't matter as much, because it won't
8824 // have any template parameters in it (because deduction isn't
8825 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008826 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008827
Larisse Voufo98b20f12013-07-19 23:00:19 +00008828 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8829 << ParamD->getDeclName() << Arg << NonCanonParam;
8830 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008831 return;
8832 }
8833
8834 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008835 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008836 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008837 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008838 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008839 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008840 which = 1;
8841 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008842 which = 2;
8843 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008844
Larisse Voufo98b20f12013-07-19 23:00:19 +00008845 S.Diag(Templated->getLocation(),
8846 diag::note_ovl_candidate_inconsistent_deduction)
8847 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8848 << *DeductionFailure.getSecondArg();
8849 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008850 return;
8851 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008852
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008853 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008854 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008855 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008856 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008857 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008858 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008859 else {
8860 int index = 0;
8861 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8862 index = TTP->getIndex();
8863 else if (NonTypeTemplateParmDecl *NTTP
8864 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8865 index = NTTP->getIndex();
8866 else
8867 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008868 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008869 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008870 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008871 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008872 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008873 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008874
Douglas Gregor02eb4832010-05-08 18:13:28 +00008875 case Sema::TDK_TooManyArguments:
8876 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008877 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008878 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008879
8880 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008881 S.Diag(Templated->getLocation(),
8882 diag::note_ovl_candidate_instantiation_depth);
8883 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008884 return;
8885
8886 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008887 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008888 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008889 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008890 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008891 TemplateArgString = " ";
8892 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00008893 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00008894 }
8895
Richard Smith6f8d2c62012-05-09 05:17:00 +00008896 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008897 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008898 if (PDiag && PDiag->second.getDiagID() ==
8899 diag::err_typename_nested_not_found_enable_if) {
8900 // FIXME: Use the source range of the condition, and the fully-qualified
8901 // name of the enable_if template. These are both present in PDiag.
8902 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8903 << "'enable_if'" << TemplateArgString;
8904 return;
8905 }
8906
Richard Smith9ca64612012-05-07 09:03:25 +00008907 // Format the SFINAE diagnostic into the argument string.
8908 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8909 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008910 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008911 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008912 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008913 SFINAEArgString = ": ";
8914 R = SourceRange(PDiag->first, PDiag->first);
8915 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8916 }
8917
Larisse Voufo98b20f12013-07-19 23:00:19 +00008918 S.Diag(Templated->getLocation(),
8919 diag::note_ovl_candidate_substitution_failure)
8920 << TemplateArgString << SFINAEArgString << R;
8921 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008922 return;
8923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008924
Richard Smith8c6eeb92013-01-31 04:03:12 +00008925 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008926 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8927 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00008928 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008929 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00008930 return;
8931 }
8932
Richard Trieue3732352013-04-08 21:11:40 +00008933 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00008934 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008935 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8936 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00008937 if (FirstTA.getKind() == TemplateArgument::Template &&
8938 SecondTA.getKind() == TemplateArgument::Template) {
8939 TemplateName FirstTN = FirstTA.getAsTemplate();
8940 TemplateName SecondTN = SecondTA.getAsTemplate();
8941 if (FirstTN.getKind() == TemplateName::Template &&
8942 SecondTN.getKind() == TemplateName::Template) {
8943 if (FirstTN.getAsTemplateDecl()->getName() ==
8944 SecondTN.getAsTemplateDecl()->getName()) {
8945 // FIXME: This fixes a bad diagnostic where both templates are named
8946 // the same. This particular case is a bit difficult since:
8947 // 1) It is passed as a string to the diagnostic printer.
8948 // 2) The diagnostic printer only attempts to find a better
8949 // name for types, not decls.
8950 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008951 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00008952 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8953 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8954 return;
8955 }
8956 }
8957 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00008958 // FIXME: For generic lambda parameters, check if the function is a lambda
8959 // call operator, and if so, emit a prettier and more informative
8960 // diagnostic that mentions 'auto' and lambda in addition to
8961 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008962 S.Diag(Templated->getLocation(),
8963 diag::note_ovl_candidate_non_deduced_mismatch)
8964 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00008965 return;
Richard Trieue3732352013-04-08 21:11:40 +00008966 }
John McCall8b9ed552010-02-01 18:53:26 +00008967 // TODO: diagnose these individually, then kill off
8968 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00008969 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008970 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8971 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008972 return;
8973 }
8974}
8975
Larisse Voufo98b20f12013-07-19 23:00:19 +00008976/// Diagnose a failed template-argument deduction, for function calls.
8977void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8978 unsigned TDK = Cand->DeductionFailure.Result;
8979 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8980 if (CheckArityMismatch(S, Cand, NumArgs))
8981 return;
8982 }
8983 DiagnoseBadDeduction(S, Cand->Function, // pattern
8984 Cand->DeductionFailure, NumArgs);
8985}
8986
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008987/// CUDA: diagnose an invalid call across targets.
8988void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8989 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8990 FunctionDecl *Callee = Cand->Function;
8991
8992 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8993 CalleeTarget = S.IdentifyCUDATarget(Callee);
8994
8995 std::string FnDesc;
8996 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8997
8998 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8999 << (unsigned) FnKind << CalleeTarget << CallerTarget;
9000}
9001
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009002void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
9003 FunctionDecl *Callee = Cand->Function;
9004 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
9005
9006 S.Diag(Callee->getLocation(),
9007 diag::note_ovl_candidate_disabled_by_enable_if_attr)
9008 << Attr->getCond()->getSourceRange() << Attr->getMessage();
9009}
9010
John McCall8b9ed552010-02-01 18:53:26 +00009011/// Generates a 'note' diagnostic for an overload candidate. We've
9012/// already generated a primary error at the call site.
9013///
9014/// It really does need to be a single diagnostic with its caret
9015/// pointed at the candidate declaration. Yes, this creates some
9016/// major challenges of technical writing. Yes, this makes pointing
9017/// out problems with specific arguments quite awkward. It's still
9018/// better than generating twenty screens of text for every failed
9019/// overload.
9020///
9021/// It would be great to be able to express per-candidate problems
9022/// more richly for those diagnostic clients that cared, but we'd
9023/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00009024void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009025 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00009026 FunctionDecl *Fn = Cand->Function;
9027
John McCall12f97bc2010-01-08 04:41:39 +00009028 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009029 if (Cand->Viable && (Fn->isDeleted() ||
9030 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009031 std::string FnDesc;
9032 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009033
9034 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009035 << FnKind << FnDesc
9036 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009037 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009038 return;
John McCall12f97bc2010-01-08 04:41:39 +00009039 }
9040
John McCalle1ac8d12010-01-13 00:25:19 +00009041 // We don't really have anything else to say about viable candidates.
9042 if (Cand->Viable) {
9043 S.NoteOverloadCandidate(Fn);
9044 return;
9045 }
John McCall0d1da222010-01-12 00:44:57 +00009046
John McCall6a61b522010-01-13 09:16:55 +00009047 switch (Cand->FailureKind) {
9048 case ovl_fail_too_many_arguments:
9049 case ovl_fail_too_few_arguments:
9050 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009051
John McCall6a61b522010-01-13 09:16:55 +00009052 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009053 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009054
John McCallfe796dd2010-01-23 05:17:32 +00009055 case ovl_fail_trivial_conversion:
9056 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009057 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009058 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009059
John McCall65eb8792010-02-25 01:37:24 +00009060 case ovl_fail_bad_conversion: {
9061 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009062 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009063 if (Cand->Conversions[I].isBad())
9064 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009065
John McCall6a61b522010-01-13 09:16:55 +00009066 // FIXME: this currently happens when we're called from SemaInit
9067 // when user-conversion overload fails. Figure out how to handle
9068 // those conditions and diagnose them well.
9069 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009070 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009071
9072 case ovl_fail_bad_target:
9073 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009074
9075 case ovl_fail_enable_if:
9076 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009077 }
John McCalld3224162010-01-08 00:58:21 +00009078}
9079
9080void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9081 // Desugar the type of the surrogate down to a function type,
9082 // retaining as many typedefs as possible while still showing
9083 // the function type (and, therefore, its parameter types).
9084 QualType FnType = Cand->Surrogate->getConversionType();
9085 bool isLValueReference = false;
9086 bool isRValueReference = false;
9087 bool isPointer = false;
9088 if (const LValueReferenceType *FnTypeRef =
9089 FnType->getAs<LValueReferenceType>()) {
9090 FnType = FnTypeRef->getPointeeType();
9091 isLValueReference = true;
9092 } else if (const RValueReferenceType *FnTypeRef =
9093 FnType->getAs<RValueReferenceType>()) {
9094 FnType = FnTypeRef->getPointeeType();
9095 isRValueReference = true;
9096 }
9097 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9098 FnType = FnTypePtr->getPointeeType();
9099 isPointer = true;
9100 }
9101 // Desugar down to a function type.
9102 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9103 // Reconstruct the pointer/reference as appropriate.
9104 if (isPointer) FnType = S.Context.getPointerType(FnType);
9105 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9106 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9107
9108 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9109 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009110 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009111}
9112
9113void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009114 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009115 SourceLocation OpLoc,
9116 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009117 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009118 std::string TypeStr("operator");
9119 TypeStr += Opc;
9120 TypeStr += "(";
9121 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009122 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009123 TypeStr += ")";
9124 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9125 } else {
9126 TypeStr += ", ";
9127 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9128 TypeStr += ")";
9129 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9130 }
9131}
9132
9133void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9134 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009135 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009136 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9137 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009138 if (ICS.isBad()) break; // all meaningless after first invalid
9139 if (!ICS.isAmbiguous()) continue;
9140
John McCall5c32be02010-08-24 20:38:10 +00009141 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009142 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009143 }
9144}
9145
Larisse Voufo98b20f12013-07-19 23:00:19 +00009146static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009147 if (Cand->Function)
9148 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009149 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009150 return Cand->Surrogate->getLocation();
9151 return SourceLocation();
9152}
9153
Larisse Voufo98b20f12013-07-19 23:00:19 +00009154static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009155 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009156 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009157 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009158
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009159 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009160 case Sema::TDK_Incomplete:
9161 return 1;
9162
9163 case Sema::TDK_Underqualified:
9164 case Sema::TDK_Inconsistent:
9165 return 2;
9166
9167 case Sema::TDK_SubstitutionFailure:
9168 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009169 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009170 return 3;
9171
9172 case Sema::TDK_InstantiationDepth:
9173 case Sema::TDK_FailedOverloadResolution:
9174 return 4;
9175
9176 case Sema::TDK_InvalidExplicitArguments:
9177 return 5;
9178
9179 case Sema::TDK_TooManyArguments:
9180 case Sema::TDK_TooFewArguments:
9181 return 6;
9182 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009183 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009184}
9185
John McCallad2587a2010-01-12 00:48:53 +00009186struct CompareOverloadCandidatesForDisplay {
9187 Sema &S;
9188 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00009189
9190 bool operator()(const OverloadCandidate *L,
9191 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009192 // Fast-path this check.
9193 if (L == R) return false;
9194
John McCall12f97bc2010-01-08 04:41:39 +00009195 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009196 if (L->Viable) {
9197 if (!R->Viable) return true;
9198
9199 // TODO: introduce a tri-valued comparison for overload
9200 // candidates. Would be more worthwhile if we had a sort
9201 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009202 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9203 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009204 } else if (R->Viable)
9205 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009206
John McCall3712d9e2010-01-15 23:32:50 +00009207 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009208
John McCall3712d9e2010-01-15 23:32:50 +00009209 // Criteria by which we can sort non-viable candidates:
9210 if (!L->Viable) {
9211 // 1. Arity mismatches come after other candidates.
9212 if (L->FailureKind == ovl_fail_too_many_arguments ||
9213 L->FailureKind == ovl_fail_too_few_arguments)
9214 return false;
9215 if (R->FailureKind == ovl_fail_too_many_arguments ||
9216 R->FailureKind == ovl_fail_too_few_arguments)
9217 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009218
John McCallfe796dd2010-01-23 05:17:32 +00009219 // 2. Bad conversions come first and are ordered by the number
9220 // of bad conversions and quality of good conversions.
9221 if (L->FailureKind == ovl_fail_bad_conversion) {
9222 if (R->FailureKind != ovl_fail_bad_conversion)
9223 return true;
9224
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009225 // The conversion that can be fixed with a smaller number of changes,
9226 // comes first.
9227 unsigned numLFixes = L->Fix.NumConversionsFixed;
9228 unsigned numRFixes = R->Fix.NumConversionsFixed;
9229 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9230 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009231 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009232 if (numLFixes < numRFixes)
9233 return true;
9234 else
9235 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009236 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009237
John McCallfe796dd2010-01-23 05:17:32 +00009238 // If there's any ordering between the defined conversions...
9239 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009240 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009241
9242 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009243 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009244 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009245 switch (CompareImplicitConversionSequences(S,
9246 L->Conversions[I],
9247 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009248 case ImplicitConversionSequence::Better:
9249 leftBetter++;
9250 break;
9251
9252 case ImplicitConversionSequence::Worse:
9253 leftBetter--;
9254 break;
9255
9256 case ImplicitConversionSequence::Indistinguishable:
9257 break;
9258 }
9259 }
9260 if (leftBetter > 0) return true;
9261 if (leftBetter < 0) return false;
9262
9263 } else if (R->FailureKind == ovl_fail_bad_conversion)
9264 return false;
9265
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009266 if (L->FailureKind == ovl_fail_bad_deduction) {
9267 if (R->FailureKind != ovl_fail_bad_deduction)
9268 return true;
9269
9270 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9271 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009272 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009273 } else if (R->FailureKind == ovl_fail_bad_deduction)
9274 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009275
John McCall3712d9e2010-01-15 23:32:50 +00009276 // TODO: others?
9277 }
9278
9279 // Sort everything else by location.
9280 SourceLocation LLoc = GetLocationForCandidate(L);
9281 SourceLocation RLoc = GetLocationForCandidate(R);
9282
9283 // Put candidates without locations (e.g. builtins) at the end.
9284 if (LLoc.isInvalid()) return false;
9285 if (RLoc.isInvalid()) return true;
9286
9287 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009288 }
9289};
9290
John McCallfe796dd2010-01-23 05:17:32 +00009291/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009292/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009293void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009294 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009295 assert(!Cand->Viable);
9296
9297 // Don't do anything on failures other than bad conversion.
9298 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9299
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009300 // We only want the FixIts if all the arguments can be corrected.
9301 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009302 // Use a implicit copy initialization to check conversion fixes.
9303 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009304
John McCallfe796dd2010-01-23 05:17:32 +00009305 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009306 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009307 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009308 while (true) {
9309 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9310 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009311 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009312 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009313 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009314 }
John McCallfe796dd2010-01-23 05:17:32 +00009315 }
9316
9317 if (ConvIdx == ConvCount)
9318 return;
9319
John McCall65eb8792010-02-25 01:37:24 +00009320 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9321 "remaining conversion is initialized?");
9322
Douglas Gregoradc7a702010-04-16 17:45:54 +00009323 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009324 // operation somehow.
9325 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009326
9327 const FunctionProtoType* Proto;
9328 unsigned ArgIdx = ConvIdx;
9329
9330 if (Cand->IsSurrogate) {
9331 QualType ConvType
9332 = Cand->Surrogate->getConversionType().getNonReferenceType();
9333 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9334 ConvType = ConvPtrType->getPointeeType();
9335 Proto = ConvType->getAs<FunctionProtoType>();
9336 ArgIdx--;
9337 } else if (Cand->Function) {
9338 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9339 if (isa<CXXMethodDecl>(Cand->Function) &&
9340 !isa<CXXConstructorDecl>(Cand->Function))
9341 ArgIdx--;
9342 } else {
9343 // Builtin binary operator with a bad first conversion.
9344 assert(ConvCount <= 3);
9345 for (; ConvIdx != ConvCount; ++ConvIdx)
9346 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009347 = TryCopyInitialization(S, Args[ConvIdx],
9348 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009349 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009350 /*InOverloadResolution*/ true,
9351 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009352 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009353 return;
9354 }
9355
9356 // Fill in the rest of the conversions.
9357 unsigned NumArgsInProto = Proto->getNumArgs();
9358 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009359 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00009360 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009361 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009362 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009363 /*InOverloadResolution=*/true,
9364 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009365 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009366 // Store the FixIt in the candidate if it exists.
9367 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009368 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009369 }
John McCallfe796dd2010-01-23 05:17:32 +00009370 else
9371 Cand->Conversions[ConvIdx].setEllipsis();
9372 }
9373}
9374
John McCalld3224162010-01-08 00:58:21 +00009375} // end anonymous namespace
9376
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009377/// PrintOverloadCandidates - When overload resolution fails, prints
9378/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009379/// set.
John McCall5c32be02010-08-24 20:38:10 +00009380void OverloadCandidateSet::NoteCandidates(Sema &S,
9381 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009382 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009383 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009384 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009385 // Sort the candidates by viability and position. Sorting directly would
9386 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009387 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009388 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9389 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009390 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009391 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009392 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009393 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009394 if (Cand->Function || Cand->IsSurrogate)
9395 Cands.push_back(Cand);
9396 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9397 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009398 }
9399 }
9400
John McCallad2587a2010-01-12 00:48:53 +00009401 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00009402 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009403
John McCall0d1da222010-01-12 00:44:57 +00009404 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009405
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009406 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009407 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009408 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009409 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9410 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009411
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009412 // Set an arbitrary limit on the number of candidate functions we'll spam
9413 // the user with. FIXME: This limit should depend on details of the
9414 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009415 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009416 break;
9417 }
9418 ++CandsShown;
9419
John McCalld3224162010-01-08 00:58:21 +00009420 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009421 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009422 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009423 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009424 else {
9425 assert(Cand->Viable &&
9426 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009427 // Generally we only see ambiguities including viable builtin
9428 // operators if overload resolution got screwed up by an
9429 // ambiguous user-defined conversion.
9430 //
9431 // FIXME: It's quite possible for different conversions to see
9432 // different ambiguities, though.
9433 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009434 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009435 ReportedAmbiguousConversions = true;
9436 }
John McCalld3224162010-01-08 00:58:21 +00009437
John McCall0d1da222010-01-12 00:44:57 +00009438 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009439 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009440 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009441 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009442
9443 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009444 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009445}
9446
Larisse Voufo98b20f12013-07-19 23:00:19 +00009447static SourceLocation
9448GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9449 return Cand->Specialization ? Cand->Specialization->getLocation()
9450 : SourceLocation();
9451}
9452
9453struct CompareTemplateSpecCandidatesForDisplay {
9454 Sema &S;
9455 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9456
9457 bool operator()(const TemplateSpecCandidate *L,
9458 const TemplateSpecCandidate *R) {
9459 // Fast-path this check.
9460 if (L == R)
9461 return false;
9462
9463 // Assuming that both candidates are not matches...
9464
9465 // Sort by the ranking of deduction failures.
9466 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9467 return RankDeductionFailure(L->DeductionFailure) <
9468 RankDeductionFailure(R->DeductionFailure);
9469
9470 // Sort everything else by location.
9471 SourceLocation LLoc = GetLocationForCandidate(L);
9472 SourceLocation RLoc = GetLocationForCandidate(R);
9473
9474 // Put candidates without locations (e.g. builtins) at the end.
9475 if (LLoc.isInvalid())
9476 return false;
9477 if (RLoc.isInvalid())
9478 return true;
9479
9480 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9481 }
9482};
9483
9484/// Diagnose a template argument deduction failure.
9485/// We are treating these failures as overload failures due to bad
9486/// deductions.
9487void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9488 DiagnoseBadDeduction(S, Specialization, // pattern
9489 DeductionFailure, /*NumArgs=*/0);
9490}
9491
9492void TemplateSpecCandidateSet::destroyCandidates() {
9493 for (iterator i = begin(), e = end(); i != e; ++i) {
9494 i->DeductionFailure.Destroy();
9495 }
9496}
9497
9498void TemplateSpecCandidateSet::clear() {
9499 destroyCandidates();
9500 Candidates.clear();
9501}
9502
9503/// NoteCandidates - When no template specialization match is found, prints
9504/// diagnostic messages containing the non-matching specializations that form
9505/// the candidate set.
9506/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9507/// OCD == OCD_AllCandidates and Cand->Viable == false.
9508void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9509 // Sort the candidates by position (assuming no candidate is a match).
9510 // Sorting directly would be prohibitive, so we make a set of pointers
9511 // and sort those.
9512 SmallVector<TemplateSpecCandidate *, 32> Cands;
9513 Cands.reserve(size());
9514 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9515 if (Cand->Specialization)
9516 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009517 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009518 // in general, want to list every possible builtin candidate.
9519 }
9520
9521 std::sort(Cands.begin(), Cands.end(),
9522 CompareTemplateSpecCandidatesForDisplay(S));
9523
9524 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9525 // for generalization purposes (?).
9526 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9527
9528 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9529 unsigned CandsShown = 0;
9530 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9531 TemplateSpecCandidate *Cand = *I;
9532
9533 // Set an arbitrary limit on the number of candidates we'll spam
9534 // the user with. FIXME: This limit should depend on details of the
9535 // candidate list.
9536 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9537 break;
9538 ++CandsShown;
9539
9540 assert(Cand->Specialization &&
9541 "Non-matching built-in candidates are not added to Cands.");
9542 Cand->NoteDeductionFailure(S);
9543 }
9544
9545 if (I != E)
9546 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9547}
9548
Douglas Gregorb491ed32011-02-19 21:32:49 +00009549// [PossiblyAFunctionType] --> [Return]
9550// NonFunctionType --> NonFunctionType
9551// R (A) --> R(A)
9552// R (*)(A) --> R (A)
9553// R (&)(A) --> R (A)
9554// R (S::*)(A) --> R (A)
9555QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9556 QualType Ret = PossiblyAFunctionType;
9557 if (const PointerType *ToTypePtr =
9558 PossiblyAFunctionType->getAs<PointerType>())
9559 Ret = ToTypePtr->getPointeeType();
9560 else if (const ReferenceType *ToTypeRef =
9561 PossiblyAFunctionType->getAs<ReferenceType>())
9562 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009563 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009564 PossiblyAFunctionType->getAs<MemberPointerType>())
9565 Ret = MemTypePtr->getPointeeType();
9566 Ret =
9567 Context.getCanonicalType(Ret).getUnqualifiedType();
9568 return Ret;
9569}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009570
Douglas Gregorb491ed32011-02-19 21:32:49 +00009571// A helper class to help with address of function resolution
9572// - allows us to avoid passing around all those ugly parameters
9573class AddressOfFunctionResolver
9574{
9575 Sema& S;
9576 Expr* SourceExpr;
9577 const QualType& TargetType;
9578 QualType TargetFunctionType; // Extracted function type from target type
9579
9580 bool Complain;
9581 //DeclAccessPair& ResultFunctionAccessPair;
9582 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009583
Douglas Gregorb491ed32011-02-19 21:32:49 +00009584 bool TargetTypeIsNonStaticMemberFunction;
9585 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009586 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009587
Douglas Gregorb491ed32011-02-19 21:32:49 +00009588 OverloadExpr::FindResult OvlExprInfo;
9589 OverloadExpr *OvlExpr;
9590 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009591 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009592 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009593
Douglas Gregorb491ed32011-02-19 21:32:49 +00009594public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009595 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9596 const QualType &TargetType, bool Complain)
9597 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9598 Complain(Complain), Context(S.getASTContext()),
9599 TargetTypeIsNonStaticMemberFunction(
9600 !!TargetType->getAs<MemberPointerType>()),
9601 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009602 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009603 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9604 OvlExpr(OvlExprInfo.Expression),
9605 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009606 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009607
David Majnemera4f7c7a2013-08-01 06:13:59 +00009608 if (TargetFunctionType->isFunctionType()) {
9609 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9610 if (!UME->isImplicitAccess() &&
9611 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9612 StaticMemberFunctionFromBoundPointer = true;
9613 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9614 DeclAccessPair dap;
9615 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9616 OvlExpr, false, &dap)) {
9617 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9618 if (!Method->isStatic()) {
9619 // If the target type is a non-function type and the function found
9620 // is a non-static member function, pretend as if that was the
9621 // target, it's the only possible type to end up with.
9622 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009623
David Majnemera4f7c7a2013-08-01 06:13:59 +00009624 // And skip adding the function if its not in the proper form.
9625 // We'll diagnose this due to an empty set of functions.
9626 if (!OvlExprInfo.HasFormOfMemberPointer)
9627 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009628 }
9629
David Majnemera4f7c7a2013-08-01 06:13:59 +00009630 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009631 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009632 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009633 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009634
9635 if (OvlExpr->hasExplicitTemplateArgs())
9636 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009637
Douglas Gregorb491ed32011-02-19 21:32:49 +00009638 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9639 // C++ [over.over]p4:
9640 // If more than one function is selected, [...]
9641 if (Matches.size() > 1) {
9642 if (FoundNonTemplateFunction)
9643 EliminateAllTemplateMatches();
9644 else
9645 EliminateAllExceptMostSpecializedTemplate();
9646 }
9647 }
9648 }
9649
9650private:
9651 bool isTargetTypeAFunction() const {
9652 return TargetFunctionType->isFunctionType();
9653 }
9654
9655 // [ToType] [Return]
9656
9657 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9658 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9659 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9660 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9661 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9662 }
9663
9664 // return true if any matching specializations were found
9665 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9666 const DeclAccessPair& CurAccessFunPair) {
9667 if (CXXMethodDecl *Method
9668 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9669 // Skip non-static function templates when converting to pointer, and
9670 // static when converting to member pointer.
9671 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9672 return false;
9673 }
9674 else if (TargetTypeIsNonStaticMemberFunction)
9675 return false;
9676
9677 // C++ [over.over]p2:
9678 // If the name is a function template, template argument deduction is
9679 // done (14.8.2.2), and if the argument deduction succeeds, the
9680 // resulting template argument list is used to generate a single
9681 // function template specialization, which is added to the set of
9682 // overloaded functions considered.
9683 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009684 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009685 if (Sema::TemplateDeductionResult Result
9686 = S.DeduceTemplateArguments(FunctionTemplate,
9687 &OvlExplicitTemplateArgs,
9688 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009689 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009690 // Make a note of the failed deduction for diagnostics.
9691 FailedCandidates.addCandidate()
9692 .set(FunctionTemplate->getTemplatedDecl(),
9693 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009694 return false;
9695 }
9696
Douglas Gregor19a41f12013-04-17 08:45:07 +00009697 // Template argument deduction ensures that we have an exact match or
9698 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009699 // This function template specicalization works.
9700 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009701 assert(S.isSameOrCompatibleFunctionType(
9702 Context.getCanonicalType(Specialization->getType()),
9703 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009704 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9705 return true;
9706 }
9707
9708 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9709 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009710 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009711 // Skip non-static functions when converting to pointer, and static
9712 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009713 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9714 return false;
9715 }
9716 else if (TargetTypeIsNonStaticMemberFunction)
9717 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009718
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009719 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009720 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009721 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9722 if (S.CheckCUDATarget(Caller, FunDecl))
9723 return false;
9724
Richard Smith2a7d4812013-05-04 07:00:32 +00009725 // If any candidate has a placeholder return type, trigger its deduction
9726 // now.
9727 if (S.getLangOpts().CPlusPlus1y &&
9728 FunDecl->getResultType()->isUndeducedType() &&
9729 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9730 return false;
9731
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009732 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009733 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9734 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009735 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9736 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009737 Matches.push_back(std::make_pair(CurAccessFunPair,
9738 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009739 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009740 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009741 }
Mike Stump11289f42009-09-09 15:08:12 +00009742 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009743
9744 return false;
9745 }
9746
9747 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9748 bool Ret = false;
9749
9750 // If the overload expression doesn't have the form of a pointer to
9751 // member, don't try to convert it to a pointer-to-member type.
9752 if (IsInvalidFormOfPointerToMemberFunction())
9753 return false;
9754
9755 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9756 E = OvlExpr->decls_end();
9757 I != E; ++I) {
9758 // Look through any using declarations to find the underlying function.
9759 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9760
9761 // C++ [over.over]p3:
9762 // Non-member functions and static member functions match
9763 // targets of type "pointer-to-function" or "reference-to-function."
9764 // Nonstatic member functions match targets of
9765 // type "pointer-to-member-function."
9766 // Note that according to DR 247, the containing class does not matter.
9767 if (FunctionTemplateDecl *FunctionTemplate
9768 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9769 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9770 Ret = true;
9771 }
9772 // If we have explicit template arguments supplied, skip non-templates.
9773 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9774 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9775 Ret = true;
9776 }
9777 assert(Ret || Matches.empty());
9778 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009779 }
9780
Douglas Gregorb491ed32011-02-19 21:32:49 +00009781 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009782 // [...] and any given function template specialization F1 is
9783 // eliminated if the set contains a second function template
9784 // specialization whose function template is more specialized
9785 // than the function template of F1 according to the partial
9786 // ordering rules of 14.5.5.2.
9787
9788 // The algorithm specified above is quadratic. We instead use a
9789 // two-pass algorithm (similar to the one used to identify the
9790 // best viable function in an overload set) that identifies the
9791 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009792
9793 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9794 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9795 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009796
Larisse Voufo98b20f12013-07-19 23:00:19 +00009797 // TODO: It looks like FailedCandidates does not serve much purpose
9798 // here, since the no_viable diagnostic has index 0.
9799 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009800 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009801 SourceExpr->getLocStart(), S.PDiag(),
9802 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9803 .second->getDeclName(),
9804 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9805 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009806
Douglas Gregorb491ed32011-02-19 21:32:49 +00009807 if (Result != MatchesCopy.end()) {
9808 // Make it the first and only element
9809 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9810 Matches[0].second = cast<FunctionDecl>(*Result);
9811 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009812 }
9813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009814
Douglas Gregorb491ed32011-02-19 21:32:49 +00009815 void EliminateAllTemplateMatches() {
9816 // [...] any function template specializations in the set are
9817 // eliminated if the set also contains a non-template function, [...]
9818 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9819 if (Matches[I].second->getPrimaryTemplate() == 0)
9820 ++I;
9821 else {
9822 Matches[I] = Matches[--N];
9823 Matches.set_size(N);
9824 }
9825 }
9826 }
9827
9828public:
9829 void ComplainNoMatchesFound() const {
9830 assert(Matches.empty());
9831 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9832 << OvlExpr->getName() << TargetFunctionType
9833 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009834 if (FailedCandidates.empty())
9835 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9836 else {
9837 // We have some deduction failure messages. Use them to diagnose
9838 // the function templates, and diagnose the non-template candidates
9839 // normally.
9840 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9841 IEnd = OvlExpr->decls_end();
9842 I != IEnd; ++I)
9843 if (FunctionDecl *Fun =
9844 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9845 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9846 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9847 }
9848 }
9849
Douglas Gregorb491ed32011-02-19 21:32:49 +00009850 bool IsInvalidFormOfPointerToMemberFunction() const {
9851 return TargetTypeIsNonStaticMemberFunction &&
9852 !OvlExprInfo.HasFormOfMemberPointer;
9853 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009854
Douglas Gregorb491ed32011-02-19 21:32:49 +00009855 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9856 // TODO: Should we condition this on whether any functions might
9857 // have matched, or is it more appropriate to do that in callers?
9858 // TODO: a fixit wouldn't hurt.
9859 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9860 << TargetType << OvlExpr->getSourceRange();
9861 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009862
9863 bool IsStaticMemberFunctionFromBoundPointer() const {
9864 return StaticMemberFunctionFromBoundPointer;
9865 }
9866
9867 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9868 S.Diag(OvlExpr->getLocStart(),
9869 diag::err_invalid_form_pointer_member_function)
9870 << OvlExpr->getSourceRange();
9871 }
9872
Douglas Gregorb491ed32011-02-19 21:32:49 +00009873 void ComplainOfInvalidConversion() const {
9874 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9875 << OvlExpr->getName() << TargetType;
9876 }
9877
9878 void ComplainMultipleMatchesFound() const {
9879 assert(Matches.size() > 1);
9880 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9881 << OvlExpr->getName()
9882 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009883 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009884 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009885
9886 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9887
Douglas Gregorb491ed32011-02-19 21:32:49 +00009888 int getNumMatches() const { return Matches.size(); }
9889
9890 FunctionDecl* getMatchingFunctionDecl() const {
9891 if (Matches.size() != 1) return 0;
9892 return Matches[0].second;
9893 }
9894
9895 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9896 if (Matches.size() != 1) return 0;
9897 return &Matches[0].first;
9898 }
9899};
9900
9901/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9902/// an overloaded function (C++ [over.over]), where @p From is an
9903/// expression with overloaded function type and @p ToType is the type
9904/// we're trying to resolve to. For example:
9905///
9906/// @code
9907/// int f(double);
9908/// int f(int);
9909///
9910/// int (*pfd)(double) = f; // selects f(double)
9911/// @endcode
9912///
9913/// This routine returns the resulting FunctionDecl if it could be
9914/// resolved, and NULL otherwise. When @p Complain is true, this
9915/// routine will emit diagnostics if there is an error.
9916FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009917Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9918 QualType TargetType,
9919 bool Complain,
9920 DeclAccessPair &FoundResult,
9921 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009922 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009923
9924 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9925 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009926 int NumMatches = Resolver.getNumMatches();
9927 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009928 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009929 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9930 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9931 else
9932 Resolver.ComplainNoMatchesFound();
9933 }
9934 else if (NumMatches > 1 && Complain)
9935 Resolver.ComplainMultipleMatchesFound();
9936 else if (NumMatches == 1) {
9937 Fn = Resolver.getMatchingFunctionDecl();
9938 assert(Fn);
9939 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +00009940 if (Complain) {
9941 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9942 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9943 else
9944 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9945 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009946 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009947
9948 if (pHadMultipleCandidates)
9949 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009950 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009951}
9952
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009953/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009954/// resolve that overloaded function expression down to a single function.
9955///
9956/// This routine can only resolve template-ids that refer to a single function
9957/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009958/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009959/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +00009960///
9961/// If no template-ids are found, no diagnostics are emitted and NULL is
9962/// returned.
John McCall0009fcc2011-04-26 20:42:42 +00009963FunctionDecl *
9964Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9965 bool Complain,
9966 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009967 // C++ [over.over]p1:
9968 // [...] [Note: any redundant set of parentheses surrounding the
9969 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009970 // C++ [over.over]p1:
9971 // [...] The overloaded function name can be preceded by the &
9972 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009973
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009974 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009975 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009976 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009977
9978 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009979 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009980 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009981
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009982 // Look through all of the overloaded functions, searching for one
9983 // whose type matches exactly.
9984 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009985 for (UnresolvedSetIterator I = ovl->decls_begin(),
9986 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009987 // C++0x [temp.arg.explicit]p3:
9988 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009989 // where deduction is not done, if a template argument list is
9990 // specified and it, along with any default template arguments,
9991 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009992 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009993 FunctionTemplateDecl *FunctionTemplate
9994 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009995
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009996 // C++ [over.over]p2:
9997 // If the name is a function template, template argument deduction is
9998 // done (14.8.2.2), and if the argument deduction succeeds, the
9999 // resulting template argument list is used to generate a single
10000 // function template specialization, which is added to the set of
10001 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010002 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +000010003 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010004 if (TemplateDeductionResult Result
10005 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +000010006 Specialization, Info,
10007 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +000010008 // Make a note of the failed deduction for diagnostics.
10009 // TODO: Actually use the failed-deduction info?
10010 FailedCandidates.addCandidate()
10011 .set(FunctionTemplate->getTemplatedDecl(),
10012 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010013 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010014 }
10015
John McCall0009fcc2011-04-26 20:42:42 +000010016 assert(Specialization && "no specialization and no error?");
10017
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010018 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +000010019 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +000010020 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +000010021 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
10022 << ovl->getName();
10023 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +000010024 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010025 return 0;
John McCall0009fcc2011-04-26 20:42:42 +000010026 }
Douglas Gregorb491ed32011-02-19 21:32:49 +000010027
John McCall0009fcc2011-04-26 20:42:42 +000010028 Matched = Specialization;
10029 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010031
Richard Smith2a7d4812013-05-04 07:00:32 +000010032 if (Matched && getLangOpts().CPlusPlus1y &&
10033 Matched->getResultType()->isUndeducedType() &&
10034 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10035 return 0;
10036
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010037 return Matched;
10038}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010039
Douglas Gregor1beec452011-03-12 01:48:56 +000010040
10041
10042
John McCall50a2c2c2011-10-11 23:14:30 +000010043// Resolve and fix an overloaded expression that can be resolved
10044// because it identifies a single function template specialization.
10045//
Douglas Gregor1beec452011-03-12 01:48:56 +000010046// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010047//
10048// Return true if it was logically possible to so resolve the
10049// expression, regardless of whether or not it succeeded. Always
10050// returns true if 'complain' is set.
10051bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10052 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10053 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010054 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010055 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010056 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010057
John McCall50a2c2c2011-10-11 23:14:30 +000010058 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010059
John McCall0009fcc2011-04-26 20:42:42 +000010060 DeclAccessPair found;
10061 ExprResult SingleFunctionExpression;
10062 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10063 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010064 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010065 SrcExpr = ExprError();
10066 return true;
10067 }
John McCall0009fcc2011-04-26 20:42:42 +000010068
10069 // It is only correct to resolve to an instance method if we're
10070 // resolving a form that's permitted to be a pointer to member.
10071 // Otherwise we'll end up making a bound member expression, which
10072 // is illegal in all the contexts we resolve like this.
10073 if (!ovl.HasFormOfMemberPointer &&
10074 isa<CXXMethodDecl>(fn) &&
10075 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010076 if (!complain) return false;
10077
10078 Diag(ovl.Expression->getExprLoc(),
10079 diag::err_bound_member_function)
10080 << 0 << ovl.Expression->getSourceRange();
10081
10082 // TODO: I believe we only end up here if there's a mix of
10083 // static and non-static candidates (otherwise the expression
10084 // would have 'bound member' type, not 'overload' type).
10085 // Ideally we would note which candidate was chosen and why
10086 // the static candidates were rejected.
10087 SrcExpr = ExprError();
10088 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010089 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010090
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010091 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010092 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +000010093 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +000010094
10095 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010096 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010097 SingleFunctionExpression =
10098 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +000010099 if (SingleFunctionExpression.isInvalid()) {
10100 SrcExpr = ExprError();
10101 return true;
10102 }
10103 }
John McCall0009fcc2011-04-26 20:42:42 +000010104 }
10105
10106 if (!SingleFunctionExpression.isUsable()) {
10107 if (complain) {
10108 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10109 << ovl.Expression->getName()
10110 << DestTypeForComplaining
10111 << OpRangeForComplaining
10112 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010113 NoteAllOverloadCandidates(SrcExpr.get());
10114
10115 SrcExpr = ExprError();
10116 return true;
10117 }
10118
10119 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010120 }
10121
John McCall50a2c2c2011-10-11 23:14:30 +000010122 SrcExpr = SingleFunctionExpression;
10123 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010124}
10125
Douglas Gregorcabea402009-09-22 15:41:20 +000010126/// \brief Add a single candidate to the overload set.
10127static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010128 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010129 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010130 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010131 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010132 bool PartialOverloading,
10133 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010134 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010135 if (isa<UsingShadowDecl>(Callee))
10136 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10137
Douglas Gregorcabea402009-09-22 15:41:20 +000010138 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010139 if (ExplicitTemplateArgs) {
10140 assert(!KnownValid && "Explicit template arguments?");
10141 return;
10142 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010143 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10144 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010145 return;
John McCalld14a8642009-11-21 08:51:07 +000010146 }
10147
10148 if (FunctionTemplateDecl *FuncTemplate
10149 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010150 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010151 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010152 return;
10153 }
10154
Richard Smith95ce4f62011-06-26 22:19:54 +000010155 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010156}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010157
Douglas Gregorcabea402009-09-22 15:41:20 +000010158/// \brief Add the overload candidates named by callee and/or found by argument
10159/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010160void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010161 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010162 OverloadCandidateSet &CandidateSet,
10163 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010164
10165#ifndef NDEBUG
10166 // Verify that ArgumentDependentLookup is consistent with the rules
10167 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010168 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010169 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10170 // and let Y be the lookup set produced by argument dependent
10171 // lookup (defined as follows). If X contains
10172 //
10173 // -- a declaration of a class member, or
10174 //
10175 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010176 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010177 //
10178 // -- a declaration that is neither a function or a function
10179 // template
10180 //
10181 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010182
John McCall57500772009-12-16 12:17:52 +000010183 if (ULE->requiresADL()) {
10184 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10185 E = ULE->decls_end(); I != E; ++I) {
10186 assert(!(*I)->getDeclContext()->isRecord());
10187 assert(isa<UsingShadowDecl>(*I) ||
10188 !(*I)->getDeclContext()->isFunctionOrMethod());
10189 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010190 }
10191 }
10192#endif
10193
John McCall57500772009-12-16 12:17:52 +000010194 // It would be nice to avoid this copy.
10195 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +000010196 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010197 if (ULE->hasExplicitTemplateArgs()) {
10198 ULE->copyTemplateArgumentsInto(TABuffer);
10199 ExplicitTemplateArgs = &TABuffer;
10200 }
10201
10202 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10203 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010204 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10205 CandidateSet, PartialOverloading,
10206 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010207
John McCall57500772009-12-16 12:17:52 +000010208 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +000010209 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +000010210 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010211 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010212 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010213}
John McCalld681c392009-12-16 08:11:27 +000010214
Richard Smith0603bbb2013-06-12 22:56:54 +000010215/// Determine whether a declaration with the specified name could be moved into
10216/// a different namespace.
10217static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10218 switch (Name.getCXXOverloadedOperator()) {
10219 case OO_New: case OO_Array_New:
10220 case OO_Delete: case OO_Array_Delete:
10221 return false;
10222
10223 default:
10224 return true;
10225 }
10226}
10227
Richard Smith998a5912011-06-05 22:42:48 +000010228/// Attempt to recover from an ill-formed use of a non-dependent name in a
10229/// template, where the non-dependent name was declared after the template
10230/// was defined. This is common in code written for a compilers which do not
10231/// correctly implement two-stage name lookup.
10232///
10233/// Returns true if a viable candidate was found and a diagnostic was issued.
10234static bool
10235DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10236 const CXXScopeSpec &SS, LookupResult &R,
10237 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010238 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010239 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10240 return false;
10241
10242 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010243 if (DC->isTransparentContext())
10244 continue;
10245
Richard Smith998a5912011-06-05 22:42:48 +000010246 SemaRef.LookupQualifiedName(R, DC);
10247
10248 if (!R.empty()) {
10249 R.suppressDiagnostics();
10250
10251 if (isa<CXXRecordDecl>(DC)) {
10252 // Don't diagnose names we find in classes; we get much better
10253 // diagnostics for these from DiagnoseEmptyLookup.
10254 R.clear();
10255 return false;
10256 }
10257
10258 OverloadCandidateSet Candidates(FnLoc);
10259 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10260 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010261 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010262 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010263
10264 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010265 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010266 // No viable functions. Don't bother the user with notes for functions
10267 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010268 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010269 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010270 }
Richard Smith998a5912011-06-05 22:42:48 +000010271
10272 // Find the namespaces where ADL would have looked, and suggest
10273 // declaring the function there instead.
10274 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10275 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010276 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010277 AssociatedNamespaces,
10278 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010279 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010280 if (canBeDeclaredInNamespace(R.getLookupName())) {
10281 DeclContext *Std = SemaRef.getStdNamespace();
10282 for (Sema::AssociatedNamespaceSet::iterator
10283 it = AssociatedNamespaces.begin(),
10284 end = AssociatedNamespaces.end(); it != end; ++it) {
10285 // Never suggest declaring a function within namespace 'std'.
10286 if (Std && Std->Encloses(*it))
10287 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010288
Richard Smith0603bbb2013-06-12 22:56:54 +000010289 // Never suggest declaring a function within a namespace with a
10290 // reserved name, like __gnu_cxx.
10291 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10292 if (NS &&
10293 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10294 continue;
10295
10296 SuggestedNamespaces.insert(*it);
10297 }
Richard Smith998a5912011-06-05 22:42:48 +000010298 }
10299
10300 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10301 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010302 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010303 SemaRef.Diag(Best->Function->getLocation(),
10304 diag::note_not_found_by_two_phase_lookup)
10305 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010306 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010307 SemaRef.Diag(Best->Function->getLocation(),
10308 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010309 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010310 } else {
10311 // FIXME: It would be useful to list the associated namespaces here,
10312 // but the diagnostics infrastructure doesn't provide a way to produce
10313 // a localized representation of a list of items.
10314 SemaRef.Diag(Best->Function->getLocation(),
10315 diag::note_not_found_by_two_phase_lookup)
10316 << R.getLookupName() << 2;
10317 }
10318
10319 // Try to recover by calling this function.
10320 return true;
10321 }
10322
10323 R.clear();
10324 }
10325
10326 return false;
10327}
10328
10329/// Attempt to recover from ill-formed use of a non-dependent operator in a
10330/// template, where the non-dependent operator was declared after the template
10331/// was defined.
10332///
10333/// Returns true if a viable candidate was found and a diagnostic was issued.
10334static bool
10335DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10336 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010337 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010338 DeclarationName OpName =
10339 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10340 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10341 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010342 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010343}
10344
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010345namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010346class BuildRecoveryCallExprRAII {
10347 Sema &SemaRef;
10348public:
10349 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10350 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10351 SemaRef.IsBuildingRecoveryCallExpr = true;
10352 }
10353
10354 ~BuildRecoveryCallExprRAII() {
10355 SemaRef.IsBuildingRecoveryCallExpr = false;
10356 }
10357};
10358
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010359}
10360
John McCalld681c392009-12-16 08:11:27 +000010361/// Attempts to recover from a call where no functions were found.
10362///
10363/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010364static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010365BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010366 UnresolvedLookupExpr *ULE,
10367 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010368 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010369 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010370 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010371 // Do not try to recover if it is already building a recovery call.
10372 // This stops infinite loops for template instantiations like
10373 //
10374 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10375 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10376 //
10377 if (SemaRef.IsBuildingRecoveryCallExpr)
10378 return ExprError();
10379 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010380
10381 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010382 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010383 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010384
John McCall57500772009-12-16 12:17:52 +000010385 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +000010386 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010387 if (ULE->hasExplicitTemplateArgs()) {
10388 ULE->copyTemplateArgumentsInto(TABuffer);
10389 ExplicitTemplateArgs = &TABuffer;
10390 }
10391
John McCalld681c392009-12-16 08:11:27 +000010392 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10393 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010394 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10395 ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010396 NoTypoCorrectionCCC RejectAll;
10397 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10398 (CorrectionCandidateCallback*)&Validator :
10399 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010400 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010401 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010402 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010403 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010404 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010405 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010406
John McCall57500772009-12-16 12:17:52 +000010407 assert(!R.empty() && "lookup results empty despite recovery");
10408
10409 // Build an implicit member call if appropriate. Just drop the
10410 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010411 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010412 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010413 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10414 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010415 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010416 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010417 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010418 else
10419 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10420
10421 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010422 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010423
10424 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010425 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010426 // end up here.
John McCallb268a282010-08-23 23:25:46 +000010427 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010428 MultiExprArg(Args.data(), Args.size()),
10429 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010430}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010431
Sam Panzer0f384432012-08-21 00:52:01 +000010432/// \brief Constructs and populates an OverloadedCandidateSet from
10433/// the given function.
10434/// \returns true when an the ExprResult output parameter has been set.
10435bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10436 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010437 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010438 SourceLocation RParenLoc,
10439 OverloadCandidateSet *CandidateSet,
10440 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010441#ifndef NDEBUG
10442 if (ULE->requiresADL()) {
10443 // To do ADL, we must have found an unqualified name.
10444 assert(!ULE->getQualifier() && "qualified name with ADL");
10445
10446 // We don't perform ADL for implicit declarations of builtins.
10447 // Verify that this was correctly set up.
10448 FunctionDecl *F;
10449 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10450 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10451 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010452 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010453
John McCall57500772009-12-16 12:17:52 +000010454 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010455 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010456 }
John McCall57500772009-12-16 12:17:52 +000010457#endif
10458
John McCall4124c492011-10-17 18:40:02 +000010459 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010460 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010461 *Result = ExprError();
10462 return true;
10463 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010464
John McCall57500772009-12-16 12:17:52 +000010465 // Add the functions denoted by the callee to the set of candidate
10466 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010467 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010468
10469 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010470 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10471 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010472 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010473 // In Microsoft mode, if we are inside a template class member function then
10474 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010475 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010476 // classes.
Alp Tokerbfa39342014-01-14 12:51:41 +000010477 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010478 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010479 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010480 Context.DependentTy, VK_RValue,
10481 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010482 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +000010483 *Result = Owned(CE);
10484 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010485 }
Sam Panzer0f384432012-08-21 00:52:01 +000010486 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010487 }
John McCalld681c392009-12-16 08:11:27 +000010488
John McCall4124c492011-10-17 18:40:02 +000010489 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010490 return false;
10491}
John McCall4124c492011-10-17 18:40:02 +000010492
Sam Panzer0f384432012-08-21 00:52:01 +000010493/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10494/// the completed call expression. If overload resolution fails, emits
10495/// diagnostics and returns ExprError()
10496static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10497 UnresolvedLookupExpr *ULE,
10498 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010499 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010500 SourceLocation RParenLoc,
10501 Expr *ExecConfig,
10502 OverloadCandidateSet *CandidateSet,
10503 OverloadCandidateSet::iterator *Best,
10504 OverloadingResult OverloadResult,
10505 bool AllowTypoCorrection) {
10506 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010507 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010508 RParenLoc, /*EmptyLookup=*/true,
10509 AllowTypoCorrection);
10510
10511 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010512 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010513 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010514 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010515 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10516 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010517 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010518 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10519 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010520 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010521
Richard Smith998a5912011-06-05 22:42:48 +000010522 case OR_No_Viable_Function: {
10523 // Try to recover by looking for viable functions which the user might
10524 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010525 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010526 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010527 /*EmptyLookup=*/false,
10528 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010529 if (!Recovery.isInvalid())
10530 return Recovery;
10531
Sam Panzer0f384432012-08-21 00:52:01 +000010532 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010533 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010534 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010535 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010536 break;
Richard Smith998a5912011-06-05 22:42:48 +000010537 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010538
10539 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010540 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010541 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010542 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010543 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010544
Sam Panzer0f384432012-08-21 00:52:01 +000010545 case OR_Deleted: {
10546 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10547 << (*Best)->Function->isDeleted()
10548 << ULE->getName()
10549 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10550 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010551 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010552
Sam Panzer0f384432012-08-21 00:52:01 +000010553 // We emitted an error for the unvailable/deleted function call but keep
10554 // the call in the AST.
10555 FunctionDecl *FDecl = (*Best)->Function;
10556 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010557 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10558 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010559 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010560 }
10561
Douglas Gregorb412e172010-07-25 18:17:45 +000010562 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010563 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010564}
10565
Sam Panzer0f384432012-08-21 00:52:01 +000010566/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10567/// (which eventually refers to the declaration Func) and the call
10568/// arguments Args/NumArgs, attempt to resolve the function call down
10569/// to a specific function. If overload resolution succeeds, returns
10570/// the call expression produced by overload resolution.
10571/// Otherwise, emits diagnostics and returns ExprError.
10572ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10573 UnresolvedLookupExpr *ULE,
10574 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010575 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010576 SourceLocation RParenLoc,
10577 Expr *ExecConfig,
10578 bool AllowTypoCorrection) {
10579 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10580 ExprResult result;
10581
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010582 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10583 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010584 return result;
10585
10586 OverloadCandidateSet::iterator Best;
10587 OverloadingResult OverloadResult =
10588 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10589
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010590 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010591 RParenLoc, ExecConfig, &CandidateSet,
10592 &Best, OverloadResult,
10593 AllowTypoCorrection);
10594}
10595
John McCall4c4c1df2010-01-26 03:27:55 +000010596static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010597 return Functions.size() > 1 ||
10598 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10599}
10600
Douglas Gregor084d8552009-03-13 23:49:33 +000010601/// \brief Create a unary operation that may resolve to an overloaded
10602/// operator.
10603///
10604/// \param OpLoc The location of the operator itself (e.g., '*').
10605///
10606/// \param OpcIn The UnaryOperator::Opcode that describes this
10607/// operator.
10608///
James Dennett18348b62012-06-22 08:52:37 +000010609/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010610/// considered by overload resolution. The caller needs to build this
10611/// set based on the context using, e.g.,
10612/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10613/// set should not contain any member functions; those will be added
10614/// by CreateOverloadedUnaryOp().
10615///
James Dennett91738ff2012-06-22 10:32:46 +000010616/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010617ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010618Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10619 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010620 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010621 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010622
10623 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10624 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10625 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010626 // TODO: provide better source location info.
10627 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010628
John McCall4124c492011-10-17 18:40:02 +000010629 if (checkPlaceholderForOverload(*this, Input))
10630 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010631
Douglas Gregor084d8552009-03-13 23:49:33 +000010632 Expr *Args[2] = { Input, 0 };
10633 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010634
Douglas Gregor084d8552009-03-13 23:49:33 +000010635 // For post-increment and post-decrement, add the implicit '0' as
10636 // the second argument, so that we know this is a post-increment or
10637 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010638 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010639 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010640 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10641 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010642 NumArgs = 2;
10643 }
10644
Richard Smithe54c3072013-05-05 15:51:06 +000010645 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10646
Douglas Gregor084d8552009-03-13 23:49:33 +000010647 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010648 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +000010649 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010650 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +000010651 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010652 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +000010653 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010654
John McCall58cc69d2010-01-27 01:50:18 +000010655 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010656 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010657 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010658 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010659 /*ADL*/ true, IsOverloaded(Fns),
10660 Fns.begin(), Fns.end());
Richard Smithe54c3072013-05-05 15:51:06 +000010661 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregor084d8552009-03-13 23:49:33 +000010662 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010663 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010664 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010665 }
10666
10667 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010668 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010669
10670 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010671 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010672
10673 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010674 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010675
John McCall4c4c1df2010-01-26 03:27:55 +000010676 // Add candidates from ADL.
Richard Smithe54c3072013-05-05 15:51:06 +000010677 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10678 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall4c4c1df2010-01-26 03:27:55 +000010679 CandidateSet);
10680
Douglas Gregor084d8552009-03-13 23:49:33 +000010681 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010682 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010683
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010684 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10685
Douglas Gregor084d8552009-03-13 23:49:33 +000010686 // Perform overload resolution.
10687 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010688 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010689 case OR_Success: {
10690 // We found a built-in operator or an overloaded operator.
10691 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010692
Douglas Gregor084d8552009-03-13 23:49:33 +000010693 if (FnDecl) {
10694 // We matched an overloaded operator. Build a call to that
10695 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010696
Douglas Gregor084d8552009-03-13 23:49:33 +000010697 // Convert the arguments.
10698 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010699 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010700
John Wiegley01296292011-04-08 18:41:53 +000010701 ExprResult InputRes =
10702 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10703 Best->FoundDecl, Method);
10704 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010705 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010706 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010707 } else {
10708 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010709 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010710 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010711 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010712 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010713 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010714 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010715 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010716 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010717 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010718 }
10719
Douglas Gregor084d8552009-03-13 23:49:33 +000010720 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010721 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010722 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010723 if (FnExpr.isInvalid())
10724 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010725
Richard Smithc1564702013-11-15 02:58:23 +000010726 // Determine the result type.
10727 QualType ResultTy = FnDecl->getResultType();
10728 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10729 ResultTy = ResultTy.getNonLValueExprType(Context);
10730
Eli Friedman030eee42009-11-18 03:58:17 +000010731 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010732 CallExpr *TheCall =
Richard Smithe54c3072013-05-05 15:51:06 +000010733 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010734 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010735
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010736 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010737 FnDecl))
10738 return ExprError();
10739
John McCallb268a282010-08-23 23:25:46 +000010740 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010741 } else {
10742 // We matched a built-in operator. Convert the arguments, then
10743 // break out so that we will build the appropriate built-in
10744 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010745 ExprResult InputRes =
10746 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10747 Best->Conversions[0], AA_Passing);
10748 if (InputRes.isInvalid())
10749 return ExprError();
10750 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010751 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010752 }
John Wiegley01296292011-04-08 18:41:53 +000010753 }
10754
10755 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010756 // This is an erroneous use of an operator which can be overloaded by
10757 // a non-member function. Check for non-member operators which were
10758 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010759 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010760 // FIXME: Recover by calling the found function.
10761 return ExprError();
10762
John Wiegley01296292011-04-08 18:41:53 +000010763 // No viable function; fall through to handling this as a
10764 // built-in operator, which will produce an error message for us.
10765 break;
10766
10767 case OR_Ambiguous:
10768 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10769 << UnaryOperator::getOpcodeStr(Opc)
10770 << Input->getType()
10771 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010772 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010773 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10774 return ExprError();
10775
10776 case OR_Deleted:
10777 Diag(OpLoc, diag::err_ovl_deleted_oper)
10778 << Best->Function->isDeleted()
10779 << UnaryOperator::getOpcodeStr(Opc)
10780 << getDeletedOrUnavailableSuffix(Best->Function)
10781 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010782 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010783 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010784 return ExprError();
10785 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010786
10787 // Either we found no viable overloaded operator or we matched a
10788 // built-in operator. In either case, fall through to trying to
10789 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010790 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010791}
10792
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010793/// \brief Create a binary operation that may resolve to an overloaded
10794/// operator.
10795///
10796/// \param OpLoc The location of the operator itself (e.g., '+').
10797///
10798/// \param OpcIn The BinaryOperator::Opcode that describes this
10799/// operator.
10800///
James Dennett18348b62012-06-22 08:52:37 +000010801/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010802/// considered by overload resolution. The caller needs to build this
10803/// set based on the context using, e.g.,
10804/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10805/// set should not contain any member functions; those will be added
10806/// by CreateOverloadedBinOp().
10807///
10808/// \param LHS Left-hand argument.
10809/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010810ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010811Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010812 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010813 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010814 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010815 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010816 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010817
10818 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10819 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10820 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10821
10822 // If either side is type-dependent, create an appropriate dependent
10823 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010824 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010825 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010826 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010827 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010828 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010829 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010830 Context.DependentTy,
10831 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010832 OpLoc,
10833 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010834
Douglas Gregor5287f092009-11-05 00:51:44 +000010835 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10836 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010837 VK_LValue,
10838 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010839 Context.DependentTy,
10840 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010841 OpLoc,
10842 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010843 }
John McCall4c4c1df2010-01-26 03:27:55 +000010844
10845 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010846 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010847 // TODO: provide better source location info in DNLoc component.
10848 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010849 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010850 = UnresolvedLookupExpr::Create(Context, NamingClass,
10851 NestedNameSpecifierLoc(), OpNameInfo,
10852 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010853 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010854 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10855 Context.DependentTy, VK_RValue,
10856 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010857 }
10858
John McCall4124c492011-10-17 18:40:02 +000010859 // Always do placeholder-like conversions on the RHS.
10860 if (checkPlaceholderForOverload(*this, Args[1]))
10861 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010862
John McCall526ab472011-10-25 17:37:35 +000010863 // Do placeholder-like conversion on the LHS; note that we should
10864 // not get here with a PseudoObject LHS.
10865 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010866 if (checkPlaceholderForOverload(*this, Args[0]))
10867 return ExprError();
10868
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010869 // If this is the assignment operator, we only perform overload resolution
10870 // if the left-hand side is a class or enumeration type. This is actually
10871 // a hack. The standard requires that we do overload resolution between the
10872 // various built-in candidates, but as DR507 points out, this can lead to
10873 // problems. So we do it this way, which pretty much follows what GCC does.
10874 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010875 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010876 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010877
John McCalle26a8722010-12-04 08:14:53 +000010878 // If this is the .* operator, which is not overloadable, just
10879 // create a built-in binary operator.
10880 if (Opc == BO_PtrMemD)
10881 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10882
Douglas Gregor084d8552009-03-13 23:49:33 +000010883 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010884 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010885
10886 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010887 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010888
10889 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010890 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010891
John McCall4c4c1df2010-01-26 03:27:55 +000010892 // Add candidates from ADL.
10893 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010894 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010895 /*ExplicitTemplateArgs*/ 0,
10896 CandidateSet);
10897
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010898 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010899 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010900
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010901 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10902
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010903 // Perform overload resolution.
10904 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010905 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010906 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010907 // We found a built-in operator or an overloaded operator.
10908 FunctionDecl *FnDecl = Best->Function;
10909
10910 if (FnDecl) {
10911 // We matched an overloaded operator. Build a call to that
10912 // operator.
10913
10914 // Convert the arguments.
10915 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010916 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010917 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010918
Chandler Carruth8e543b32010-12-12 08:17:55 +000010919 ExprResult Arg1 =
10920 PerformCopyInitialization(
10921 InitializedEntity::InitializeParameter(Context,
10922 FnDecl->getParamDecl(0)),
10923 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010924 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010925 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010926
John Wiegley01296292011-04-08 18:41:53 +000010927 ExprResult Arg0 =
10928 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10929 Best->FoundDecl, Method);
10930 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010931 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010932 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010933 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010934 } else {
10935 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010936 ExprResult Arg0 = PerformCopyInitialization(
10937 InitializedEntity::InitializeParameter(Context,
10938 FnDecl->getParamDecl(0)),
10939 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010940 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010941 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010942
Chandler Carruth8e543b32010-12-12 08:17:55 +000010943 ExprResult Arg1 =
10944 PerformCopyInitialization(
10945 InitializedEntity::InitializeParameter(Context,
10946 FnDecl->getParamDecl(1)),
10947 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010948 if (Arg1.isInvalid())
10949 return ExprError();
10950 Args[0] = LHS = Arg0.takeAs<Expr>();
10951 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010952 }
10953
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010954 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010955 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000010956 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010957 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010958 if (FnExpr.isInvalid())
10959 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010960
Richard Smithc1564702013-11-15 02:58:23 +000010961 // Determine the result type.
10962 QualType ResultTy = FnDecl->getResultType();
10963 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10964 ResultTy = ResultTy.getNonLValueExprType(Context);
10965
John McCallb268a282010-08-23 23:25:46 +000010966 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010967 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010968 Args, ResultTy, VK, OpLoc,
10969 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010970
10971 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010972 FnDecl))
10973 return ExprError();
10974
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000010975 ArrayRef<const Expr *> ArgsArray(Args, 2);
10976 // Cut off the implicit 'this'.
10977 if (isa<CXXMethodDecl>(FnDecl))
10978 ArgsArray = ArgsArray.slice(1);
10979 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10980 TheCall->getSourceRange(), VariadicDoesNotApply);
10981
John McCallb268a282010-08-23 23:25:46 +000010982 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010983 } else {
10984 // We matched a built-in operator. Convert the arguments, then
10985 // break out so that we will build the appropriate built-in
10986 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010987 ExprResult ArgsRes0 =
10988 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10989 Best->Conversions[0], AA_Passing);
10990 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010991 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010992 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010993
John Wiegley01296292011-04-08 18:41:53 +000010994 ExprResult ArgsRes1 =
10995 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10996 Best->Conversions[1], AA_Passing);
10997 if (ArgsRes1.isInvalid())
10998 return ExprError();
10999 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011000 break;
11001 }
11002 }
11003
Douglas Gregor66950a32009-09-30 21:46:01 +000011004 case OR_No_Viable_Function: {
11005 // C++ [over.match.oper]p9:
11006 // If the operator is the operator , [...] and there are no
11007 // viable functions, then the operator is assumed to be the
11008 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000011009 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000011010 break;
11011
Chandler Carruth8e543b32010-12-12 08:17:55 +000011012 // For class as left operand for assignment or compound assigment
11013 // operator do not fall through to handling in built-in, but report that
11014 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000011015 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011016 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000011017 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000011018 Diag(OpLoc, diag::err_ovl_no_viable_oper)
11019 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000011020 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000011021 if (Args[0]->getType()->isIncompleteType()) {
11022 Diag(OpLoc, diag::note_assign_lhs_incomplete)
11023 << Args[0]->getType()
11024 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11025 }
Douglas Gregor66950a32009-09-30 21:46:01 +000011026 } else {
Richard Smith998a5912011-06-05 22:42:48 +000011027 // This is an erroneous use of an operator which can be overloaded by
11028 // a non-member function. Check for non-member operators which were
11029 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011030 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011031 // FIXME: Recover by calling the found function.
11032 return ExprError();
11033
Douglas Gregor66950a32009-09-30 21:46:01 +000011034 // No viable function; try to create a built-in operation, which will
11035 // produce an error. Then, show the non-viable candidates.
11036 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011037 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011038 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011039 "C++ binary operator overloading is missing candidates!");
11040 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011041 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011042 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011043 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011044 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011045
11046 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011047 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011048 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011049 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011050 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011051 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011052 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011053 return ExprError();
11054
11055 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011056 if (isImplicitlyDeleted(Best->Function)) {
11057 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11058 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011059 << Context.getRecordType(Method->getParent())
11060 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011061
Richard Smithde1a4872012-12-28 12:23:24 +000011062 // The user probably meant to call this special member. Just
11063 // explain why it's deleted.
11064 NoteDeletedFunction(Method);
11065 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011066 } else {
11067 Diag(OpLoc, diag::err_ovl_deleted_oper)
11068 << Best->Function->isDeleted()
11069 << BinaryOperator::getOpcodeStr(Opc)
11070 << getDeletedOrUnavailableSuffix(Best->Function)
11071 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11072 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011073 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011074 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011075 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011076 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011077
Douglas Gregor66950a32009-09-30 21:46:01 +000011078 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011079 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011080}
11081
John McCalldadc5752010-08-24 06:29:42 +000011082ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011083Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11084 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011085 Expr *Base, Expr *Idx) {
11086 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011087 DeclarationName OpName =
11088 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11089
11090 // If either side is type-dependent, create an appropriate dependent
11091 // expression.
11092 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11093
John McCall58cc69d2010-01-27 01:50:18 +000011094 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011095 // CHECKME: no 'operator' keyword?
11096 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11097 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011098 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011099 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011100 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011101 /*ADL*/ true, /*Overloaded*/ false,
11102 UnresolvedSetIterator(),
11103 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011104 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011105
Sebastian Redladba46e2009-10-29 20:17:01 +000011106 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011107 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000011108 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000011109 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000011110 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000011111 }
11112
John McCall4124c492011-10-17 18:40:02 +000011113 // Handle placeholders on both operands.
11114 if (checkPlaceholderForOverload(*this, Args[0]))
11115 return ExprError();
11116 if (checkPlaceholderForOverload(*this, Args[1]))
11117 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011118
Sebastian Redladba46e2009-10-29 20:17:01 +000011119 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000011120 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011121
11122 // Subscript can only be overloaded as a member function.
11123
11124 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011125 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011126
11127 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011128 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011129
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011130 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11131
Sebastian Redladba46e2009-10-29 20:17:01 +000011132 // Perform overload resolution.
11133 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011134 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011135 case OR_Success: {
11136 // We found a built-in operator or an overloaded operator.
11137 FunctionDecl *FnDecl = Best->Function;
11138
11139 if (FnDecl) {
11140 // We matched an overloaded operator. Build a call to that
11141 // operator.
11142
John McCalla0296f72010-03-19 07:35:19 +000011143 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011144
Sebastian Redladba46e2009-10-29 20:17:01 +000011145 // Convert the arguments.
11146 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011147 ExprResult Arg0 =
11148 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
11149 Best->FoundDecl, Method);
11150 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011151 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011152 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011153
Anders Carlssona68e51e2010-01-29 18:37:50 +000011154 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011155 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011156 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011157 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011158 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011159 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000011160 Owned(Args[1]));
11161 if (InputInit.isInvalid())
11162 return ExprError();
11163
11164 Args[1] = InputInit.takeAs<Expr>();
11165
Sebastian Redladba46e2009-10-29 20:17:01 +000011166 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011167 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11168 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011169 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011170 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011171 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011172 OpLocInfo.getLoc(),
11173 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011174 if (FnExpr.isInvalid())
11175 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011176
Richard Smithc1564702013-11-15 02:58:23 +000011177 // Determine the result type
11178 QualType ResultTy = FnDecl->getResultType();
11179 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11180 ResultTy = ResultTy.getNonLValueExprType(Context);
11181
John McCallb268a282010-08-23 23:25:46 +000011182 CXXOperatorCallExpr *TheCall =
11183 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011184 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011185 ResultTy, VK, RLoc,
11186 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011187
John McCallb268a282010-08-23 23:25:46 +000011188 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000011189 FnDecl))
11190 return ExprError();
11191
John McCallb268a282010-08-23 23:25:46 +000011192 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011193 } else {
11194 // We matched a built-in operator. Convert the arguments, then
11195 // break out so that we will build the appropriate built-in
11196 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011197 ExprResult ArgsRes0 =
11198 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11199 Best->Conversions[0], AA_Passing);
11200 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011201 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011202 Args[0] = ArgsRes0.take();
11203
11204 ExprResult ArgsRes1 =
11205 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11206 Best->Conversions[1], AA_Passing);
11207 if (ArgsRes1.isInvalid())
11208 return ExprError();
11209 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011210
11211 break;
11212 }
11213 }
11214
11215 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011216 if (CandidateSet.empty())
11217 Diag(LLoc, diag::err_ovl_no_oper)
11218 << Args[0]->getType() << /*subscript*/ 0
11219 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11220 else
11221 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11222 << Args[0]->getType()
11223 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011225 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011226 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011227 }
11228
11229 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011230 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011231 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011232 << Args[0]->getType() << Args[1]->getType()
11233 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011234 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011235 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011236 return ExprError();
11237
11238 case OR_Deleted:
11239 Diag(LLoc, diag::err_ovl_deleted_oper)
11240 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011241 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011242 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011243 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011244 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011245 return ExprError();
11246 }
11247
11248 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011249 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011250}
11251
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011252/// BuildCallToMemberFunction - Build a call to a member
11253/// function. MemExpr is the expression that refers to the member
11254/// function (and includes the object parameter), Args/NumArgs are the
11255/// arguments to the function call (not including the object
11256/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011257/// expression refers to a non-static member function or an overloaded
11258/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011259ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011260Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011261 SourceLocation LParenLoc,
11262 MultiExprArg Args,
11263 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011264 assert(MemExprE->getType() == Context.BoundMemberTy ||
11265 MemExprE->getType() == Context.OverloadTy);
11266
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011267 // Dig out the member expression. This holds both the object
11268 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011269 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011270
John McCall0009fcc2011-04-26 20:42:42 +000011271 // Determine whether this is a call to a pointer-to-member function.
11272 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11273 assert(op->getType() == Context.BoundMemberTy);
11274 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11275
11276 QualType fnType =
11277 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11278
11279 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11280 QualType resultType = proto->getCallResultType(Context);
11281 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
11282
11283 // Check that the object type isn't more qualified than the
11284 // member function we're calling.
11285 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11286
11287 QualType objectType = op->getLHS()->getType();
11288 if (op->getOpcode() == BO_PtrMemI)
11289 objectType = objectType->castAs<PointerType>()->getPointeeType();
11290 Qualifiers objectQuals = objectType.getQualifiers();
11291
11292 Qualifiers difference = objectQuals - funcQuals;
11293 difference.removeObjCGCAttr();
11294 difference.removeAddressSpace();
11295 if (difference) {
11296 std::string qualsString = difference.getAsString();
11297 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11298 << fnType.getUnqualifiedType()
11299 << qualsString
11300 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11301 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011302
John McCall0009fcc2011-04-26 20:42:42 +000011303 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011304 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011305 resultType, valueKind, RParenLoc);
11306
11307 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011308 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000011309 call, 0))
11310 return ExprError();
11311
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011312 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011313 return ExprError();
11314
Richard Trieu9be9c682013-06-22 02:30:38 +000011315 if (CheckOtherCall(call, proto))
11316 return ExprError();
11317
John McCall0009fcc2011-04-26 20:42:42 +000011318 return MaybeBindToTemporary(call);
11319 }
11320
John McCall4124c492011-10-17 18:40:02 +000011321 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011322 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011323 return ExprError();
11324
John McCall10eae182009-11-30 22:42:35 +000011325 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011326 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000011327 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011328 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000011329 if (isa<MemberExpr>(NakedMemExpr)) {
11330 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011331 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011332 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011333 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011334 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011335 } else {
11336 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011337 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011338
John McCall6e9f8f62009-12-03 04:06:58 +000011339 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011340 Expr::Classification ObjectClassification
11341 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11342 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011343
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011344 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000011345 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000011346
John McCall2d74de92009-12-01 22:10:20 +000011347 // FIXME: avoid copy.
11348 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11349 if (UnresExpr->hasExplicitTemplateArgs()) {
11350 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11351 TemplateArgs = &TemplateArgsBuffer;
11352 }
11353
John McCall10eae182009-11-30 22:42:35 +000011354 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11355 E = UnresExpr->decls_end(); I != E; ++I) {
11356
John McCall6e9f8f62009-12-03 04:06:58 +000011357 NamedDecl *Func = *I;
11358 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11359 if (isa<UsingShadowDecl>(Func))
11360 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11361
Douglas Gregor02824322011-01-26 19:30:28 +000011362
Francois Pichet64225792011-01-18 05:04:39 +000011363 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011364 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011365 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011366 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011367 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011368 // If explicit template arguments were provided, we can't call a
11369 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011370 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011371 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011372
John McCalla0296f72010-03-19 07:35:19 +000011373 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011374 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011375 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011376 } else {
John McCall10eae182009-11-30 22:42:35 +000011377 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011378 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011379 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011380 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011381 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011382 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011383 }
Mike Stump11289f42009-09-09 15:08:12 +000011384
John McCall10eae182009-11-30 22:42:35 +000011385 DeclarationName DeclName = UnresExpr->getMemberName();
11386
John McCall4124c492011-10-17 18:40:02 +000011387 UnbridgedCasts.restore();
11388
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011389 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011390 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011391 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011392 case OR_Success:
11393 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011394 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011395 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011396 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11397 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011398 // If FoundDecl is different from Method (such as if one is a template
11399 // and the other a specialization), make sure DiagnoseUseOfDecl is
11400 // called on both.
11401 // FIXME: This would be more comprehensively addressed by modifying
11402 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11403 // being used.
11404 if (Method != FoundDecl.getDecl() &&
11405 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11406 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011407 break;
11408
11409 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011410 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011411 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011412 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011413 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011414 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011415 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011416
11417 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011418 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011419 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011420 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011421 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011422 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011423
11424 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011425 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011426 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011427 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011428 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011429 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011430 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011431 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011432 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011433 }
11434
John McCall16df1e52010-03-30 21:47:33 +000011435 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011436
John McCall2d74de92009-12-01 22:10:20 +000011437 // If overload resolution picked a static member, build a
11438 // non-member call based on that function.
11439 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011440 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11441 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011442 }
11443
John McCall10eae182009-11-30 22:42:35 +000011444 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011445 }
11446
John McCall7decc9e2010-11-18 06:31:45 +000011447 QualType ResultType = Method->getResultType();
11448 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11449 ResultType = ResultType.getNonLValueExprType(Context);
11450
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011451 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011452 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011453 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011454 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011455
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011456 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011457 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011458 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011459 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011460
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011461 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011462 // We only need to do this if there was actually an overload; otherwise
11463 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011464 if (!Method->isStatic()) {
11465 ExprResult ObjectArg =
11466 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11467 FoundDecl, Method);
11468 if (ObjectArg.isInvalid())
11469 return ExprError();
11470 MemExpr->setBase(ObjectArg.take());
11471 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011472
11473 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011474 const FunctionProtoType *Proto =
11475 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011476 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011477 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011478 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011479
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011480 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011481
Richard Smith55ce3522012-06-25 20:30:08 +000011482 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011483 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011484
Anders Carlsson47061ee2011-05-06 14:25:31 +000011485 if ((isa<CXXConstructorDecl>(CurContext) ||
11486 isa<CXXDestructorDecl>(CurContext)) &&
11487 TheCall->getMethodDecl()->isPure()) {
11488 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11489
Chandler Carruth59259262011-06-27 08:31:58 +000011490 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011491 Diag(MemExpr->getLocStart(),
11492 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11493 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11494 << MD->getParent()->getDeclName();
11495
11496 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011497 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011498 }
John McCallb268a282010-08-23 23:25:46 +000011499 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011500}
11501
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011502/// BuildCallToObjectOfClassType - Build a call to an object of class
11503/// type (C++ [over.call.object]), which can end up invoking an
11504/// overloaded function call operator (@c operator()) or performing a
11505/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011506ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011507Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011508 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011509 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011510 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011511 if (checkPlaceholderForOverload(*this, Obj))
11512 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011513 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000011514
11515 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011516 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011517 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011518
John Wiegley01296292011-04-08 18:41:53 +000011519 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11520 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011521
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011522 // C++ [over.call.object]p1:
11523 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011524 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011525 // candidate functions includes at least the function call
11526 // operators of T. The function call operators of T are obtained by
11527 // ordinary lookup of the name operator() in the context of
11528 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000011529 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000011530 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011531
John Wiegley01296292011-04-08 18:41:53 +000011532 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011533 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011534 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011535
John McCall27b18f82009-11-17 02:14:36 +000011536 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11537 LookupQualifiedName(R, Record->getDecl());
11538 R.suppressDiagnostics();
11539
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011540 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011541 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011542 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011543 Object.get()->Classify(Context),
11544 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011545 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011546 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011547
Douglas Gregorab7897a2008-11-19 22:57:39 +000011548 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011549 // In addition, for each (non-explicit in C++0x) conversion function
11550 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011551 //
11552 // operator conversion-type-id () cv-qualifier;
11553 //
11554 // where cv-qualifier is the same cv-qualification as, or a
11555 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011556 // denotes the type "pointer to function of (P1,...,Pn) returning
11557 // R", or the type "reference to pointer to function of
11558 // (P1,...,Pn) returning R", or the type "reference to function
11559 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011560 // is also considered as a candidate function. Similarly,
11561 // surrogate call functions are added to the set of candidate
11562 // functions for each conversion function declared in an
11563 // accessible base class provided the function is not hidden
11564 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011565 std::pair<CXXRecordDecl::conversion_iterator,
11566 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011567 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011568 for (CXXRecordDecl::conversion_iterator
11569 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011570 NamedDecl *D = *I;
11571 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11572 if (isa<UsingShadowDecl>(D))
11573 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011574
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011575 // Skip over templated conversion functions; they aren't
11576 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011577 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011578 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011579
John McCall6e9f8f62009-12-03 04:06:58 +000011580 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011581 if (!Conv->isExplicit()) {
11582 // Strip the reference type (if any) and then the pointer type (if
11583 // any) to get down to what might be a function type.
11584 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11585 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11586 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011587
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011588 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11589 {
11590 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011591 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011592 }
11593 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011594 }
Mike Stump11289f42009-09-09 15:08:12 +000011595
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011596 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11597
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011598 // Perform overload resolution.
11599 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011600 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011601 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011602 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011603 // Overload resolution succeeded; we'll build the appropriate call
11604 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011605 break;
11606
11607 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011608 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011609 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011610 << Object.get()->getType() << /*call*/ 1
11611 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011612 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011613 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011614 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011615 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011616 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011617 break;
11618
11619 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011620 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011621 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011622 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011623 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011624 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011625
11626 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011627 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011628 diag::err_ovl_deleted_object_call)
11629 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011630 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011631 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011632 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011633 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011634 break;
Mike Stump11289f42009-09-09 15:08:12 +000011635 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011636
Douglas Gregorb412e172010-07-25 18:17:45 +000011637 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011638 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011639
John McCall4124c492011-10-17 18:40:02 +000011640 UnbridgedCasts.restore();
11641
Douglas Gregorab7897a2008-11-19 22:57:39 +000011642 if (Best->Function == 0) {
11643 // Since there is no function declaration, this is one of the
11644 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011645 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011646 = cast<CXXConversionDecl>(
11647 Best->Conversions[0].UserDefined.ConversionFunction);
11648
John Wiegley01296292011-04-08 18:41:53 +000011649 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011650 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11651 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011652 assert(Conv == Best->FoundDecl.getDecl() &&
11653 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011654 // We selected one of the surrogate functions that converts the
11655 // object parameter to a function pointer. Perform the conversion
11656 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011657
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011658 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011659 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011660 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11661 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011662 if (Call.isInvalid())
11663 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011664 // Record usage of conversion in an implicit cast.
11665 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11666 CK_UserDefinedConversion,
11667 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011668
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011669 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011670 }
11671
John Wiegley01296292011-04-08 18:41:53 +000011672 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011673
Douglas Gregorab7897a2008-11-19 22:57:39 +000011674 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11675 // that calls this method, using Object for the implicit object
11676 // parameter and passing along the remaining arguments.
11677 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011678
11679 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011680 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011681 return ExprError();
11682
Chandler Carruth8e543b32010-12-12 08:17:55 +000011683 const FunctionProtoType *Proto =
11684 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011685
11686 unsigned NumArgsInProto = Proto->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +000011687
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011688 DeclarationNameInfo OpLocInfo(
11689 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11690 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011691 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011692 HadMultipleCandidates,
11693 OpLocInfo.getLoc(),
11694 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011695 if (NewFn.isInvalid())
11696 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011697
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011698 // Build the full argument list for the method call (the implicit object
11699 // parameter is placed at the beginning of the list).
11700 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11701 MethodArgs[0] = Object.get();
11702 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11703
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011704 // Once we've built TheCall, all of the expressions are properly
11705 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011706 QualType ResultTy = Method->getResultType();
11707 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11708 ResultTy = ResultTy.getNonLValueExprType(Context);
11709
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011710 CXXOperatorCallExpr *TheCall = new (Context)
11711 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11712 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11713 ResultTy, VK, RParenLoc, false);
11714 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011715
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011716 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011717 Method))
11718 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011719
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011720 // We may have default arguments. If so, we need to allocate more
11721 // slots in the call for them.
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011722 if (Args.size() < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011723 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011724
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011725 bool IsError = false;
11726
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011727 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011728 ExprResult ObjRes =
11729 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11730 Best->FoundDecl, Method);
11731 if (ObjRes.isInvalid())
11732 IsError = true;
11733 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011734 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011735 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011736
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011737 // Check the argument types.
Benjamin Kramer3c529ca2013-10-05 10:03:01 +000011738 for (unsigned i = 0; i != NumArgsInProto; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011739 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011740 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011741 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011742
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011743 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011744
John McCalldadc5752010-08-24 06:29:42 +000011745 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011746 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011747 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011748 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011749 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011750
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011751 IsError |= InputInit.isInvalid();
11752 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011753 } else {
John McCalldadc5752010-08-24 06:29:42 +000011754 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011755 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11756 if (DefArg.isInvalid()) {
11757 IsError = true;
11758 break;
11759 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011760
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011761 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011762 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011763
11764 TheCall->setArg(i + 1, Arg);
11765 }
11766
11767 // If this is a variadic call, handle args passed through "...".
11768 if (Proto->isVariadic()) {
11769 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011770 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011771 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11772 IsError |= Arg.isInvalid();
11773 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011774 }
11775 }
11776
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011777 if (IsError) return true;
11778
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011779 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011780
Richard Smith55ce3522012-06-25 20:30:08 +000011781 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011782 return true;
11783
John McCalle172be52010-08-24 06:09:16 +000011784 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011785}
11786
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011787/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011788/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011789/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011790ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011791Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11792 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011793 assert(Base->getType()->isRecordType() &&
11794 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011795
John McCall4124c492011-10-17 18:40:02 +000011796 if (checkPlaceholderForOverload(*this, Base))
11797 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011798
John McCallbc077cf2010-02-08 23:07:23 +000011799 SourceLocation Loc = Base->getExprLoc();
11800
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011801 // C++ [over.ref]p1:
11802 //
11803 // [...] An expression x->m is interpreted as (x.operator->())->m
11804 // for a class object x of type T if T::operator->() exists and if
11805 // the operator is selected as the best match function by the
11806 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011807 DeclarationName OpName =
11808 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011809 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011810 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011811
John McCallbc077cf2010-02-08 23:07:23 +000011812 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011813 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011814 return ExprError();
11815
John McCall27b18f82009-11-17 02:14:36 +000011816 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11817 LookupQualifiedName(R, BaseRecord->getDecl());
11818 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011819
11820 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011821 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011822 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011823 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011824 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011825
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011826 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11827
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011828 // Perform overload resolution.
11829 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011830 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011831 case OR_Success:
11832 // Overload resolution succeeded; we'll build the call below.
11833 break;
11834
11835 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011836 if (CandidateSet.empty()) {
11837 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011838 if (NoArrowOperatorFound) {
11839 // Report this specific error to the caller instead of emitting a
11840 // diagnostic, as requested.
11841 *NoArrowOperatorFound = true;
11842 return ExprError();
11843 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011844 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11845 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011846 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011847 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011848 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011849 }
11850 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011851 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011852 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011853 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011854 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011855
11856 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011857 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11858 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011859 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011860 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011861
11862 case OR_Deleted:
11863 Diag(OpLoc, diag::err_ovl_deleted_oper)
11864 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011865 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011866 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011867 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011868 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011869 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011870 }
11871
John McCalla0296f72010-03-19 07:35:19 +000011872 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11873
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011874 // Convert the object parameter.
11875 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011876 ExprResult BaseResult =
11877 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11878 Best->FoundDecl, Method);
11879 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011880 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011881 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011882
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011883 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000011884 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011885 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011886 if (FnExpr.isInvalid())
11887 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011888
John McCall7decc9e2010-11-18 06:31:45 +000011889 QualType ResultTy = Method->getResultType();
11890 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11891 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011892 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011893 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011894 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011895
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011896 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011897 Method))
11898 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011899
11900 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011901}
11902
Richard Smithbcc22fc2012-03-09 08:00:36 +000011903/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11904/// a literal operator described by the provided lookup results.
11905ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11906 DeclarationNameInfo &SuffixInfo,
11907 ArrayRef<Expr*> Args,
11908 SourceLocation LitEndLoc,
11909 TemplateArgumentListInfo *TemplateArgs) {
11910 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011911
Richard Smithbcc22fc2012-03-09 08:00:36 +000011912 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11913 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11914 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011915
Richard Smithbcc22fc2012-03-09 08:00:36 +000011916 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11917
Richard Smithbcc22fc2012-03-09 08:00:36 +000011918 // Perform overload resolution. This will usually be trivial, but might need
11919 // to perform substitutions for a literal operator template.
11920 OverloadCandidateSet::iterator Best;
11921 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11922 case OR_Success:
11923 case OR_Deleted:
11924 break;
11925
11926 case OR_No_Viable_Function:
11927 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11928 << R.getLookupName();
11929 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11930 return ExprError();
11931
11932 case OR_Ambiguous:
11933 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11934 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11935 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011936 }
11937
Richard Smithbcc22fc2012-03-09 08:00:36 +000011938 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000011939 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11940 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000011941 SuffixInfo.getLoc(),
11942 SuffixInfo.getInfo());
11943 if (Fn.isInvalid())
11944 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011945
11946 // Check the argument types. This should almost always be a no-op, except
11947 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011948 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000011949 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000011950 ExprResult InputInit = PerformCopyInitialization(
11951 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11952 SourceLocation(), Args[ArgIdx]);
11953 if (InputInit.isInvalid())
11954 return true;
11955 ConvArgs[ArgIdx] = InputInit.take();
11956 }
11957
Richard Smithc67fdd42012-03-07 08:35:16 +000011958 QualType ResultTy = FD->getResultType();
11959 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11960 ResultTy = ResultTy.getNonLValueExprType(Context);
11961
Richard Smithc67fdd42012-03-07 08:35:16 +000011962 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011963 new (Context) UserDefinedLiteral(Context, Fn.take(),
11964 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011965 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11966
11967 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11968 return ExprError();
11969
Richard Smith55ce3522012-06-25 20:30:08 +000011970 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011971 return ExprError();
11972
11973 return MaybeBindToTemporary(UDL);
11974}
11975
Sam Panzer0f384432012-08-21 00:52:01 +000011976/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11977/// given LookupResult is non-empty, it is assumed to describe a member which
11978/// will be invoked. Otherwise, the function will be found via argument
11979/// dependent lookup.
11980/// CallExpr is set to a valid expression and FRS_Success returned on success,
11981/// otherwise CallExpr is set to ExprError() and some non-success value
11982/// is returned.
11983Sema::ForRangeStatus
11984Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11985 SourceLocation RangeLoc, VarDecl *Decl,
11986 BeginEndFunction BEF,
11987 const DeclarationNameInfo &NameInfo,
11988 LookupResult &MemberLookup,
11989 OverloadCandidateSet *CandidateSet,
11990 Expr *Range, ExprResult *CallExpr) {
11991 CandidateSet->clear();
11992 if (!MemberLookup.empty()) {
11993 ExprResult MemberRef =
11994 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11995 /*IsPtr=*/false, CXXScopeSpec(),
11996 /*TemplateKWLoc=*/SourceLocation(),
11997 /*FirstQualifierInScope=*/0,
11998 MemberLookup,
11999 /*TemplateArgs=*/0);
12000 if (MemberRef.isInvalid()) {
12001 *CallExpr = ExprError();
12002 Diag(Range->getLocStart(), diag::note_in_for_range)
12003 << RangeLoc << BEF << Range->getType();
12004 return FRS_DiagnosticIssued;
12005 }
Dmitri Gribenko78852e92013-05-05 20:40:26 +000012006 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzer0f384432012-08-21 00:52:01 +000012007 if (CallExpr->isInvalid()) {
12008 *CallExpr = ExprError();
12009 Diag(Range->getLocStart(), diag::note_in_for_range)
12010 << RangeLoc << BEF << Range->getType();
12011 return FRS_DiagnosticIssued;
12012 }
12013 } else {
12014 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000012015 UnresolvedLookupExpr *Fn =
12016 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
12017 NestedNameSpecifierLoc(), NameInfo,
12018 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000012019 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000012020
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012021 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000012022 CandidateSet, CallExpr);
12023 if (CandidateSet->empty() || CandidateSetError) {
12024 *CallExpr = ExprError();
12025 return FRS_NoViableFunction;
12026 }
12027 OverloadCandidateSet::iterator Best;
12028 OverloadingResult OverloadResult =
12029 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12030
12031 if (OverloadResult == OR_No_Viable_Function) {
12032 *CallExpr = ExprError();
12033 return FRS_NoViableFunction;
12034 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012035 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzer0f384432012-08-21 00:52:01 +000012036 Loc, 0, CandidateSet, &Best,
12037 OverloadResult,
12038 /*AllowTypoCorrection=*/false);
12039 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12040 *CallExpr = ExprError();
12041 Diag(Range->getLocStart(), diag::note_in_for_range)
12042 << RangeLoc << BEF << Range->getType();
12043 return FRS_DiagnosticIssued;
12044 }
12045 }
12046 return FRS_Success;
12047}
12048
12049
Douglas Gregorcd695e52008-11-10 20:40:00 +000012050/// FixOverloadedFunctionReference - E is an expression that refers to
12051/// a C++ overloaded function (possibly with some parentheses and
12052/// perhaps a '&' around it). We have resolved the overloaded function
12053/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012054/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012055Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012056 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012057 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012058 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12059 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012060 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012061 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012062
Douglas Gregor51c538b2009-11-20 19:42:02 +000012063 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012064 }
12065
Douglas Gregor51c538b2009-11-20 19:42:02 +000012066 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012067 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12068 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012069 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012070 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012071 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012072 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012073 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012074 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012075
12076 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012077 ICE->getCastKind(),
12078 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000012079 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012080 }
12081
Douglas Gregor51c538b2009-11-20 19:42:02 +000012082 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012083 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012084 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012085 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12086 if (Method->isStatic()) {
12087 // Do nothing: static member functions aren't any different
12088 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012089 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012090 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012091 // UnresolvedLookupExpr holding an overloaded member function
12092 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012093 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12094 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012095 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012096 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012097
John McCalld14a8642009-11-21 08:51:07 +000012098 assert(isa<DeclRefExpr>(SubExpr)
12099 && "fixed to something other than a decl ref");
12100 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12101 && "fixed to a member ref with no nested name qualifier");
12102
12103 // We have taken the address of a pointer to member
12104 // function. Perform the computation here so that we get the
12105 // appropriate pointer to member type.
12106 QualType ClassType
12107 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12108 QualType MemPtrType
12109 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12110
John McCall7decc9e2010-11-18 06:31:45 +000012111 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12112 VK_RValue, OK_Ordinary,
12113 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012114 }
12115 }
John McCall16df1e52010-03-30 21:47:33 +000012116 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12117 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012118 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012119 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012120
John McCalle3027922010-08-25 11:45:40 +000012121 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012122 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012123 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012124 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012125 }
John McCalld14a8642009-11-21 08:51:07 +000012126
12127 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012128 // FIXME: avoid copy.
12129 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000012130 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012131 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12132 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012133 }
12134
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012135 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12136 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012137 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012138 Fn,
John McCall113bee02012-03-10 09:33:50 +000012139 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012140 ULE->getNameLoc(),
12141 Fn->getType(),
12142 VK_LValue,
12143 Found.getDecl(),
12144 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012145 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012146 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12147 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012148 }
12149
John McCall10eae182009-11-30 22:42:35 +000012150 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012151 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000012152 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
12153 if (MemExpr->hasExplicitTemplateArgs()) {
12154 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12155 TemplateArgs = &TemplateArgsBuffer;
12156 }
John McCall6b51f282009-11-23 01:53:49 +000012157
John McCall2d74de92009-12-01 22:10:20 +000012158 Expr *Base;
12159
John McCall7decc9e2010-11-18 06:31:45 +000012160 // If we're filling in a static method where we used to have an
12161 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012162 if (MemExpr->isImplicitAccess()) {
12163 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012164 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12165 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012166 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012167 Fn,
John McCall113bee02012-03-10 09:33:50 +000012168 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012169 MemExpr->getMemberLoc(),
12170 Fn->getType(),
12171 VK_LValue,
12172 Found.getDecl(),
12173 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012174 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012175 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
12176 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012177 } else {
12178 SourceLocation Loc = MemExpr->getMemberLoc();
12179 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012180 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012181 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012182 Base = new (Context) CXXThisExpr(Loc,
12183 MemExpr->getBaseType(),
12184 /*isImplicit=*/true);
12185 }
John McCall2d74de92009-12-01 22:10:20 +000012186 } else
John McCallc3007a22010-10-26 07:05:15 +000012187 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012188
John McCall4adb38c2011-04-27 00:36:17 +000012189 ExprValueKind valueKind;
12190 QualType type;
12191 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12192 valueKind = VK_LValue;
12193 type = Fn->getType();
12194 } else {
12195 valueKind = VK_RValue;
12196 type = Context.BoundMemberTy;
12197 }
12198
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012199 MemberExpr *ME = MemberExpr::Create(Context, Base,
12200 MemExpr->isArrow(),
12201 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012202 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012203 Fn,
12204 Found,
12205 MemExpr->getMemberNameInfo(),
12206 TemplateArgs,
12207 type, valueKind, OK_Ordinary);
12208 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012209 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012210 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012212
John McCallc3007a22010-10-26 07:05:15 +000012213 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012214}
12215
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012216ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012217 DeclAccessPair Found,
12218 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000012219 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012220}
12221
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012222} // end namespace clang