blob: 6032ed398052958645d53e4ce9988178a39f90de [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 Gregore489a7d2010-02-28 18:30:25 +00001446 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001447 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001448 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001449 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001450
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001451 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001452 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001453 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001454 if (S.getLangOpts().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001455 return false;
1456
Mike Stump11289f42009-09-09 15:08:12 +00001457 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001458 }
1459
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001460 // The first conversion can be an lvalue-to-rvalue conversion,
1461 // array-to-pointer conversion, or function-to-pointer conversion
1462 // (C++ 4p1).
1463
John McCall5c32be02010-08-24 20:38:10 +00001464 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001465 DeclAccessPair AccessPair;
1466 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001468 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001469 // We were able to resolve the address of the overloaded function,
1470 // so we can convert to the type of that function.
1471 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001472
1473 // we can sometimes resolve &foo<int> regardless of ToType, so check
1474 // if the type matches (identity) or we are converting to bool
1475 if (!S.Context.hasSameUnqualifiedType(
1476 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1477 QualType resultTy;
1478 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001479 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001480 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1481 // otherwise, only a boolean conversion is standard
1482 if (!ToType->isBooleanType())
1483 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001485
Chandler Carruthffce2452011-03-29 08:08:18 +00001486 // Check if the "from" expression is taking the address of an overloaded
1487 // function and recompute the FromType accordingly. Take advantage of the
1488 // fact that non-static member functions *must* have such an address-of
1489 // expression.
1490 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1491 if (Method && !Method->isStatic()) {
1492 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1493 "Non-unary operator on non-static member address");
1494 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1495 == UO_AddrOf &&
1496 "Non-address-of operator on non-static member address");
1497 const Type *ClassType
1498 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1499 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001500 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1501 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1502 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001503 "Non-address-of operator for overloaded function expression");
1504 FromType = S.Context.getPointerType(FromType);
1505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001506
Douglas Gregor980fb162010-04-29 18:24:40 +00001507 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001508 assert(S.Context.hasSameType(
1509 FromType,
1510 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001511 } else {
1512 return false;
1513 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001514 }
John McCall154a2fd2011-08-30 00:57:29 +00001515 // Lvalue-to-rvalue conversion (C++11 4.1):
1516 // A glvalue (3.10) of a non-function, non-array type T can
1517 // be converted to a prvalue.
1518 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001519 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001520 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001521 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001522 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001523
Douglas Gregorc79862f2012-04-12 17:51:55 +00001524 // C11 6.3.2.1p2:
1525 // ... if the lvalue has atomic type, the value has the non-atomic version
1526 // of the type of the lvalue ...
1527 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1528 FromType = Atomic->getValueType();
1529
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530 // If T is a non-class type, the type of the rvalue is the
1531 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001532 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1533 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001534 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001535 } else if (FromType->isArrayType()) {
1536 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001537 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001538
1539 // An lvalue or rvalue of type "array of N T" or "array of unknown
1540 // bound of T" can be converted to an rvalue of type "pointer to
1541 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001542 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543
John McCall5c32be02010-08-24 20:38:10 +00001544 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001546 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547
1548 // For the purpose of ranking in overload resolution
1549 // (13.3.3.1.1), this conversion is considered an
1550 // array-to-pointer conversion followed by a qualification
1551 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001552 SCS.Second = ICK_Identity;
1553 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001554 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001555 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001556 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001557 }
John McCall086a4642010-11-24 05:12:34 +00001558 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001559 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001560 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561
1562 // An lvalue of function type T can be converted to an rvalue of
1563 // type "pointer to T." The result is a pointer to the
1564 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001565 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001566 } else {
1567 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001568 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001569 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001570 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001571
1572 // The second conversion can be an integral promotion, floating
1573 // point promotion, integral conversion, floating point conversion,
1574 // floating-integral conversion, pointer conversion,
1575 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001576 // For overloading in C, this can also be a "compatible-type"
1577 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001578 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001579 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001580 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 // The unqualified versions of the types are the same: there's no
1582 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001583 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001584 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001585 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001586 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001587 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001588 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001589 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001590 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001591 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001592 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001593 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001594 SCS.Second = ICK_Complex_Promotion;
1595 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001596 } else if (ToType->isBooleanType() &&
1597 (FromType->isArithmeticType() ||
1598 FromType->isAnyPointerType() ||
1599 FromType->isBlockPointerType() ||
1600 FromType->isMemberPointerType() ||
1601 FromType->isNullPtrType())) {
1602 // Boolean conversions (C++ 4.12).
1603 SCS.Second = ICK_Boolean_Conversion;
1604 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001605 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001606 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001607 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001608 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609 FromType = ToType.getUnqualifiedType();
Richard Smithb8a98242013-05-10 20:29:50 +00001610 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001611 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001612 SCS.Second = ICK_Complex_Conversion;
1613 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001614 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1615 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001616 // Complex-real conversions (C99 6.3.1.7)
1617 SCS.Second = ICK_Complex_Real;
1618 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001619 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001620 // Floating point conversions (C++ 4.8).
1621 SCS.Second = ICK_Floating_Conversion;
1622 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001623 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001624 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001625 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001626 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001627 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001628 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001630 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001631 SCS.Second = ICK_Block_Pointer_Conversion;
1632 } else if (AllowObjCWritebackConversion &&
1633 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1634 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001635 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1636 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001637 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001639 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001640 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001641 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001642 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001643 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001644 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001645 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001646 SCS.Second = SecondICK;
1647 FromType = ToType.getUnqualifiedType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00001648 } else if (!S.getLangOpts().CPlusPlus &&
John McCall5c32be02010-08-24 20:38:10 +00001649 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001650 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001651 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001652 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001653 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001654 // Treat a conversion that strips "noreturn" as an identity conversion.
1655 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001656 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1657 InOverloadResolution,
1658 SCS, CStyle)) {
1659 SCS.Second = ICK_TransparentUnionConversion;
1660 FromType = ToType;
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00001661 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1662 CStyle)) {
1663 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorc79862f2012-04-12 17:51:55 +00001664 // appropriately.
1665 return true;
Guy Benyei259f9f42013-02-07 16:05:33 +00001666 } else if (ToType->isEventT() &&
1667 From->isIntegerConstantExpr(S.getASTContext()) &&
1668 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1669 SCS.Second = ICK_Zero_Event_Conversion;
1670 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 } else {
1672 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001673 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001675 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001676
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001677 QualType CanonFrom;
1678 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001679 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001680 bool ObjCLifetimeConversion;
1681 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1682 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001683 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001684 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001685 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001686 CanonFrom = S.Context.getCanonicalType(FromType);
1687 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001688 } else {
1689 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001690 SCS.Third = ICK_Identity;
1691
Mike Stump11289f42009-09-09 15:08:12 +00001692 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001693 // [...] Any difference in top-level cv-qualification is
1694 // subsumed by the initialization itself and does not constitute
1695 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001696 CanonFrom = S.Context.getCanonicalType(FromType);
1697 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001698 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001699 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault7d36c012013-02-26 21:15:54 +00001700 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001701 FromType = ToType;
1702 CanonFrom = CanonTo;
1703 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001704 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001705 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001706
1707 // If we have not converted the argument type to the parameter type,
1708 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001709 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001710 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001711
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001712 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001714
1715static bool
1716IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1717 QualType &ToType,
1718 bool InOverloadResolution,
1719 StandardConversionSequence &SCS,
1720 bool CStyle) {
1721
1722 const RecordType *UT = ToType->getAsUnionType();
1723 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1724 return false;
1725 // The field to initialize within the transparent union.
1726 RecordDecl *UD = UT->getDecl();
1727 // It's compatible if the expression matches any of the fields.
1728 for (RecordDecl::field_iterator it = UD->field_begin(),
1729 itend = UD->field_end();
1730 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001731 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1732 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001733 ToType = it->getType();
1734 return true;
1735 }
1736 }
1737 return false;
1738}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739
1740/// IsIntegralPromotion - Determines whether the conversion from the
1741/// expression From (whose potentially-adjusted type is FromType) to
1742/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1743/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001744bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001745 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001746 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001747 if (!To) {
1748 return false;
1749 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001750
1751 // An rvalue of type char, signed char, unsigned char, short int, or
1752 // unsigned short int can be converted to an rvalue of type int if
1753 // int can represent all the values of the source type; otherwise,
1754 // the source rvalue can be converted to an rvalue of type unsigned
1755 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001756 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1757 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001758 if (// We can promote any signed, promotable integer type to an int
1759 (FromType->isSignedIntegerType() ||
1760 // We can promote any unsigned integer type whose size is
1761 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001762 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001763 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001764 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001765 }
1766
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001767 return To->getKind() == BuiltinType::UInt;
1768 }
1769
Richard Smithb9c5a602012-09-13 21:18:54 +00001770 // C++11 [conv.prom]p3:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001771 // A prvalue of an unscoped enumeration type whose underlying type is not
1772 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1773 // following types that can represent all the values of the enumeration
1774 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1775 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001776 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001777 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001778 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001779 // with lowest integer conversion rank (4.13) greater than the rank of long
1780 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001781 // there are two such extended types, the signed one is chosen.
Richard Smithb9c5a602012-09-13 21:18:54 +00001782 // C++11 [conv.prom]p4:
1783 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1784 // can be converted to a prvalue of its underlying type. Moreover, if
1785 // integral promotion can be applied to its underlying type, a prvalue of an
1786 // unscoped enumeration type whose underlying type is fixed can also be
1787 // converted to a prvalue of the promoted underlying type.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001788 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1789 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1790 // provided for a scoped enumeration.
1791 if (FromEnumType->getDecl()->isScoped())
1792 return false;
1793
Richard Smithb9c5a602012-09-13 21:18:54 +00001794 // We can perform an integral promotion to the underlying type of the enum,
1795 // even if that's not the promoted type.
1796 if (FromEnumType->getDecl()->isFixed()) {
1797 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1798 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1799 IsIntegralPromotion(From, Underlying, ToType);
1800 }
1801
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001802 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803 if (ToType->isIntegerType() &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001804 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall56774992009-12-09 09:09:27 +00001805 return Context.hasSameUnqualifiedType(ToType,
1806 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001807 }
John McCall56774992009-12-09 09:09:27 +00001808
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001809 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001810 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1811 // to an rvalue a prvalue of the first of the following types that can
1812 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001813 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001815 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001816 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001817 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001818 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001819 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001820 // Determine whether the type we're converting from is signed or
1821 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001822 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001823 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001825 // The types we'll try to promote to, in the appropriate
1826 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001827 QualType PromoteTypes[6] = {
1828 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001829 Context.LongTy, Context.UnsignedLongTy ,
1830 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001831 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001832 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001833 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1834 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001835 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001836 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1837 // We found the type that we can promote to. If this is the
1838 // type we wanted, we have a promotion. Otherwise, no
1839 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001840 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001841 }
1842 }
1843 }
1844
1845 // An rvalue for an integral bit-field (9.6) can be converted to an
1846 // rvalue of type int if int can represent all the values of the
1847 // bit-field; otherwise, it can be converted to unsigned int if
1848 // unsigned int can represent all the values of the bit-field. If
1849 // the bit-field is larger yet, no integral promotion applies to
1850 // it. If the bit-field has an enumerated type, it is treated as any
1851 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001852 // FIXME: We should delay checking of bit-fields until we actually perform the
1853 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001854 using llvm::APSInt;
1855 if (From)
John McCalld25db7e2013-05-06 21:39:12 +00001856 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001857 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001858 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001859 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1860 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1861 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001862
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001863 // Are we promoting to an int from a bitfield that fits in an int?
1864 if (BitWidth < ToSize ||
1865 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1866 return To->getKind() == BuiltinType::Int;
1867 }
Mike Stump11289f42009-09-09 15:08:12 +00001868
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001869 // Are we promoting to an unsigned int from an unsigned bitfield
1870 // that fits into an unsigned int?
1871 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1872 return To->getKind() == BuiltinType::UInt;
1873 }
Mike Stump11289f42009-09-09 15:08:12 +00001874
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001875 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001876 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001877 }
Mike Stump11289f42009-09-09 15:08:12 +00001878
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001879 // An rvalue of type bool can be converted to an rvalue of type int,
1880 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001881 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001882 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001883 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001884
1885 return false;
1886}
1887
1888/// IsFloatingPointPromotion - Determines whether the conversion from
1889/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1890/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001891bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001892 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1893 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001894 /// An rvalue of type float can be converted to an rvalue of type
1895 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001896 if (FromBuiltin->getKind() == BuiltinType::Float &&
1897 ToBuiltin->getKind() == BuiltinType::Double)
1898 return true;
1899
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001900 // C99 6.3.1.5p1:
1901 // When a float is promoted to double or long double, or a
1902 // double is promoted to long double [...].
David Blaikiebbafb8a2012-03-11 07:00:24 +00001903 if (!getLangOpts().CPlusPlus &&
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001904 (FromBuiltin->getKind() == BuiltinType::Float ||
1905 FromBuiltin->getKind() == BuiltinType::Double) &&
1906 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1907 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001908
1909 // Half can be promoted to float.
Joey Goulydd7f4562013-01-23 11:56:20 +00001910 if (!getLangOpts().NativeHalfType &&
1911 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001912 ToBuiltin->getKind() == BuiltinType::Float)
1913 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001914 }
1915
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001916 return false;
1917}
1918
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001919/// \brief Determine if a conversion is a complex promotion.
1920///
1921/// A complex promotion is defined as a complex -> complex conversion
1922/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001923/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001924bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001925 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001926 if (!FromComplex)
1927 return false;
1928
John McCall9dd450b2009-09-21 23:43:11 +00001929 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001930 if (!ToComplex)
1931 return false;
1932
1933 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001934 ToComplex->getElementType()) ||
1935 IsIntegralPromotion(0, FromComplex->getElementType(),
1936 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001937}
1938
Douglas Gregor237f96c2008-11-26 23:31:11 +00001939/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1940/// the pointer type FromPtr to a pointer to type ToPointee, with the
1941/// same type qualifiers as FromPtr has on its pointee type. ToType,
1942/// if non-empty, will be a pointer to ToType that may or may not have
1943/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001944///
Mike Stump11289f42009-09-09 15:08:12 +00001945static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001946BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001947 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001948 ASTContext &Context,
1949 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001950 assert((FromPtr->getTypeClass() == Type::Pointer ||
1951 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1952 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001953
John McCall31168b02011-06-15 23:02:42 +00001954 /// Conversions to 'id' subsume cv-qualifier conversions.
1955 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001956 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001957
1958 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001959 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001960 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001961 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001962
John McCall31168b02011-06-15 23:02:42 +00001963 if (StripObjCLifetime)
1964 Quals.removeObjCLifetime();
1965
Mike Stump11289f42009-09-09 15:08:12 +00001966 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001967 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001968 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001969 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001970 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001971
1972 // Build a pointer to ToPointee. It has the right qualifiers
1973 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001974 if (isa<ObjCObjectPointerType>(ToType))
1975 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001976 return Context.getPointerType(ToPointee);
1977 }
1978
1979 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001980 QualType QualifiedCanonToPointee
1981 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001982
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001983 if (isa<ObjCObjectPointerType>(ToType))
1984 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1985 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001986}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001987
Mike Stump11289f42009-09-09 15:08:12 +00001988static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001989 bool InOverloadResolution,
1990 ASTContext &Context) {
1991 // Handle value-dependent integral null pointer constants correctly.
1992 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1993 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001994 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001995 return !InOverloadResolution;
1996
Douglas Gregor56751b52009-09-25 04:25:58 +00001997 return Expr->isNullPointerConstant(Context,
1998 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1999 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00002000}
Mike Stump11289f42009-09-09 15:08:12 +00002001
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002002/// IsPointerConversion - Determines whether the conversion of the
2003/// expression From, which has the (possibly adjusted) type FromType,
2004/// can be converted to the type ToType via a pointer conversion (C++
2005/// 4.10). If so, returns true and places the converted type (that
2006/// might differ from ToType in its cv-qualifiers at some level) into
2007/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00002008///
Douglas Gregora29dc052008-11-27 01:19:21 +00002009/// This routine also supports conversions to and from block pointers
2010/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2011/// pointers to interfaces. FIXME: Once we've determined the
2012/// appropriate overloading rules for Objective-C, we may want to
2013/// split the Objective-C checks into a different routine; however,
2014/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00002015/// conversions, so for now they live here. IncompatibleObjC will be
2016/// set if the conversion is an allowed Objective-C conversion that
2017/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002018bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00002019 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00002020 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00002021 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00002022 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00002023 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2024 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00002025 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00002026
Mike Stump11289f42009-09-09 15:08:12 +00002027 // Conversion from a null pointer constant to any Objective-C pointer type.
2028 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002029 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00002030 ConvertedType = ToType;
2031 return true;
2032 }
2033
Douglas Gregor231d1c62008-11-27 00:15:41 +00002034 // Blocks: Block pointers can be converted to void*.
2035 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002036 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002037 ConvertedType = ToType;
2038 return true;
2039 }
2040 // Blocks: A null pointer constant can be converted to a block
2041 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00002042 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002043 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00002044 ConvertedType = ToType;
2045 return true;
2046 }
2047
Sebastian Redl576fd422009-05-10 18:38:11 +00002048 // If the left-hand-side is nullptr_t, the right side can be a null
2049 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00002050 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00002051 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00002052 ConvertedType = ToType;
2053 return true;
2054 }
2055
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002056 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002057 if (!ToTypePtr)
2058 return false;
2059
2060 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00002061 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002062 ConvertedType = ToType;
2063 return true;
2064 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00002065
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002066 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002067 // , including objective-c pointers.
2068 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00002069 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikiebbafb8a2012-03-11 07:00:24 +00002070 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002071 ConvertedType = BuildSimilarlyQualifiedPointerType(
2072 FromType->getAs<ObjCObjectPointerType>(),
2073 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002074 ToType, Context);
2075 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00002076 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002077 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002078 if (!FromTypePtr)
2079 return false;
2080
2081 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002082
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002083 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00002084 // pointer conversion, so don't do all of the work below.
2085 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2086 return false;
2087
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002088 // An rvalue of type "pointer to cv T," where T is an object type,
2089 // can be converted to an rvalue of type "pointer to cv void" (C++
2090 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00002091 if (FromPointeeType->isIncompleteOrObjectType() &&
2092 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002093 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002094 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00002095 ToType, Context,
2096 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002097 return true;
2098 }
2099
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002100 // MSVC allows implicit function to void* type conversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002101 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00002102 ToPointeeType->isVoidType()) {
2103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2104 ToPointeeType,
2105 ToType, Context);
2106 return true;
2107 }
2108
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002109 // When we're overloading in C, we allow a special kind of pointer
2110 // conversion for compatible-but-not-identical pointee types.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002111 if (!getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002112 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002113 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002114 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00002115 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002116 return true;
2117 }
2118
Douglas Gregor5c407d92008-10-23 00:40:37 +00002119 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00002120 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00002121 // An rvalue of type "pointer to cv D," where D is a class type,
2122 // can be converted to an rvalue of type "pointer to cv B," where
2123 // B is a base class (clause 10) of D. If B is an inaccessible
2124 // (clause 11) or ambiguous (10.2) base class of D, a program that
2125 // necessitates this conversion is ill-formed. The result of the
2126 // conversion is a pointer to the base class sub-object of the
2127 // derived class object. The null pointer value is converted to
2128 // the null pointer value of the destination type.
2129 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00002130 // Note that we do not check for ambiguity or inaccessibility
2131 // here. That is handled by CheckPointerConversion.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002132 if (getLangOpts().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002133 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00002134 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002135 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00002136 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00002137 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00002138 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002139 ToType, Context);
2140 return true;
2141 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002142
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00002143 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2144 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2145 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2146 ToPointeeType,
2147 ToType, Context);
2148 return true;
2149 }
2150
Douglas Gregora119f102008-12-19 19:13:09 +00002151 return false;
2152}
Douglas Gregoraec25842011-04-26 23:16:46 +00002153
2154/// \brief Adopt the given qualifiers for the given type.
2155static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2156 Qualifiers TQs = T.getQualifiers();
2157
2158 // Check whether qualifiers already match.
2159 if (TQs == Qs)
2160 return T;
2161
2162 if (Qs.compatiblyIncludes(TQs))
2163 return Context.getQualifiedType(T, Qs);
2164
2165 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2166}
Douglas Gregora119f102008-12-19 19:13:09 +00002167
2168/// isObjCPointerConversion - Determines whether this is an
2169/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2170/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00002171bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00002172 QualType& ConvertedType,
2173 bool &IncompatibleObjC) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002174 if (!getLangOpts().ObjC1)
Douglas Gregora119f102008-12-19 19:13:09 +00002175 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002176
Douglas Gregoraec25842011-04-26 23:16:46 +00002177 // The set of qualifiers on the type we're converting from.
2178 Qualifiers FromQualifiers = FromType.getQualifiers();
2179
Steve Naroff7cae42b2009-07-10 23:34:53 +00002180 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00002181 const ObjCObjectPointerType* ToObjCPtr =
2182 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00002183 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00002184 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002185
Steve Naroff7cae42b2009-07-10 23:34:53 +00002186 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002187 // If the pointee types are the same (ignoring qualifications),
2188 // then this is not a pointer conversion.
2189 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2190 FromObjCPtr->getPointeeType()))
2191 return false;
2192
Douglas Gregoraec25842011-04-26 23:16:46 +00002193 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00002194 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00002195 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00002196 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002197 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002198 return true;
2199 }
2200 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00002201 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00002202 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00002203 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00002204 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002205 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002206 return true;
2207 }
2208 // Objective C++: We're able to convert from a pointer to an
2209 // interface to a pointer to a different interface.
2210 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002211 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2212 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002213 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianb397e432010-03-15 18:36:00 +00002214 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2215 FromObjCPtr->getPointeeType()))
2216 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002217 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002218 ToObjCPtr->getPointeeType(),
2219 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002220 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002221 return true;
2222 }
2223
2224 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2225 // Okay: this is some kind of implicit downcast of Objective-C
2226 // interfaces, which is permitted. However, we're going to
2227 // complain about it.
2228 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002229 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002230 ToObjCPtr->getPointeeType(),
2231 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00002232 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00002233 return true;
2234 }
Mike Stump11289f42009-09-09 15:08:12 +00002235 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002236 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00002237 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002238 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002239 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002240 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002241 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002242 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002243 // to a block pointer type.
2244 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00002245 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002246 return true;
2247 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002248 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00002249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002250 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002251 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002252 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00002253 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00002254 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00002255 return true;
2256 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00002257 else
Douglas Gregora119f102008-12-19 19:13:09 +00002258 return false;
2259
Douglas Gregor033f56d2008-12-23 00:53:59 +00002260 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002261 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002262 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00002263 else if (const BlockPointerType *FromBlockPtr =
2264 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00002265 FromPointeeType = FromBlockPtr->getPointeeType();
2266 else
Douglas Gregora119f102008-12-19 19:13:09 +00002267 return false;
2268
Douglas Gregora119f102008-12-19 19:13:09 +00002269 // If we have pointers to pointers, recursively check whether this
2270 // is an Objective-C conversion.
2271 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2272 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2273 IncompatibleObjC)) {
2274 // We always complain about this conversion.
2275 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002276 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002277 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002278 return true;
2279 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002280 // Allow conversion of pointee being objective-c pointer to another one;
2281 // as in I* to id.
2282 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2283 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2284 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2285 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00002286
Douglas Gregor8d6d0672010-12-01 21:43:58 +00002287 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00002288 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00002289 return true;
2290 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002291
Douglas Gregor033f56d2008-12-23 00:53:59 +00002292 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00002293 // differences in the argument and result types are in Objective-C
2294 // pointer conversions. If so, we permit the conversion (but
2295 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00002296 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002297 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002298 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00002299 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00002300 if (FromFunctionType && ToFunctionType) {
2301 // If the function types are exactly the same, this isn't an
2302 // Objective-C pointer conversion.
2303 if (Context.getCanonicalType(FromPointeeType)
2304 == Context.getCanonicalType(ToPointeeType))
2305 return false;
2306
2307 // Perform the quick checks that will tell us whether these
2308 // function types are obviously different.
2309 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2310 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2311 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2312 return false;
2313
2314 bool HasObjCConversion = false;
2315 if (Context.getCanonicalType(FromFunctionType->getResultType())
2316 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2317 // Okay, the types match exactly. Nothing to do.
2318 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2319 ToFunctionType->getResultType(),
2320 ConvertedType, IncompatibleObjC)) {
2321 // Okay, we have an Objective-C pointer conversion.
2322 HasObjCConversion = true;
2323 } else {
2324 // Function types are too different. Abort.
2325 return false;
2326 }
Mike Stump11289f42009-09-09 15:08:12 +00002327
Douglas Gregora119f102008-12-19 19:13:09 +00002328 // Check argument types.
2329 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2330 ArgIdx != NumArgs; ++ArgIdx) {
2331 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2332 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2333 if (Context.getCanonicalType(FromArgType)
2334 == Context.getCanonicalType(ToArgType)) {
2335 // Okay, the types match exactly. Nothing to do.
2336 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2337 ConvertedType, IncompatibleObjC)) {
2338 // Okay, we have an Objective-C pointer conversion.
2339 HasObjCConversion = true;
2340 } else {
2341 // Argument types are too different. Abort.
2342 return false;
2343 }
2344 }
2345
2346 if (HasObjCConversion) {
2347 // We had an Objective-C conversion. Allow this pointer
2348 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002349 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002350 IncompatibleObjC = true;
2351 return true;
2352 }
2353 }
2354
Sebastian Redl72b597d2009-01-25 19:43:20 +00002355 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002356}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002357
John McCall31168b02011-06-15 23:02:42 +00002358/// \brief Determine whether this is an Objective-C writeback conversion,
2359/// used for parameter passing when performing automatic reference counting.
2360///
2361/// \param FromType The type we're converting form.
2362///
2363/// \param ToType The type we're converting to.
2364///
2365/// \param ConvertedType The type that will be produced after applying
2366/// this conversion.
2367bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2368 QualType &ConvertedType) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002369 if (!getLangOpts().ObjCAutoRefCount ||
John McCall31168b02011-06-15 23:02:42 +00002370 Context.hasSameUnqualifiedType(FromType, ToType))
2371 return false;
2372
2373 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2374 QualType ToPointee;
2375 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2376 ToPointee = ToPointer->getPointeeType();
2377 else
2378 return false;
2379
2380 Qualifiers ToQuals = ToPointee.getQualifiers();
2381 if (!ToPointee->isObjCLifetimeType() ||
2382 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall18ce25e2012-02-08 00:46:36 +00002383 !ToQuals.withoutObjCLifetime().empty())
John McCall31168b02011-06-15 23:02:42 +00002384 return false;
2385
2386 // Argument must be a pointer to __strong to __weak.
2387 QualType FromPointee;
2388 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2389 FromPointee = FromPointer->getPointeeType();
2390 else
2391 return false;
2392
2393 Qualifiers FromQuals = FromPointee.getQualifiers();
2394 if (!FromPointee->isObjCLifetimeType() ||
2395 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2396 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2397 return false;
2398
2399 // Make sure that we have compatible qualifiers.
2400 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2401 if (!ToQuals.compatiblyIncludes(FromQuals))
2402 return false;
2403
2404 // Remove qualifiers from the pointee type we're converting from; they
2405 // aren't used in the compatibility check belong, and we'll be adding back
2406 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2407 FromPointee = FromPointee.getUnqualifiedType();
2408
2409 // The unqualified form of the pointee types must be compatible.
2410 ToPointee = ToPointee.getUnqualifiedType();
2411 bool IncompatibleObjC;
2412 if (Context.typesAreCompatible(FromPointee, ToPointee))
2413 FromPointee = ToPointee;
2414 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2415 IncompatibleObjC))
2416 return false;
2417
2418 /// \brief Construct the type we're converting to, which is a pointer to
2419 /// __autoreleasing pointee.
2420 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2421 ConvertedType = Context.getPointerType(FromPointee);
2422 return true;
2423}
2424
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002425bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2426 QualType& ConvertedType) {
2427 QualType ToPointeeType;
2428 if (const BlockPointerType *ToBlockPtr =
2429 ToType->getAs<BlockPointerType>())
2430 ToPointeeType = ToBlockPtr->getPointeeType();
2431 else
2432 return false;
2433
2434 QualType FromPointeeType;
2435 if (const BlockPointerType *FromBlockPtr =
2436 FromType->getAs<BlockPointerType>())
2437 FromPointeeType = FromBlockPtr->getPointeeType();
2438 else
2439 return false;
2440 // We have pointer to blocks, check whether the only
2441 // differences in the argument and result types are in Objective-C
2442 // pointer conversions. If so, we permit the conversion.
2443
2444 const FunctionProtoType *FromFunctionType
2445 = FromPointeeType->getAs<FunctionProtoType>();
2446 const FunctionProtoType *ToFunctionType
2447 = ToPointeeType->getAs<FunctionProtoType>();
2448
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002449 if (!FromFunctionType || !ToFunctionType)
2450 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002451
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002452 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002453 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002454
2455 // Perform the quick checks that will tell us whether these
2456 // function types are obviously different.
2457 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2458 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2459 return false;
2460
2461 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2462 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2463 if (FromEInfo != ToEInfo)
2464 return false;
2465
2466 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002467 if (Context.hasSameType(FromFunctionType->getResultType(),
2468 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002469 // Okay, the types match exactly. Nothing to do.
2470 } else {
2471 QualType RHS = FromFunctionType->getResultType();
2472 QualType LHS = ToFunctionType->getResultType();
David Blaikiebbafb8a2012-03-11 07:00:24 +00002473 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002474 !RHS.hasQualifiers() && LHS.hasQualifiers())
2475 LHS = LHS.getUnqualifiedType();
2476
2477 if (Context.hasSameType(RHS,LHS)) {
2478 // OK exact match.
2479 } else if (isObjCPointerConversion(RHS, LHS,
2480 ConvertedType, IncompatibleObjC)) {
2481 if (IncompatibleObjC)
2482 return false;
2483 // Okay, we have an Objective-C pointer conversion.
2484 }
2485 else
2486 return false;
2487 }
2488
2489 // Check argument types.
2490 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2491 ArgIdx != NumArgs; ++ArgIdx) {
2492 IncompatibleObjC = false;
2493 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2494 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2495 if (Context.hasSameType(FromArgType, ToArgType)) {
2496 // Okay, the types match exactly. Nothing to do.
2497 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2498 ConvertedType, IncompatibleObjC)) {
2499 if (IncompatibleObjC)
2500 return false;
2501 // Okay, we have an Objective-C pointer conversion.
2502 } else
2503 // Argument types are too different. Abort.
2504 return false;
2505 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002506 if (LangOpts.ObjCAutoRefCount &&
2507 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2508 ToFunctionType))
2509 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002510
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002511 ConvertedType = ToType;
2512 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002513}
2514
Richard Trieucaff2472011-11-23 22:32:32 +00002515enum {
2516 ft_default,
2517 ft_different_class,
2518 ft_parameter_arity,
2519 ft_parameter_mismatch,
2520 ft_return_type,
2521 ft_qualifer_mismatch
2522};
2523
2524/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2525/// function types. Catches different number of parameter, mismatch in
2526/// parameter types, and different return types.
2527void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2528 QualType FromType, QualType ToType) {
Richard Trieu96ed5b62011-12-13 23:19:45 +00002529 // If either type is not valid, include no extra info.
2530 if (FromType.isNull() || ToType.isNull()) {
2531 PDiag << ft_default;
2532 return;
2533 }
2534
Richard Trieucaff2472011-11-23 22:32:32 +00002535 // Get the function type from the pointers.
2536 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2537 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2538 *ToMember = ToType->getAs<MemberPointerType>();
2539 if (FromMember->getClass() != ToMember->getClass()) {
2540 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2541 << QualType(FromMember->getClass(), 0);
2542 return;
2543 }
2544 FromType = FromMember->getPointeeType();
2545 ToType = ToMember->getPointeeType();
Richard Trieucaff2472011-11-23 22:32:32 +00002546 }
2547
Richard Trieu96ed5b62011-12-13 23:19:45 +00002548 if (FromType->isPointerType())
2549 FromType = FromType->getPointeeType();
2550 if (ToType->isPointerType())
2551 ToType = ToType->getPointeeType();
2552
2553 // Remove references.
Richard Trieucaff2472011-11-23 22:32:32 +00002554 FromType = FromType.getNonReferenceType();
2555 ToType = ToType.getNonReferenceType();
2556
Richard Trieucaff2472011-11-23 22:32:32 +00002557 // Don't print extra info for non-specialized template functions.
2558 if (FromType->isInstantiationDependentType() &&
2559 !FromType->getAs<TemplateSpecializationType>()) {
2560 PDiag << ft_default;
2561 return;
2562 }
2563
Richard Trieu96ed5b62011-12-13 23:19:45 +00002564 // No extra info for same types.
2565 if (Context.hasSameType(FromType, ToType)) {
2566 PDiag << ft_default;
2567 return;
2568 }
2569
Richard Trieucaff2472011-11-23 22:32:32 +00002570 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2571 *ToFunction = ToType->getAs<FunctionProtoType>();
2572
2573 // Both types need to be function types.
2574 if (!FromFunction || !ToFunction) {
2575 PDiag << ft_default;
2576 return;
2577 }
2578
2579 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2580 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2581 << FromFunction->getNumArgs();
2582 return;
2583 }
2584
2585 // Handle different parameter types.
2586 unsigned ArgPos;
2587 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2588 PDiag << ft_parameter_mismatch << ArgPos + 1
2589 << ToFunction->getArgType(ArgPos)
2590 << FromFunction->getArgType(ArgPos);
2591 return;
2592 }
2593
2594 // Handle different return type.
2595 if (!Context.hasSameType(FromFunction->getResultType(),
2596 ToFunction->getResultType())) {
2597 PDiag << ft_return_type << ToFunction->getResultType()
2598 << FromFunction->getResultType();
2599 return;
2600 }
2601
2602 unsigned FromQuals = FromFunction->getTypeQuals(),
2603 ToQuals = ToFunction->getTypeQuals();
2604 if (FromQuals != ToQuals) {
2605 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2606 return;
2607 }
2608
2609 // Unable to find a difference, so add no extra info.
2610 PDiag << ft_default;
2611}
2612
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002613/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregor2039ca02011-12-15 17:15:07 +00002614/// for equality of their argument types. Caller has already checked that
Eli Friedman5f508952013-06-18 22:41:37 +00002615/// they have same number of arguments. If the parameters are different,
2616/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002617bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002618 const FunctionProtoType *NewType,
2619 unsigned *ArgPos) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002620 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2621 N = NewType->arg_type_begin(),
2622 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Richard Trieu4b03d982013-08-09 21:42:32 +00002623 if (!Context.hasSameType(O->getUnqualifiedType(),
2624 N->getUnqualifiedType())) {
Larisse Voufo4154f462013-08-06 03:57:41 +00002625 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2626 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002627 }
2628 }
2629 return true;
2630}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002631
Douglas Gregor39c16d42008-10-24 04:54:22 +00002632/// CheckPointerConversion - Check the pointer conversion from the
2633/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002634/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002635/// conversions for which IsPointerConversion has already returned
2636/// true. It returns true and produces a diagnostic if there was an
2637/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002638bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002639 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002640 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002641 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002642 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002643 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002644
John McCall8cb679e2010-11-15 09:13:47 +00002645 Kind = CK_BitCast;
2646
David Blaikie1c7c8f72012-08-08 17:33:31 +00002647 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2648 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2649 Expr::NPCK_ZeroExpression) {
2650 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2651 DiagRuntimeBehavior(From->getExprLoc(), From,
2652 PDiag(diag::warn_impcast_bool_to_null_pointer)
2653 << ToType << From->getSourceRange());
2654 else if (!isUnevaluatedContext())
2655 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2656 << ToType << From->getSourceRange();
2657 }
John McCall9320b872011-09-09 05:25:32 +00002658 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2659 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002660 QualType FromPointeeType = FromPtrType->getPointeeType(),
2661 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002662
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002663 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2664 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002665 // We must have a derived-to-base conversion. Check an
2666 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002667 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2668 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002669 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002670 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002671 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002673 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002674 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002675 }
2676 }
John McCall9320b872011-09-09 05:25:32 +00002677 } else if (const ObjCObjectPointerType *ToPtrType =
2678 ToType->getAs<ObjCObjectPointerType>()) {
2679 if (const ObjCObjectPointerType *FromPtrType =
2680 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002681 // Objective-C++ conversions are always okay.
2682 // FIXME: We should have a different class of conversions for the
2683 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002684 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002685 return false;
John McCall9320b872011-09-09 05:25:32 +00002686 } else if (FromType->isBlockPointerType()) {
2687 Kind = CK_BlockPointerToObjCPointerCast;
2688 } else {
2689 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002690 }
John McCall9320b872011-09-09 05:25:32 +00002691 } else if (ToType->isBlockPointerType()) {
2692 if (!FromType->isBlockPointerType())
2693 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002694 }
John McCall8cb679e2010-11-15 09:13:47 +00002695
2696 // We shouldn't fall into this case unless it's valid for other
2697 // reasons.
2698 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2699 Kind = CK_NullToPointer;
2700
Douglas Gregor39c16d42008-10-24 04:54:22 +00002701 return false;
2702}
2703
Sebastian Redl72b597d2009-01-25 19:43:20 +00002704/// IsMemberPointerConversion - Determines whether the conversion of the
2705/// expression From, which has the (possibly adjusted) type FromType, can be
2706/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2707/// If so, returns true and places the converted type (that might differ from
2708/// ToType in its cv-qualifiers at some level) into ConvertedType.
2709bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002711 bool InOverloadResolution,
2712 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002713 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002714 if (!ToTypePtr)
2715 return false;
2716
2717 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002718 if (From->isNullPointerConstant(Context,
2719 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2720 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002721 ConvertedType = ToType;
2722 return true;
2723 }
2724
2725 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002726 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002727 if (!FromTypePtr)
2728 return false;
2729
2730 // A pointer to member of B can be converted to a pointer to member of D,
2731 // where D is derived from B (C++ 4.11p2).
2732 QualType FromClass(FromTypePtr->getClass(), 0);
2733 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002734
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002735 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00002736 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002737 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002738 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2739 ToClass.getTypePtr());
2740 return true;
2741 }
2742
2743 return false;
2744}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002745
Sebastian Redl72b597d2009-01-25 19:43:20 +00002746/// CheckMemberPointerConversion - Check the member pointer conversion from the
2747/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002748/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002749/// for which IsMemberPointerConversion has already returned true. It returns
2750/// true and produces a diagnostic if there was an error, or returns false
2751/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002752bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002753 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002754 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002755 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002756 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002757 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002758 if (!FromPtrType) {
2759 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002761 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002762 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002763 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002764 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002765 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002766
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002767 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002768 assert(ToPtrType && "No member pointer cast has a target type "
2769 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002770
Sebastian Redled8f2002009-01-28 18:33:18 +00002771 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2772 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002773
Sebastian Redled8f2002009-01-28 18:33:18 +00002774 // FIXME: What about dependent types?
2775 assert(FromClass->isRecordType() && "Pointer into non-class.");
2776 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002777
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002778 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002779 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002780 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2781 assert(DerivationOkay &&
2782 "Should not have been called if derivation isn't OK.");
2783 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002784
Sebastian Redled8f2002009-01-28 18:33:18 +00002785 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2786 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002787 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2788 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2789 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2790 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002791 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002792
Douglas Gregor89ee6822009-02-28 01:32:25 +00002793 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002794 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2795 << FromClass << ToClass << QualType(VBase, 0)
2796 << From->getSourceRange();
2797 return true;
2798 }
2799
John McCall5b0829a2010-02-10 09:31:12 +00002800 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002801 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2802 Paths.front(),
2803 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002804
Anders Carlssond7923c62009-08-22 23:33:40 +00002805 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002806 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002807 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002808 return false;
2809}
2810
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002811/// Determine whether the lifetime conversion between the two given
2812/// qualifiers sets is nontrivial.
2813static bool isNonTrivialObjCLifetimeConversion(Qualifiers FromQuals,
2814 Qualifiers ToQuals) {
2815 // Converting anything to const __unsafe_unretained is trivial.
2816 if (ToQuals.hasConst() &&
2817 ToQuals.getObjCLifetime() == Qualifiers::OCL_ExplicitNone)
2818 return false;
2819
2820 return true;
2821}
2822
Douglas Gregor9a657932008-10-21 23:43:52 +00002823/// IsQualificationConversion - Determines whether the conversion from
2824/// an rvalue of type FromType to ToType is a qualification conversion
2825/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002826///
2827/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2828/// when the qualification conversion involves a change in the Objective-C
2829/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002830bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002831Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002832 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002833 FromType = Context.getCanonicalType(FromType);
2834 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002835 ObjCLifetimeConversion = false;
2836
Douglas Gregor9a657932008-10-21 23:43:52 +00002837 // If FromType and ToType are the same type, this is not a
2838 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002839 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002840 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002841
Douglas Gregor9a657932008-10-21 23:43:52 +00002842 // (C++ 4.4p4):
2843 // A conversion can add cv-qualifiers at levels other than the first
2844 // in multi-level pointers, subject to the following rules: [...]
2845 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002846 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002847 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002848 // Within each iteration of the loop, we check the qualifiers to
2849 // determine if this still looks like a qualification
2850 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002851 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002852 // until there are no more pointers or pointers-to-members left to
2853 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002854 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002855
Douglas Gregor90609aa2011-04-25 18:40:17 +00002856 Qualifiers FromQuals = FromType.getQualifiers();
2857 Qualifiers ToQuals = ToType.getQualifiers();
2858
John McCall31168b02011-06-15 23:02:42 +00002859 // Objective-C ARC:
2860 // Check Objective-C lifetime conversions.
2861 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2862 UnwrappedAnyPointer) {
2863 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00002864 if (isNonTrivialObjCLifetimeConversion(FromQuals, ToQuals))
2865 ObjCLifetimeConversion = true;
John McCall31168b02011-06-15 23:02:42 +00002866 FromQuals.removeObjCLifetime();
2867 ToQuals.removeObjCLifetime();
2868 } else {
2869 // Qualification conversions cannot cast between different
2870 // Objective-C lifetime qualifiers.
2871 return false;
2872 }
2873 }
2874
Douglas Gregorf30053d2011-05-08 06:09:53 +00002875 // Allow addition/removal of GC attributes but not changing GC attributes.
2876 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2877 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2878 FromQuals.removeObjCGCAttr();
2879 ToQuals.removeObjCGCAttr();
2880 }
2881
Douglas Gregor9a657932008-10-21 23:43:52 +00002882 // -- for every j > 0, if const is in cv 1,j then const is in cv
2883 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002884 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002885 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002886
Douglas Gregor9a657932008-10-21 23:43:52 +00002887 // -- if the cv 1,j and cv 2,j are different, then const is in
2888 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002889 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002890 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002891 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002892
Douglas Gregor9a657932008-10-21 23:43:52 +00002893 // Keep track of whether all prior cv-qualifiers in the "to" type
2894 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002895 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002896 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002897 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002898
2899 // We are left with FromType and ToType being the pointee types
2900 // after unwrapping the original FromType and ToType the same number
2901 // of types. If we unwrapped any pointers, and if FromType and
2902 // ToType have the same unqualified type (since we checked
2903 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002904 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002905}
2906
Douglas Gregorc79862f2012-04-12 17:51:55 +00002907/// \brief - Determine whether this is a conversion from a scalar type to an
2908/// atomic type.
2909///
2910/// If successful, updates \c SCS's second and third steps in the conversion
2911/// sequence to finish the conversion.
Douglas Gregorf9e36cc2012-04-12 20:48:09 +00002912static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2913 bool InOverloadResolution,
2914 StandardConversionSequence &SCS,
2915 bool CStyle) {
Douglas Gregorc79862f2012-04-12 17:51:55 +00002916 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2917 if (!ToAtomic)
2918 return false;
2919
2920 StandardConversionSequence InnerSCS;
2921 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2922 InOverloadResolution, InnerSCS,
2923 CStyle, /*AllowObjCWritebackConversion=*/false))
2924 return false;
2925
2926 SCS.Second = InnerSCS.Second;
2927 SCS.setToType(1, InnerSCS.getToType(1));
2928 SCS.Third = InnerSCS.Third;
2929 SCS.QualificationIncludesObjCLifetime
2930 = InnerSCS.QualificationIncludesObjCLifetime;
2931 SCS.setToType(2, InnerSCS.getToType(2));
2932 return true;
2933}
2934
Sebastian Redle5417162012-03-27 18:33:03 +00002935static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2936 CXXConstructorDecl *Constructor,
2937 QualType Type) {
2938 const FunctionProtoType *CtorType =
2939 Constructor->getType()->getAs<FunctionProtoType>();
2940 if (CtorType->getNumArgs() > 0) {
2941 QualType FirstArg = CtorType->getArgType(0);
2942 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2943 return true;
2944 }
2945 return false;
2946}
2947
Sebastian Redl82ace982012-02-11 23:51:08 +00002948static OverloadingResult
2949IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2950 CXXRecordDecl *To,
2951 UserDefinedConversionSequence &User,
2952 OverloadCandidateSet &CandidateSet,
2953 bool AllowExplicit) {
David Blaikieff7d47a2012-12-19 00:45:41 +00002954 DeclContext::lookup_result R = S.LookupConstructors(To);
2955 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl82ace982012-02-11 23:51:08 +00002956 Con != ConEnd; ++Con) {
2957 NamedDecl *D = *Con;
2958 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2959
2960 // Find the constructor (which may be a template).
2961 CXXConstructorDecl *Constructor = 0;
2962 FunctionTemplateDecl *ConstructorTmpl
2963 = dyn_cast<FunctionTemplateDecl>(D);
2964 if (ConstructorTmpl)
2965 Constructor
2966 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2967 else
2968 Constructor = cast<CXXConstructorDecl>(D);
2969
2970 bool Usable = !Constructor->isInvalidDecl() &&
2971 S.isInitListConstructor(Constructor) &&
2972 (AllowExplicit || !Constructor->isExplicit());
2973 if (Usable) {
Sebastian Redle5417162012-03-27 18:33:03 +00002974 // If the first argument is (a reference to) the target type,
2975 // suppress conversions.
2976 bool SuppressUserConversions =
2977 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl82ace982012-02-11 23:51:08 +00002978 if (ConstructorTmpl)
2979 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2980 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002981 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002982 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002983 else
2984 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00002985 From, CandidateSet,
Sebastian Redle5417162012-03-27 18:33:03 +00002986 SuppressUserConversions);
Sebastian Redl82ace982012-02-11 23:51:08 +00002987 }
2988 }
2989
2990 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2991
2992 OverloadCandidateSet::iterator Best;
2993 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2994 case OR_Success: {
2995 // Record the standard conversion we used and the conversion function.
2996 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl82ace982012-02-11 23:51:08 +00002997 QualType ThisType = Constructor->getThisType(S.Context);
2998 // Initializer lists don't have conversions as such.
2999 User.Before.setAsIdentityConversion();
3000 User.HadMultipleCandidates = HadMultipleCandidates;
3001 User.ConversionFunction = Constructor;
3002 User.FoundConversionFunction = Best->FoundDecl;
3003 User.After.setAsIdentityConversion();
3004 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3005 User.After.setAllToTypes(ToType);
3006 return OR_Success;
3007 }
3008
3009 case OR_No_Viable_Function:
3010 return OR_No_Viable_Function;
3011 case OR_Deleted:
3012 return OR_Deleted;
3013 case OR_Ambiguous:
3014 return OR_Ambiguous;
3015 }
3016
3017 llvm_unreachable("Invalid OverloadResult!");
3018}
3019
Douglas Gregor576e98c2009-01-30 23:27:23 +00003020/// Determines whether there is a user-defined conversion sequence
3021/// (C++ [over.ics.user]) that converts expression From to the type
3022/// ToType. If such a conversion exists, User will contain the
3023/// user-defined conversion sequence that performs such a conversion
3024/// and this routine will return true. Otherwise, this routine returns
3025/// false and User is unspecified.
3026///
Douglas Gregor576e98c2009-01-30 23:27:23 +00003027/// \param AllowExplicit true if the conversion should consider C++0x
3028/// "explicit" conversion functions as well as non-explicit conversion
3029/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor4b60a152013-11-07 22:34:54 +00003030///
3031/// \param AllowObjCConversionOnExplicit true if the conversion should
3032/// allow an extra Objective-C pointer conversion on uses of explicit
3033/// constructors. Requires \c AllowExplicit to also be set.
John McCall5c32be02010-08-24 20:38:10 +00003034static OverloadingResult
3035IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl82ace982012-02-11 23:51:08 +00003036 UserDefinedConversionSequence &User,
3037 OverloadCandidateSet &CandidateSet,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003038 bool AllowExplicit,
3039 bool AllowObjCConversionOnExplicit) {
Douglas Gregor2ee1d992013-11-08 01:20:25 +00003040 assert(AllowExplicit || !AllowObjCConversionOnExplicit);
Douglas Gregor4b60a152013-11-07 22:34:54 +00003041
Douglas Gregor5ab11652010-04-17 22:01:05 +00003042 // Whether we will only visit constructors.
3043 bool ConstructorsOnly = false;
3044
3045 // If the type we are conversion to is a class type, enumerate its
3046 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003047 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00003048 // C++ [over.match.ctor]p1:
3049 // When objects of class type are direct-initialized (8.5), or
3050 // copy-initialized from an expression of the same or a
3051 // derived class type (8.5), overload resolution selects the
3052 // constructor. [...] For copy-initialization, the candidate
3053 // functions are all the converting constructors (12.3.1) of
3054 // that class. The argument list is the expression-list within
3055 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00003056 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00003057 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00003058 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00003059 ConstructorsOnly = true;
3060
Benjamin Kramer90633e32012-11-23 17:04:52 +00003061 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00003062 // RequireCompleteType may have returned true due to some invalid decl
3063 // during template instantiation, but ToType may be complete enough now
3064 // to try to recover.
3065 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00003066 // We're not going to find any constructors.
3067 } else if (CXXRecordDecl *ToRecordDecl
3068 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003069
3070 Expr **Args = &From;
3071 unsigned NumArgs = 1;
3072 bool ListInitializing = false;
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003073 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003074 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl82ace982012-02-11 23:51:08 +00003075 OverloadingResult Result = IsInitializerListConstructorConversion(
3076 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3077 if (Result != OR_No_Viable_Function)
3078 return Result;
3079 // Never mind.
3080 CandidateSet.clear();
3081
3082 // If we're list-initializing, we pass the individual elements as
3083 // arguments, not the entire list.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003084 Args = InitList->getInits();
3085 NumArgs = InitList->getNumInits();
3086 ListInitializing = true;
3087 }
3088
David Blaikieff7d47a2012-12-19 00:45:41 +00003089 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3090 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregor89ee6822009-02-28 01:32:25 +00003091 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00003092 NamedDecl *D = *Con;
3093 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3094
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003095 // Find the constructor (which may be a template).
3096 CXXConstructorDecl *Constructor = 0;
3097 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00003098 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003099 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00003100 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003101 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3102 else
John McCalla0296f72010-03-19 07:35:19 +00003103 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003104
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003105 bool Usable = !Constructor->isInvalidDecl();
3106 if (ListInitializing)
3107 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3108 else
3109 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3110 if (Usable) {
Sebastian Redld9170b02012-03-20 21:24:14 +00003111 bool SuppressUserConversions = !ConstructorsOnly;
3112 if (SuppressUserConversions && ListInitializing) {
3113 SuppressUserConversions = false;
3114 if (NumArgs == 1) {
3115 // If the first argument is (a reference to) the target type,
3116 // suppress conversions.
Sebastian Redle5417162012-03-27 18:33:03 +00003117 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3118 S.Context, Constructor, ToType);
Sebastian Redld9170b02012-03-20 21:24:14 +00003119 }
3120 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003121 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00003122 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3123 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003124 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003125 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003126 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00003127 // Allow one user-defined conversion when user specifies a
3128 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00003129 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003130 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redld9170b02012-03-20 21:24:14 +00003131 CandidateSet, SuppressUserConversions);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00003132 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00003133 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003134 }
3135 }
3136
Douglas Gregor5ab11652010-04-17 22:01:05 +00003137 // Enumerate conversion functions, if we're allowed to.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003138 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003139 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003140 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00003141 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00003142 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00003143 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003144 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3145 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00003146 std::pair<CXXRecordDecl::conversion_iterator,
3147 CXXRecordDecl::conversion_iterator>
3148 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3149 for (CXXRecordDecl::conversion_iterator
3150 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00003151 DeclAccessPair FoundDecl = I.getPair();
3152 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003153 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3154 if (isa<UsingShadowDecl>(D))
3155 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3156
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003157 CXXConversionDecl *Conv;
3158 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00003159 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3160 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003161 else
John McCallda4458e2010-03-31 01:36:47 +00003162 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003163
3164 if (AllowExplicit || !Conv->isExplicit()) {
3165 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00003166 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3167 ActingContext, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003168 CandidateSet,
3169 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003170 else
John McCall5c32be02010-08-24 20:38:10 +00003171 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003172 From, ToType, CandidateSet,
3173 AllowObjCConversionOnExplicit);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00003174 }
3175 }
3176 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00003177 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003178
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003179 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3180
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003181 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003182 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00003183 case OR_Success:
3184 // Record the standard conversion we used and the conversion function.
3185 if (CXXConstructorDecl *Constructor
3186 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3187 // C++ [over.ics.user]p1:
3188 // If the user-defined conversion is specified by a
3189 // constructor (12.3.1), the initial standard conversion
3190 // sequence converts the source type to the type required by
3191 // the argument of the constructor.
3192 //
3193 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00003194 if (isa<InitListExpr>(From)) {
3195 // Initializer lists don't have conversions as such.
3196 User.Before.setAsIdentityConversion();
3197 } else {
3198 if (Best->Conversions[0].isEllipsis())
3199 User.EllipsisConversion = true;
3200 else {
3201 User.Before = Best->Conversions[0].Standard;
3202 User.EllipsisConversion = false;
3203 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003204 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003205 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003206 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00003207 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003208 User.After.setAsIdentityConversion();
3209 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3210 User.After.setAllToTypes(ToType);
3211 return OR_Success;
David Blaikie8a40f702012-01-17 06:56:22 +00003212 }
3213 if (CXXConversionDecl *Conversion
John McCall5c32be02010-08-24 20:38:10 +00003214 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3215 // C++ [over.ics.user]p1:
3216 //
3217 // [...] If the user-defined conversion is specified by a
3218 // conversion function (12.3.2), the initial standard
3219 // conversion sequence converts the source type to the
3220 // implicit object parameter of the conversion function.
3221 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003222 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00003223 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00003224 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00003225 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00003226
John McCall5c32be02010-08-24 20:38:10 +00003227 // C++ [over.ics.user]p2:
3228 // The second standard conversion sequence converts the
3229 // result of the user-defined conversion to the target type
3230 // for the sequence. Since an implicit conversion sequence
3231 // is an initialization, the special rules for
3232 // initialization by user-defined conversion apply when
3233 // selecting the best user-defined conversion for a
3234 // user-defined conversion sequence (see 13.3.3 and
3235 // 13.3.3.1).
3236 User.After = Best->FinalConversion;
3237 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003238 }
David Blaikie8a40f702012-01-17 06:56:22 +00003239 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003240
John McCall5c32be02010-08-24 20:38:10 +00003241 case OR_No_Viable_Function:
3242 return OR_No_Viable_Function;
3243 case OR_Deleted:
3244 // No conversion here! We're done.
3245 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246
John McCall5c32be02010-08-24 20:38:10 +00003247 case OR_Ambiguous:
3248 return OR_Ambiguous;
3249 }
3250
David Blaikie8a40f702012-01-17 06:56:22 +00003251 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003252}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003254bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00003255Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003256 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00003257 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003258 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00003259 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor4b60a152013-11-07 22:34:54 +00003260 CandidateSet, false, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00003261 if (OvResult == OR_Ambiguous)
Daniel Dunbar62ee6412012-03-09 18:35:03 +00003262 Diag(From->getLocStart(),
Fariborz Jahanian76197412009-11-18 18:26:29 +00003263 diag::err_typecheck_ambiguous_condition)
3264 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003265 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo70bb43a2013-06-27 03:36:30 +00003266 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo64cf3ef2013-06-27 01:50:25 +00003267 diag::err_typecheck_nonviable_condition_incomplete,
3268 From->getType(), From->getSourceRange()))
3269 Diag(From->getLocStart(),
3270 diag::err_typecheck_nonviable_condition)
3271 << From->getType() << From->getSourceRange() << ToType;
3272 }
Fariborz Jahanian76197412009-11-18 18:26:29 +00003273 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003274 return false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00003275 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003276 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003277}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00003278
Douglas Gregor2837aa22012-02-22 17:32:19 +00003279/// \brief Compare the user-defined conversion functions or constructors
3280/// of two user-defined conversion sequences to determine whether any ordering
3281/// is possible.
3282static ImplicitConversionSequence::CompareKind
3283compareConversionFunctions(Sema &S,
3284 FunctionDecl *Function1,
3285 FunctionDecl *Function2) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003286 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregor2837aa22012-02-22 17:32:19 +00003287 return ImplicitConversionSequence::Indistinguishable;
3288
3289 // Objective-C++:
3290 // If both conversion functions are implicitly-declared conversions from
3291 // a lambda closure type to a function pointer and a block pointer,
3292 // respectively, always prefer the conversion to a function pointer,
3293 // because the function pointer is more lightweight and is more likely
3294 // to keep code working.
3295 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3296 if (!Conv1)
3297 return ImplicitConversionSequence::Indistinguishable;
3298
3299 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3300 if (!Conv2)
3301 return ImplicitConversionSequence::Indistinguishable;
3302
3303 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3304 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3305 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3306 if (Block1 != Block2)
3307 return Block1? ImplicitConversionSequence::Worse
3308 : ImplicitConversionSequence::Better;
3309 }
3310
3311 return ImplicitConversionSequence::Indistinguishable;
3312}
3313
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003314/// CompareImplicitConversionSequences - Compare two implicit
3315/// conversion sequences to determine whether one is better than the
3316/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00003317static ImplicitConversionSequence::CompareKind
3318CompareImplicitConversionSequences(Sema &S,
3319 const ImplicitConversionSequence& ICS1,
3320 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003321{
3322 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3323 // conversion sequences (as defined in 13.3.3.1)
3324 // -- a standard conversion sequence (13.3.3.1.1) is a better
3325 // conversion sequence than a user-defined conversion sequence or
3326 // an ellipsis conversion sequence, and
3327 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3328 // conversion sequence than an ellipsis conversion sequence
3329 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00003330 //
John McCall0d1da222010-01-12 00:44:57 +00003331 // C++0x [over.best.ics]p10:
3332 // For the purpose of ranking implicit conversion sequences as
3333 // described in 13.3.3.2, the ambiguous conversion sequence is
3334 // treated as a user-defined sequence that is indistinguishable
3335 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00003336 if (ICS1.getKindRank() < ICS2.getKindRank())
3337 return ImplicitConversionSequence::Better;
David Blaikie8a40f702012-01-17 06:56:22 +00003338 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor5ab11652010-04-17 22:01:05 +00003339 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003340
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00003341 // The following checks require both conversion sequences to be of
3342 // the same kind.
3343 if (ICS1.getKind() != ICS2.getKind())
3344 return ImplicitConversionSequence::Indistinguishable;
3345
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003346 ImplicitConversionSequence::CompareKind Result =
3347 ImplicitConversionSequence::Indistinguishable;
3348
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003349 // Two implicit conversion sequences of the same form are
3350 // indistinguishable conversion sequences unless one of the
3351 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00003352 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003353 Result = CompareStandardConversionSequences(S,
3354 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00003355 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003356 // User-defined conversion sequence U1 is a better conversion
3357 // sequence than another user-defined conversion sequence U2 if
3358 // they contain the same user-defined conversion function or
3359 // constructor and if the second standard conversion sequence of
3360 // U1 is better than the second standard conversion sequence of
3361 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00003362 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003363 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003364 Result = CompareStandardConversionSequences(S,
3365 ICS1.UserDefined.After,
3366 ICS2.UserDefined.After);
Douglas Gregor2837aa22012-02-22 17:32:19 +00003367 else
3368 Result = compareConversionFunctions(S,
3369 ICS1.UserDefined.ConversionFunction,
3370 ICS2.UserDefined.ConversionFunction);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003371 }
3372
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003373 // List-initialization sequence L1 is a better conversion sequence than
3374 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3375 // for some X and L2 does not.
3376 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smitha93f1022013-09-06 22:30:28 +00003377 !ICS1.isBad()) {
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00003378 if (ICS1.isStdInitializerListElement() &&
3379 !ICS2.isStdInitializerListElement())
3380 return ImplicitConversionSequence::Better;
3381 if (!ICS1.isStdInitializerListElement() &&
3382 ICS2.isStdInitializerListElement())
3383 return ImplicitConversionSequence::Worse;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003384 }
3385
3386 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003387}
3388
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003389static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3390 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3391 Qualifiers Quals;
3392 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003393 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003396 return Context.hasSameUnqualifiedType(T1, T2);
3397}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003399// Per 13.3.3.2p3, compare the given standard conversion sequences to
3400// determine if one is a proper subset of the other.
3401static ImplicitConversionSequence::CompareKind
3402compareStandardConversionSubsets(ASTContext &Context,
3403 const StandardConversionSequence& SCS1,
3404 const StandardConversionSequence& SCS2) {
3405 ImplicitConversionSequence::CompareKind Result
3406 = ImplicitConversionSequence::Indistinguishable;
3407
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003408 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00003409 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00003410 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3411 return ImplicitConversionSequence::Better;
3412 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3413 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003414
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003415 if (SCS1.Second != SCS2.Second) {
3416 if (SCS1.Second == ICK_Identity)
3417 Result = ImplicitConversionSequence::Better;
3418 else if (SCS2.Second == ICK_Identity)
3419 Result = ImplicitConversionSequence::Worse;
3420 else
3421 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00003422 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003423 return ImplicitConversionSequence::Indistinguishable;
3424
3425 if (SCS1.Third == SCS2.Third) {
3426 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3427 : ImplicitConversionSequence::Indistinguishable;
3428 }
3429
3430 if (SCS1.Third == ICK_Identity)
3431 return Result == ImplicitConversionSequence::Worse
3432 ? ImplicitConversionSequence::Indistinguishable
3433 : ImplicitConversionSequence::Better;
3434
3435 if (SCS2.Third == ICK_Identity)
3436 return Result == ImplicitConversionSequence::Better
3437 ? ImplicitConversionSequence::Indistinguishable
3438 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003439
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003440 return ImplicitConversionSequence::Indistinguishable;
3441}
3442
Douglas Gregore696ebb2011-01-26 14:52:12 +00003443/// \brief Determine whether one of the given reference bindings is better
3444/// than the other based on what kind of bindings they are.
3445static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3446 const StandardConversionSequence &SCS2) {
3447 // C++0x [over.ics.rank]p3b4:
3448 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3449 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003450 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00003451 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003452 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00003453 // reference*.
3454 //
3455 // FIXME: Rvalue references. We're going rogue with the above edits,
3456 // because the semantics in the current C++0x working paper (N3225 at the
3457 // time of this writing) break the standard definition of std::forward
3458 // and std::reference_wrapper when dealing with references to functions.
3459 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00003460 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3461 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3462 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463
Douglas Gregore696ebb2011-01-26 14:52:12 +00003464 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3465 SCS2.IsLvalueReference) ||
3466 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3467 !SCS2.IsLvalueReference);
3468}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003469
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003470/// CompareStandardConversionSequences - Compare two standard
3471/// conversion sequences to determine whether one is better than the
3472/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00003473static ImplicitConversionSequence::CompareKind
3474CompareStandardConversionSequences(Sema &S,
3475 const StandardConversionSequence& SCS1,
3476 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003477{
3478 // Standard conversion sequence S1 is a better conversion sequence
3479 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3480
3481 // -- S1 is a proper subsequence of S2 (comparing the conversion
3482 // sequences in the canonical form defined by 13.3.3.1.1,
3483 // excluding any Lvalue Transformation; the identity conversion
3484 // sequence is considered to be a subsequence of any
3485 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003486 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00003487 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003488 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003489
3490 // -- the rank of S1 is better than the rank of S2 (by the rules
3491 // defined below), or, if not that,
3492 ImplicitConversionRank Rank1 = SCS1.getRank();
3493 ImplicitConversionRank Rank2 = SCS2.getRank();
3494 if (Rank1 < Rank2)
3495 return ImplicitConversionSequence::Better;
3496 else if (Rank2 < Rank1)
3497 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003498
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003499 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3500 // are indistinguishable unless one of the following rules
3501 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00003502
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003503 // A conversion that is not a conversion of a pointer, or
3504 // pointer to member, to bool is better than another conversion
3505 // that is such a conversion.
3506 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3507 return SCS2.isPointerConversionToBool()
3508 ? ImplicitConversionSequence::Better
3509 : ImplicitConversionSequence::Worse;
3510
Douglas Gregor5c407d92008-10-23 00:40:37 +00003511 // C++ [over.ics.rank]p4b2:
3512 //
3513 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003514 // conversion of B* to A* is better than conversion of B* to
3515 // void*, and conversion of A* to void* is better than conversion
3516 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00003517 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003518 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00003519 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00003520 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003521 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3522 // Exactly one of the conversion sequences is a conversion to
3523 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003524 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3525 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003526 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3527 // Neither conversion sequence converts to a void pointer; compare
3528 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003529 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00003530 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003531 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003532 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3533 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003534 // Both conversion sequences are conversions to void
3535 // pointers. Compare the source types to determine if there's an
3536 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00003537 QualType FromType1 = SCS1.getFromType();
3538 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003539
3540 // Adjust the types we're converting from via the array-to-pointer
3541 // conversion, if we need to.
3542 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003543 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003544 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003545 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003546
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003547 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3548 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003549
John McCall5c32be02010-08-24 20:38:10 +00003550 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003551 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003552 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003553 return ImplicitConversionSequence::Worse;
3554
3555 // Objective-C++: If one interface is more specific than the
3556 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003557 const ObjCObjectPointerType* FromObjCPtr1
3558 = FromType1->getAs<ObjCObjectPointerType>();
3559 const ObjCObjectPointerType* FromObjCPtr2
3560 = FromType2->getAs<ObjCObjectPointerType>();
3561 if (FromObjCPtr1 && FromObjCPtr2) {
3562 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3563 FromObjCPtr2);
3564 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3565 FromObjCPtr1);
3566 if (AssignLeft != AssignRight) {
3567 return AssignLeft? ImplicitConversionSequence::Better
3568 : ImplicitConversionSequence::Worse;
3569 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003570 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003571 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003572
3573 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3574 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003575 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003576 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003577 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003578
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003579 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003580 // Check for a better reference binding based on the kind of bindings.
3581 if (isBetterReferenceBindingKind(SCS1, SCS2))
3582 return ImplicitConversionSequence::Better;
3583 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3584 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003585
Sebastian Redlb28b4072009-03-22 23:49:27 +00003586 // C++ [over.ics.rank]p3b4:
3587 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3588 // which the references refer are the same type except for
3589 // top-level cv-qualifiers, and the type to which the reference
3590 // initialized by S2 refers is more cv-qualified than the type
3591 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003592 QualType T1 = SCS1.getToType(2);
3593 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003594 T1 = S.Context.getCanonicalType(T1);
3595 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003596 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003597 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3598 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003599 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003600 // Objective-C++ ARC: If the references refer to objects with different
3601 // lifetimes, prefer bindings that don't change lifetime.
3602 if (SCS1.ObjCLifetimeConversionBinding !=
3603 SCS2.ObjCLifetimeConversionBinding) {
3604 return SCS1.ObjCLifetimeConversionBinding
3605 ? ImplicitConversionSequence::Worse
3606 : ImplicitConversionSequence::Better;
3607 }
3608
Chandler Carruth8e543b32010-12-12 08:17:55 +00003609 // If the type is an array type, promote the element qualifiers to the
3610 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003611 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003612 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003613 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003614 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003615 if (T2.isMoreQualifiedThan(T1))
3616 return ImplicitConversionSequence::Better;
3617 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003618 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003619 }
3620 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003621
Francois Pichet08d2fa02011-09-18 21:37:37 +00003622 // In Microsoft mode, prefer an integral conversion to a
3623 // floating-to-integral conversion if the integral conversion
3624 // is between types of the same size.
3625 // For example:
3626 // void f(float);
3627 // void f(int);
3628 // int main {
3629 // long a;
3630 // f(a);
3631 // }
3632 // Here, MSVC will call f(int) instead of generating a compile error
3633 // as clang will do in standard mode.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003634 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet08d2fa02011-09-18 21:37:37 +00003635 SCS1.Second == ICK_Integral_Conversion &&
3636 SCS2.Second == ICK_Floating_Integral &&
3637 S.Context.getTypeSize(SCS1.getFromType()) ==
3638 S.Context.getTypeSize(SCS1.getToType(2)))
3639 return ImplicitConversionSequence::Better;
3640
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003641 return ImplicitConversionSequence::Indistinguishable;
3642}
3643
3644/// CompareQualificationConversions - Compares two standard conversion
3645/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003646/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3647ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003648CompareQualificationConversions(Sema &S,
3649 const StandardConversionSequence& SCS1,
3650 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003651 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003652 // -- S1 and S2 differ only in their qualification conversion and
3653 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3654 // cv-qualification signature of type T1 is a proper subset of
3655 // the cv-qualification signature of type T2, and S1 is not the
3656 // deprecated string literal array-to-pointer conversion (4.2).
3657 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3658 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3659 return ImplicitConversionSequence::Indistinguishable;
3660
3661 // FIXME: the example in the standard doesn't use a qualification
3662 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003663 QualType T1 = SCS1.getToType(2);
3664 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003665 T1 = S.Context.getCanonicalType(T1);
3666 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003667 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003668 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3669 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003670
3671 // If the types are the same, we won't learn anything by unwrapped
3672 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003673 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003674 return ImplicitConversionSequence::Indistinguishable;
3675
Chandler Carruth607f38e2009-12-29 07:16:59 +00003676 // If the type is an array type, promote the element qualifiers to the type
3677 // for comparison.
3678 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003679 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003680 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003681 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003682
Mike Stump11289f42009-09-09 15:08:12 +00003683 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003684 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003685
3686 // Objective-C++ ARC:
3687 // Prefer qualification conversions not involving a change in lifetime
3688 // to qualification conversions that do not change lifetime.
3689 if (SCS1.QualificationIncludesObjCLifetime !=
3690 SCS2.QualificationIncludesObjCLifetime) {
3691 Result = SCS1.QualificationIncludesObjCLifetime
3692 ? ImplicitConversionSequence::Worse
3693 : ImplicitConversionSequence::Better;
3694 }
3695
John McCall5c32be02010-08-24 20:38:10 +00003696 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003697 // Within each iteration of the loop, we check the qualifiers to
3698 // determine if this still looks like a qualification
3699 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003700 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003701 // until there are no more pointers or pointers-to-members left
3702 // to unwrap. This essentially mimics what
3703 // IsQualificationConversion does, but here we're checking for a
3704 // strict subset of qualifiers.
3705 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3706 // The qualifiers are the same, so this doesn't tell us anything
3707 // about how the sequences rank.
3708 ;
3709 else if (T2.isMoreQualifiedThan(T1)) {
3710 // T1 has fewer qualifiers, so it could be the better sequence.
3711 if (Result == ImplicitConversionSequence::Worse)
3712 // Neither has qualifiers that are a subset of the other's
3713 // qualifiers.
3714 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003715
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003716 Result = ImplicitConversionSequence::Better;
3717 } else if (T1.isMoreQualifiedThan(T2)) {
3718 // T2 has fewer qualifiers, so it could be the better sequence.
3719 if (Result == ImplicitConversionSequence::Better)
3720 // Neither has qualifiers that are a subset of the other's
3721 // qualifiers.
3722 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003723
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003724 Result = ImplicitConversionSequence::Worse;
3725 } else {
3726 // Qualifiers are disjoint.
3727 return ImplicitConversionSequence::Indistinguishable;
3728 }
3729
3730 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003731 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003732 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003733 }
3734
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003735 // Check that the winning standard conversion sequence isn't using
3736 // the deprecated string literal array to pointer conversion.
3737 switch (Result) {
3738 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003739 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003740 Result = ImplicitConversionSequence::Indistinguishable;
3741 break;
3742
3743 case ImplicitConversionSequence::Indistinguishable:
3744 break;
3745
3746 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003747 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003748 Result = ImplicitConversionSequence::Indistinguishable;
3749 break;
3750 }
3751
3752 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003753}
3754
Douglas Gregor5c407d92008-10-23 00:40:37 +00003755/// CompareDerivedToBaseConversions - Compares two standard conversion
3756/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003757/// various kinds of derived-to-base conversions (C++
3758/// [over.ics.rank]p4b3). As part of these checks, we also look at
3759/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003760ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003761CompareDerivedToBaseConversions(Sema &S,
3762 const StandardConversionSequence& SCS1,
3763 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003764 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003765 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003766 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003767 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003768
3769 // Adjust the types we're converting from via the array-to-pointer
3770 // conversion, if we need to.
3771 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003772 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003773 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003774 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003775
3776 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003777 FromType1 = S.Context.getCanonicalType(FromType1);
3778 ToType1 = S.Context.getCanonicalType(ToType1);
3779 FromType2 = S.Context.getCanonicalType(FromType2);
3780 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003781
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003782 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003783 //
3784 // If class B is derived directly or indirectly from class A and
3785 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003786 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003787 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003788 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003789 SCS2.Second == ICK_Pointer_Conversion &&
3790 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3791 FromType1->isPointerType() && FromType2->isPointerType() &&
3792 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003793 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003794 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003795 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003796 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003797 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003798 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003799 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003800 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003801
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003802 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003803 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003804 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003805 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003806 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003807 return ImplicitConversionSequence::Worse;
3808 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003809
3810 // -- conversion of B* to A* is better than conversion of C* to A*,
3811 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003812 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003813 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003814 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003815 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003816 }
3817 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3818 SCS2.Second == ICK_Pointer_Conversion) {
3819 const ObjCObjectPointerType *FromPtr1
3820 = FromType1->getAs<ObjCObjectPointerType>();
3821 const ObjCObjectPointerType *FromPtr2
3822 = FromType2->getAs<ObjCObjectPointerType>();
3823 const ObjCObjectPointerType *ToPtr1
3824 = ToType1->getAs<ObjCObjectPointerType>();
3825 const ObjCObjectPointerType *ToPtr2
3826 = ToType2->getAs<ObjCObjectPointerType>();
3827
3828 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3829 // Apply the same conversion ranking rules for Objective-C pointer types
3830 // that we do for C++ pointers to class types. However, we employ the
3831 // Objective-C pseudo-subtyping relationship used for assignment of
3832 // Objective-C pointer types.
3833 bool FromAssignLeft
3834 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3835 bool FromAssignRight
3836 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3837 bool ToAssignLeft
3838 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3839 bool ToAssignRight
3840 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3841
3842 // A conversion to an a non-id object pointer type or qualified 'id'
3843 // type is better than a conversion to 'id'.
3844 if (ToPtr1->isObjCIdType() &&
3845 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3846 return ImplicitConversionSequence::Worse;
3847 if (ToPtr2->isObjCIdType() &&
3848 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3849 return ImplicitConversionSequence::Better;
3850
3851 // A conversion to a non-id object pointer type is better than a
3852 // conversion to a qualified 'id' type
3853 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3854 return ImplicitConversionSequence::Worse;
3855 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3856 return ImplicitConversionSequence::Better;
3857
3858 // A conversion to an a non-Class object pointer type or qualified 'Class'
3859 // type is better than a conversion to 'Class'.
3860 if (ToPtr1->isObjCClassType() &&
3861 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3862 return ImplicitConversionSequence::Worse;
3863 if (ToPtr2->isObjCClassType() &&
3864 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3865 return ImplicitConversionSequence::Better;
3866
3867 // A conversion to a non-Class object pointer type is better than a
3868 // conversion to a qualified 'Class' type.
3869 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3870 return ImplicitConversionSequence::Worse;
3871 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3872 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003873
Douglas Gregor058d3de2011-01-31 18:51:41 +00003874 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3875 if (S.Context.hasSameType(FromType1, FromType2) &&
3876 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3877 (ToAssignLeft != ToAssignRight))
3878 return ToAssignLeft? ImplicitConversionSequence::Worse
3879 : ImplicitConversionSequence::Better;
3880
3881 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3882 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3883 (FromAssignLeft != FromAssignRight))
3884 return FromAssignLeft? ImplicitConversionSequence::Better
3885 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003886 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003887 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003888
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003889 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003890 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3891 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3892 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003894 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003896 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003898 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003899 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003900 ToType2->getAs<MemberPointerType>();
3901 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3902 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3903 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3904 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3905 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3906 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3907 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3908 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003909 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003910 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003911 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003912 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003913 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003914 return ImplicitConversionSequence::Better;
3915 }
3916 // conversion of B::* to C::* is better than conversion of A::* to C::*
3917 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003918 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003919 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003920 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003921 return ImplicitConversionSequence::Worse;
3922 }
3923 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003924
Douglas Gregor5ab11652010-04-17 22:01:05 +00003925 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003926 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003927 // -- binding of an expression of type C to a reference of type
3928 // B& is better than binding an expression of type C to a
3929 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003930 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3931 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3932 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003933 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003934 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003935 return ImplicitConversionSequence::Worse;
3936 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003937
Douglas Gregor2fe98832008-11-03 19:09:14 +00003938 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003939 // -- binding of an expression of type B to a reference of type
3940 // A& is better than binding an expression of type C to a
3941 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003942 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3943 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3944 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003945 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003946 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003947 return ImplicitConversionSequence::Worse;
3948 }
3949 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003950
Douglas Gregor5c407d92008-10-23 00:40:37 +00003951 return ImplicitConversionSequence::Indistinguishable;
3952}
3953
Douglas Gregor45bb4832013-03-26 23:36:30 +00003954/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3955/// C++ class.
3956static bool isTypeValid(QualType T) {
3957 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3958 return !Record->isInvalidDecl();
3959
3960 return true;
3961}
3962
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003963/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3964/// determine whether they are reference-related,
3965/// reference-compatible, reference-compatible with added
3966/// qualification, or incompatible, for use in C++ initialization by
3967/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3968/// type, and the first type (T1) is the pointee type of the reference
3969/// type being initialized.
3970Sema::ReferenceCompareResult
3971Sema::CompareReferenceRelationship(SourceLocation Loc,
3972 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003973 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003974 bool &ObjCConversion,
3975 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003976 assert(!OrigT1->isReferenceType() &&
3977 "T1 must be the pointee type of the reference type");
3978 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3979
3980 QualType T1 = Context.getCanonicalType(OrigT1);
3981 QualType T2 = Context.getCanonicalType(OrigT2);
3982 Qualifiers T1Quals, T2Quals;
3983 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3984 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3985
3986 // C++ [dcl.init.ref]p4:
3987 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3988 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3989 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003990 DerivedToBase = false;
3991 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003992 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003993 if (UnqualT1 == UnqualT2) {
3994 // Nothing to do.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00003995 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor45bb4832013-03-26 23:36:30 +00003996 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3997 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003998 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003999 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
4000 UnqualT2->isObjCObjectOrInterfaceType() &&
4001 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
4002 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004003 else
4004 return Ref_Incompatible;
4005
4006 // At this point, we know that T1 and T2 are reference-related (at
4007 // least).
4008
4009 // If the type is an array type, promote the element qualifiers to the type
4010 // for comparison.
4011 if (isa<ArrayType>(T1) && T1Quals)
4012 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
4013 if (isa<ArrayType>(T2) && T2Quals)
4014 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
4015
4016 // C++ [dcl.init.ref]p4:
4017 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
4018 // reference-related to T2 and cv1 is the same cv-qualification
4019 // as, or greater cv-qualification than, cv2. For purposes of
4020 // overload resolution, cases for which cv1 is greater
4021 // cv-qualification than cv2 are identified as
4022 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00004023 //
4024 // Note that we also require equivalence of Objective-C GC and address-space
4025 // qualifiers when performing these computations, so that e.g., an int in
4026 // address space 1 is not reference-compatible with an int in address
4027 // space 2.
John McCall31168b02011-06-15 23:02:42 +00004028 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
4029 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
Douglas Gregorc9f019a2013-11-08 02:04:24 +00004030 if (isNonTrivialObjCLifetimeConversion(T2Quals, T1Quals))
4031 ObjCLifetimeConversion = true;
4032
John McCall31168b02011-06-15 23:02:42 +00004033 T1Quals.removeObjCLifetime();
4034 T2Quals.removeObjCLifetime();
John McCall31168b02011-06-15 23:02:42 +00004035 }
4036
Douglas Gregord517d552011-04-28 17:56:11 +00004037 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004038 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00004039 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004040 return Ref_Compatible_With_Added_Qualification;
4041 else
4042 return Ref_Related;
4043}
4044
Douglas Gregor836a7e82010-08-11 02:15:33 +00004045/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00004046/// with DeclType. Return true if something definite is found.
4047static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00004048FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4049 QualType DeclType, SourceLocation DeclLoc,
4050 Expr *Init, QualType T2, bool AllowRvalues,
4051 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004052 assert(T2->isRecordType() && "Can only find conversions of record types.");
4053 CXXRecordDecl *T2RecordDecl
4054 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4055
4056 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00004057 std::pair<CXXRecordDecl::conversion_iterator,
4058 CXXRecordDecl::conversion_iterator>
4059 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4060 for (CXXRecordDecl::conversion_iterator
4061 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004062 NamedDecl *D = *I;
4063 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4064 if (isa<UsingShadowDecl>(D))
4065 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4066
4067 FunctionTemplateDecl *ConvTemplate
4068 = dyn_cast<FunctionTemplateDecl>(D);
4069 CXXConversionDecl *Conv;
4070 if (ConvTemplate)
4071 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4072 else
4073 Conv = cast<CXXConversionDecl>(D);
4074
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00004076 // explicit conversions, skip it.
4077 if (!AllowExplicit && Conv->isExplicit())
4078 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079
Douglas Gregor836a7e82010-08-11 02:15:33 +00004080 if (AllowRvalues) {
4081 bool DerivedToBase = false;
4082 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004083 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004084
4085 // If we are initializing an rvalue reference, don't permit conversion
4086 // functions that return lvalues.
4087 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4088 const ReferenceType *RefType
4089 = Conv->getConversionType()->getAs<LValueReferenceType>();
4090 if (RefType && !RefType->getPointeeType()->isFunctionType())
4091 continue;
4092 }
4093
Douglas Gregor836a7e82010-08-11 02:15:33 +00004094 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00004095 S.CompareReferenceRelationship(
4096 DeclLoc,
4097 Conv->getConversionType().getNonReferenceType()
4098 .getUnqualifiedType(),
4099 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00004100 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00004101 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00004102 continue;
4103 } else {
4104 // If the conversion function doesn't return a reference type,
4105 // it can't be considered for this conversion. An rvalue reference
4106 // is only acceptable if its referencee is a function type.
4107
4108 const ReferenceType *RefType =
4109 Conv->getConversionType()->getAs<ReferenceType>();
4110 if (!RefType ||
4111 (!RefType->isLValueReferenceType() &&
4112 !RefType->getPointeeType()->isFunctionType()))
4113 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00004114 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115
Douglas Gregor836a7e82010-08-11 02:15:33 +00004116 if (ConvTemplate)
4117 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004118 Init, DeclType, CandidateSet,
4119 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor836a7e82010-08-11 02:15:33 +00004120 else
4121 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004122 DeclType, CandidateSet,
4123 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redld92badf2010-06-30 18:13:39 +00004124 }
4125
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004126 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4127
Sebastian Redld92badf2010-06-30 18:13:39 +00004128 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00004129 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004130 case OR_Success:
4131 // C++ [over.ics.ref]p1:
4132 //
4133 // [...] If the parameter binds directly to the result of
4134 // applying a conversion function to the argument
4135 // expression, the implicit conversion sequence is a
4136 // user-defined conversion sequence (13.3.3.1.2), with the
4137 // second standard conversion sequence either an identity
4138 // conversion or, if the conversion function returns an
4139 // entity of a type that is a derived class of the parameter
4140 // type, a derived-to-base Conversion.
4141 if (!Best->FinalConversion.DirectBinding)
4142 return false;
4143
4144 ICS.setUserDefined();
4145 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4146 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004147 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00004148 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00004149 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00004150 ICS.UserDefined.EllipsisConversion = false;
4151 assert(ICS.UserDefined.After.ReferenceBinding &&
4152 ICS.UserDefined.After.DirectBinding &&
4153 "Expected a direct reference binding!");
4154 return true;
4155
4156 case OR_Ambiguous:
4157 ICS.setAmbiguous();
4158 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4159 Cand != CandidateSet.end(); ++Cand)
4160 if (Cand->Viable)
4161 ICS.Ambiguous.addConversion(Cand->Function);
4162 return true;
4163
4164 case OR_No_Viable_Function:
4165 case OR_Deleted:
4166 // There was no suitable conversion, or we found a deleted
4167 // conversion; continue with other checks.
4168 return false;
4169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
David Blaikie8a40f702012-01-17 06:56:22 +00004171 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redld92badf2010-06-30 18:13:39 +00004172}
4173
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004174/// \brief Compute an implicit conversion sequence for reference
4175/// initialization.
4176static ImplicitConversionSequence
Sebastian Redldf888642011-12-03 14:54:30 +00004177TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004178 SourceLocation DeclLoc,
4179 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004180 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004181 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4182
4183 // Most paths end in a failed conversion.
4184 ImplicitConversionSequence ICS;
4185 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4186
4187 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4188 QualType T2 = Init->getType();
4189
4190 // If the initializer is the address of an overloaded function, try
4191 // to resolve the overloaded function. If all goes well, T2 is the
4192 // type of the resulting function.
4193 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4194 DeclAccessPair Found;
4195 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4196 false, Found))
4197 T2 = Fn->getType();
4198 }
4199
4200 // Compute some basic properties of the types and the initializer.
4201 bool isRValRef = DeclType->isRValueReferenceType();
4202 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004203 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00004204 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00004205 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004206 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004207 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00004208 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004209
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004210
Sebastian Redld92badf2010-06-30 18:13:39 +00004211 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00004212 // A reference to type "cv1 T1" is initialized by an expression
4213 // of type "cv2 T2" as follows:
4214
Sebastian Redld92badf2010-06-30 18:13:39 +00004215 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00004216 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00004217 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4218 // reference-compatible with "cv2 T2," or
4219 //
4220 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4221 if (InitCategory.isLValue() &&
4222 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004223 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00004224 // When a parameter of reference type binds directly (8.5.3)
4225 // to an argument expression, the implicit conversion sequence
4226 // is the identity conversion, unless the argument expression
4227 // has a type that is a derived class of the parameter type,
4228 // in which case the implicit conversion sequence is a
4229 // derived-to-base Conversion (13.3.3.1).
4230 ICS.setStandard();
4231 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00004232 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4233 : ObjCConversion? ICK_Compatible_Conversion
4234 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00004235 ICS.Standard.Third = ICK_Identity;
4236 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4237 ICS.Standard.setToType(0, T2);
4238 ICS.Standard.setToType(1, T1);
4239 ICS.Standard.setToType(2, T1);
4240 ICS.Standard.ReferenceBinding = true;
4241 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004242 ICS.Standard.IsLvalueReference = !isRValRef;
4243 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4244 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004245 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004246 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00004247 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004248
Sebastian Redld92badf2010-06-30 18:13:39 +00004249 // Nothing more to do: the inaccessibility/ambiguity check for
4250 // derived-to-base conversions is suppressed when we're
4251 // computing the implicit conversion sequence (C++
4252 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004253 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00004254 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004255
Sebastian Redld92badf2010-06-30 18:13:39 +00004256 // -- has a class type (i.e., T2 is a class type), where T1 is
4257 // not reference-related to T2, and can be implicitly
4258 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4259 // is reference-compatible with "cv3 T3" 92) (this
4260 // conversion is selected by enumerating the applicable
4261 // conversion functions (13.3.1.6) and choosing the best
4262 // one through overload resolution (13.3)),
4263 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004264 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00004265 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00004266 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4267 Init, T2, /*AllowRvalues=*/false,
4268 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00004269 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004270 }
4271 }
4272
Sebastian Redld92badf2010-06-30 18:13:39 +00004273 // -- Otherwise, the reference shall be an lvalue reference to a
4274 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00004275 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004276 //
Douglas Gregor870f3742010-04-18 09:22:00 +00004277 // We actually handle one oddity of C++ [over.ics.ref] at this
4278 // point, which is that, due to p2 (which short-circuits reference
4279 // binding by only attempting a simple conversion for non-direct
4280 // bindings) and p3's strange wording, we allow a const volatile
4281 // reference to bind to an rvalue. Hence the check for the presence
4282 // of "const" rather than checking for "const" being the only
4283 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00004284 // This is also the point where rvalue references and lvalue inits no longer
4285 // go together.
Richard Smithce4f6082012-05-24 04:29:20 +00004286 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004287 return ICS;
4288
Douglas Gregorf143cd52011-01-24 16:14:37 +00004289 // -- If the initializer expression
4290 //
4291 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00004292 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00004293 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4294 (InitCategory.isXValue() ||
4295 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4296 (InitCategory.isLValue() && T2->isFunctionType()))) {
4297 ICS.setStandard();
4298 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004299 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004300 : ObjCConversion? ICK_Compatible_Conversion
4301 : ICK_Identity;
4302 ICS.Standard.Third = ICK_Identity;
4303 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4304 ICS.Standard.setToType(0, T2);
4305 ICS.Standard.setToType(1, T1);
4306 ICS.Standard.setToType(2, T1);
4307 ICS.Standard.ReferenceBinding = true;
4308 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4309 // binding unless we're binding to a class prvalue.
4310 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4311 // allow the use of rvalue references in C++98/03 for the benefit of
4312 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313 ICS.Standard.DirectBinding =
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004314 S.getLangOpts().CPlusPlus11 ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00004315 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00004316 ICS.Standard.IsLvalueReference = !isRValRef;
4317 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00004319 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004320 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004321 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004322 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00004323 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004324
Douglas Gregorf143cd52011-01-24 16:14:37 +00004325 // -- has a class type (i.e., T2 is a class type), where T1 is not
4326 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 // an xvalue, class prvalue, or function lvalue of type
4328 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00004329 // "cv3 T3",
4330 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004331 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00004332 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00004334 // class subobject).
4335 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004336 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004337 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4338 Init, T2, /*AllowRvalues=*/true,
4339 AllowExplicit)) {
4340 // In the second case, if the reference is an rvalue reference
4341 // and the second standard conversion sequence of the
4342 // user-defined conversion sequence includes an lvalue-to-rvalue
4343 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004344 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00004345 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4346 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4347
Douglas Gregor95273c32011-01-21 16:36:05 +00004348 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00004349 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004351 // -- Otherwise, a temporary of type "cv1 T1" is created and
4352 // initialized from the initializer expression using the
4353 // rules for a non-reference copy initialization (8.5). The
4354 // reference is then bound to the temporary. If T1 is
4355 // reference-related to T2, cv1 must be the same
4356 // cv-qualification as, or greater cv-qualification than,
4357 // cv2; otherwise, the program is ill-formed.
4358 if (RefRelationship == Sema::Ref_Related) {
4359 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4360 // we would be reference-compatible or reference-compatible with
4361 // added qualification. But that wasn't the case, so the reference
4362 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00004363 //
4364 // Note that we only want to check address spaces and cvr-qualifiers here.
4365 // ObjC GC and lifetime qualifiers aren't important.
4366 Qualifiers T1Quals = T1.getQualifiers();
4367 Qualifiers T2Quals = T2.getQualifiers();
4368 T1Quals.removeObjCGCAttr();
4369 T1Quals.removeObjCLifetime();
4370 T2Quals.removeObjCGCAttr();
4371 T2Quals.removeObjCLifetime();
4372 if (!T1Quals.compatiblyIncludes(T2Quals))
4373 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004374 }
4375
4376 // If at least one of the types is a class type, the types are not
4377 // related, and we aren't allowed any user conversions, the
4378 // reference binding fails. This case is important for breaking
4379 // recursion, since TryImplicitConversion below will attempt to
4380 // create a temporary through the use of a copy constructor.
4381 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4382 (T1->isRecordType() || T2->isRecordType()))
4383 return ICS;
4384
Douglas Gregorcba72b12011-01-21 05:18:22 +00004385 // If T1 is reference-related to T2 and the reference is an rvalue
4386 // reference, the initializer expression shall not be an lvalue.
4387 if (RefRelationship >= Sema::Ref_Related &&
4388 isRValRef && Init->Classify(S.Context).isLValue())
4389 return ICS;
4390
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004391 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004392 // When a parameter of reference type is not bound directly to
4393 // an argument expression, the conversion sequence is the one
4394 // required to convert the argument expression to the
4395 // underlying type of the reference according to
4396 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4397 // to copy-initializing a temporary of the underlying type with
4398 // the argument expression. Any difference in top-level
4399 // cv-qualification is subsumed by the initialization itself
4400 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00004401 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4402 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004403 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004404 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004405 /*AllowObjCWritebackConversion=*/false,
4406 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004407
4408 // Of course, that's still a reference binding.
4409 if (ICS.isStandard()) {
4410 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004411 ICS.Standard.IsLvalueReference = !isRValRef;
4412 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4413 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004414 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00004415 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004416 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00004417 // Don't allow rvalue references to bind to lvalues.
4418 if (DeclType->isRValueReferenceType()) {
4419 if (const ReferenceType *RefType
4420 = ICS.UserDefined.ConversionFunction->getResultType()
4421 ->getAs<LValueReferenceType>()) {
4422 if (!RefType->getPointeeType()->isFunctionType()) {
4423 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4424 DeclType);
4425 return ICS;
4426 }
4427 }
4428 }
4429
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004430 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00004431 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4432 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4433 ICS.UserDefined.After.BindsToRvalue = true;
4434 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4435 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004436 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00004437
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004438 return ICS;
4439}
4440
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004441static ImplicitConversionSequence
4442TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4443 bool SuppressUserConversions,
4444 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004445 bool AllowObjCWritebackConversion,
4446 bool AllowExplicit = false);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004447
4448/// TryListConversion - Try to copy-initialize a value of type ToType from the
4449/// initializer list From.
4450static ImplicitConversionSequence
4451TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4452 bool SuppressUserConversions,
4453 bool InOverloadResolution,
4454 bool AllowObjCWritebackConversion) {
4455 // C++11 [over.ics.list]p1:
4456 // When an argument is an initializer list, it is not an expression and
4457 // special rules apply for converting it to a parameter type.
4458
4459 ImplicitConversionSequence Result;
4460 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4461
Sebastian Redl09edce02012-01-23 22:09:39 +00004462 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004463 // initialized from init lists.
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00004464 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004465 return Result;
4466
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004467 // C++11 [over.ics.list]p2:
4468 // If the parameter type is std::initializer_list<X> or "array of X" and
4469 // all the elements can be implicitly converted to X, the implicit
4470 // conversion sequence is the worst conversion necessary to convert an
4471 // element of the list to X.
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004472 bool toStdInitializerList = false;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004473 QualType X;
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004474 if (ToType->isArrayType())
Richard Smith0db1ea52012-12-09 06:48:56 +00004475 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004476 else
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004477 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004478 if (!X.isNull()) {
4479 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4480 Expr *Init = From->getInit(i);
4481 ImplicitConversionSequence ICS =
4482 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4483 InOverloadResolution,
4484 AllowObjCWritebackConversion);
4485 // If a single element isn't convertible, fail.
4486 if (ICS.isBad()) {
4487 Result = ICS;
4488 break;
4489 }
4490 // Otherwise, look for the worst conversion.
4491 if (Result.isBad() ||
4492 CompareImplicitConversionSequences(S, ICS, Result) ==
4493 ImplicitConversionSequence::Worse)
4494 Result = ICS;
4495 }
Douglas Gregor0f5c1c02012-04-04 23:09:20 +00004496
4497 // For an empty list, we won't have computed any conversion sequence.
4498 // Introduce the identity conversion sequence.
4499 if (From->getNumInits() == 0) {
4500 Result.setStandard();
4501 Result.Standard.setAsIdentityConversion();
4502 Result.Standard.setFromType(ToType);
4503 Result.Standard.setAllToTypes(ToType);
4504 }
4505
Sebastian Redlaa6feaa2012-02-27 22:38:26 +00004506 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004507 return Result;
Sebastian Redl10f0fc02012-01-17 22:49:48 +00004508 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004509
4510 // C++11 [over.ics.list]p3:
4511 // Otherwise, if the parameter is a non-aggregate class X and overload
4512 // resolution chooses a single best constructor [...] the implicit
4513 // conversion sequence is a user-defined conversion sequence. If multiple
4514 // constructors are viable but none is better than the others, the
4515 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004516 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4517 // This function can deal with initializer lists.
Richard Smitha93f1022013-09-06 22:30:28 +00004518 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4519 /*AllowExplicit=*/false,
4520 InOverloadResolution, /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004521 AllowObjCWritebackConversion,
4522 /*AllowObjCConversionOnExplicit=*/false);
Sebastian Redl6901c0d2011-12-22 18:58:38 +00004523 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004524
4525 // C++11 [over.ics.list]p4:
4526 // Otherwise, if the parameter has an aggregate type which can be
4527 // initialized from the initializer list [...] the implicit conversion
4528 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004529 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004530 // Type is an aggregate, argument is an init list. At this point it comes
4531 // down to checking whether the initialization works.
4532 // FIXME: Find out whether this parameter is consumed or not.
4533 InitializedEntity Entity =
4534 InitializedEntity::InitializeParameter(S.Context, ToType,
4535 /*Consumed=*/false);
4536 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4537 Result.setUserDefined();
4538 Result.UserDefined.Before.setAsIdentityConversion();
4539 // Initializer lists don't have a type.
4540 Result.UserDefined.Before.setFromType(QualType());
4541 Result.UserDefined.Before.setAllToTypes(QualType());
4542
4543 Result.UserDefined.After.setAsIdentityConversion();
4544 Result.UserDefined.After.setFromType(ToType);
4545 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramerb6d65082012-02-02 19:35:29 +00004546 Result.UserDefined.ConversionFunction = 0;
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00004547 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004548 return Result;
4549 }
4550
4551 // C++11 [over.ics.list]p5:
4552 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redldf888642011-12-03 14:54:30 +00004553 if (ToType->isReferenceType()) {
4554 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4555 // mention initializer lists in any way. So we go by what list-
4556 // initialization would do and try to extrapolate from that.
4557
4558 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4559
4560 // If the initializer list has a single element that is reference-related
4561 // to the parameter type, we initialize the reference from that.
4562 if (From->getNumInits() == 1) {
4563 Expr *Init = From->getInit(0);
4564
4565 QualType T2 = Init->getType();
4566
4567 // If the initializer is the address of an overloaded function, try
4568 // to resolve the overloaded function. If all goes well, T2 is the
4569 // type of the resulting function.
4570 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4571 DeclAccessPair Found;
4572 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4573 Init, ToType, false, Found))
4574 T2 = Fn->getType();
4575 }
4576
4577 // Compute some basic properties of the types and the initializer.
4578 bool dummy1 = false;
4579 bool dummy2 = false;
4580 bool dummy3 = false;
4581 Sema::ReferenceCompareResult RefRelationship
4582 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4583 dummy2, dummy3);
4584
Richard Smith4d2bbd72013-09-06 01:22:42 +00004585 if (RefRelationship >= Sema::Ref_Related) {
Richard Smitha93f1022013-09-06 22:30:28 +00004586 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4587 SuppressUserConversions,
4588 /*AllowExplicit=*/false);
Richard Smith4d2bbd72013-09-06 01:22:42 +00004589 }
Sebastian Redldf888642011-12-03 14:54:30 +00004590 }
4591
4592 // Otherwise, we bind the reference to a temporary created from the
4593 // initializer list.
4594 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4595 InOverloadResolution,
4596 AllowObjCWritebackConversion);
4597 if (Result.isFailure())
4598 return Result;
4599 assert(!Result.isEllipsis() &&
4600 "Sub-initialization cannot result in ellipsis conversion.");
4601
4602 // Can we even bind to a temporary?
4603 if (ToType->isRValueReferenceType() ||
4604 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4605 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4606 Result.UserDefined.After;
4607 SCS.ReferenceBinding = true;
4608 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4609 SCS.BindsToRvalue = true;
4610 SCS.BindsToFunctionLvalue = false;
4611 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4612 SCS.ObjCLifetimeConversionBinding = false;
4613 } else
4614 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4615 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004616 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004617 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004618
4619 // C++11 [over.ics.list]p6:
4620 // Otherwise, if the parameter type is not a class:
4621 if (!ToType->isRecordType()) {
4622 // - if the initializer list has one element, the implicit conversion
4623 // sequence is the one required to convert the element to the
4624 // parameter type.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004625 unsigned NumInits = From->getNumInits();
4626 if (NumInits == 1)
4627 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4628 SuppressUserConversions,
4629 InOverloadResolution,
4630 AllowObjCWritebackConversion);
4631 // - if the initializer list has no elements, the implicit conversion
4632 // sequence is the identity conversion.
4633 else if (NumInits == 0) {
4634 Result.setStandard();
4635 Result.Standard.setAsIdentityConversion();
John McCallb73bc9a2012-04-04 02:40:27 +00004636 Result.Standard.setFromType(ToType);
4637 Result.Standard.setAllToTypes(ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004638 }
4639 return Result;
4640 }
4641
4642 // C++11 [over.ics.list]p7:
4643 // In all cases other than those enumerated above, no conversion is possible
4644 return Result;
4645}
4646
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004647/// TryCopyInitialization - Try to copy-initialize a value of type
4648/// ToType from the expression From. Return the implicit conversion
4649/// sequence required to pass this argument, which may be a bad
4650/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004651/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004652/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004653static ImplicitConversionSequence
4654TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004656 bool InOverloadResolution,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004657 bool AllowObjCWritebackConversion,
4658 bool AllowExplicit) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004659 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4660 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4661 InOverloadResolution,AllowObjCWritebackConversion);
4662
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004663 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004664 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004665 /*FIXME:*/From->getLocStart(),
4666 SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00004667 AllowExplicit);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004668
John McCall5c32be02010-08-24 20:38:10 +00004669 return TryImplicitConversion(S, From, ToType,
4670 SuppressUserConversions,
4671 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004672 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004673 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004674 AllowObjCWritebackConversion,
4675 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004676}
4677
Anna Zaks1b068122011-07-28 19:46:48 +00004678static bool TryCopyInitialization(const CanQualType FromQTy,
4679 const CanQualType ToQTy,
4680 Sema &S,
4681 SourceLocation Loc,
4682 ExprValueKind FromVK) {
4683 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4684 ImplicitConversionSequence ICS =
4685 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4686
4687 return !ICS.isBad();
4688}
4689
Douglas Gregor436424c2008-11-18 23:14:02 +00004690/// TryObjectArgumentInitialization - Try to initialize the object
4691/// parameter of the given member function (@c Method) from the
4692/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004693static ImplicitConversionSequence
Richard Smith03c66d32013-01-26 02:07:32 +00004694TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004695 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004696 CXXMethodDecl *Method,
4697 CXXRecordDecl *ActingContext) {
4698 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004699 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4700 // const volatile object.
4701 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4702 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004703 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004704
4705 // Set up the conversion sequence as a "bad" conversion, to allow us
4706 // to exit early.
4707 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004708
4709 // We need to have an object of class type.
Douglas Gregor02824322011-01-26 19:30:28 +00004710 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004711 FromType = PT->getPointeeType();
4712
Douglas Gregor02824322011-01-26 19:30:28 +00004713 // When we had a pointer, it's implicitly dereferenced, so we
4714 // better have an lvalue.
4715 assert(FromClassification.isLValue());
4716 }
4717
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004718 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004719
Douglas Gregor02824322011-01-26 19:30:28 +00004720 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004721 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004722 // parameter is
4723 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004724 // - "lvalue reference to cv X" for functions declared without a
4725 // ref-qualifier or with the & ref-qualifier
4726 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004727 // ref-qualifier
4728 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004729 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004730 // cv-qualification on the member function declaration.
4731 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004732 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004733 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004734 // (C++ [over.match.funcs]p5). We perform a simplified version of
4735 // reference binding here, that allows class rvalues to bind to
4736 // non-constant references.
4737
Douglas Gregor02824322011-01-26 19:30:28 +00004738 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004739 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004740 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004741 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004742 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004743 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith03c66d32013-01-26 02:07:32 +00004744 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004745 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004746 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004747
4748 // Check that we have either the same type or a derived type. It
4749 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004750 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004751 ImplicitConversionKind SecondKind;
4752 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4753 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004754 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004755 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004756 else {
John McCall65eb8792010-02-25 01:37:24 +00004757 ICS.setBad(BadConversionSequence::unrelated_class,
4758 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004759 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004760 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004761
Douglas Gregor02824322011-01-26 19:30:28 +00004762 // Check the ref-qualifier.
4763 switch (Method->getRefQualifier()) {
4764 case RQ_None:
4765 // Do nothing; we don't care about lvalueness or rvalueness.
4766 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004767
Douglas Gregor02824322011-01-26 19:30:28 +00004768 case RQ_LValue:
4769 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4770 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004772 ImplicitParamType);
4773 return ICS;
4774 }
4775 break;
4776
4777 case RQ_RValue:
4778 if (!FromClassification.isRValue()) {
4779 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004780 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004781 ImplicitParamType);
4782 return ICS;
4783 }
4784 break;
4785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004786
Douglas Gregor436424c2008-11-18 23:14:02 +00004787 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004788 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004789 ICS.Standard.setAsIdentityConversion();
4790 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004791 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004792 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004793 ICS.Standard.ReferenceBinding = true;
4794 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004796 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004797 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4798 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4799 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004800 return ICS;
4801}
4802
4803/// PerformObjectArgumentInitialization - Perform initialization of
4804/// the implicit object parameter for the given Method with the given
4805/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004806ExprResult
4807Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004808 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004809 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004810 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004811 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004812 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004813 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004814
Douglas Gregor02824322011-01-26 19:30:28 +00004815 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004816 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004817 FromRecordType = PT->getPointeeType();
4818 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004819 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004820 } else {
4821 FromRecordType = From->getType();
4822 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004823 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004824 }
4825
John McCall6e9f8f62009-12-03 04:06:58 +00004826 // Note that we always use the true parent context when performing
4827 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004828 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004829 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4830 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004831 if (ICS.isBad()) {
4832 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4833 Qualifiers FromQs = FromRecordType.getQualifiers();
4834 Qualifiers ToQs = DestType.getQualifiers();
4835 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4836 if (CVR) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004837 Diag(From->getLocStart(),
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004838 diag::err_member_function_call_bad_cvr)
4839 << Method->getDeclName() << FromRecordType << (CVR - 1)
4840 << From->getSourceRange();
4841 Diag(Method->getLocation(), diag::note_previous_decl)
4842 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004843 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004844 }
4845 }
4846
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004847 return Diag(From->getLocStart(),
Chris Lattner3b054132008-11-19 05:08:23 +00004848 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004849 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004850 }
Mike Stump11289f42009-09-09 15:08:12 +00004851
John Wiegley01296292011-04-08 18:41:53 +00004852 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4853 ExprResult FromRes =
4854 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4855 if (FromRes.isInvalid())
4856 return ExprError();
4857 From = FromRes.take();
4858 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004859
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004860 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004861 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004862 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004863 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004864}
4865
Douglas Gregor5fb53972009-01-14 15:45:31 +00004866/// TryContextuallyConvertToBool - Attempt to contextually convert the
4867/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004868static ImplicitConversionSequence
4869TryContextuallyConvertToBool(Sema &S, Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004870 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004871 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004872 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004873 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004874 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00004875 /*AllowObjCWritebackConversion=*/false,
4876 /*AllowObjCConversionOnExplicit=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004877}
4878
4879/// PerformContextuallyConvertToBool - Perform a contextual conversion
4880/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004881ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004882 if (checkPlaceholderForOverload(*this, From))
4883 return ExprError();
4884
John McCall5c32be02010-08-24 20:38:10 +00004885 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004886 if (!ICS.isBad())
4887 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004888
Fariborz Jahanian76197412009-11-18 18:26:29 +00004889 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004890 return Diag(From->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +00004891 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004892 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004893 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004894}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895
Richard Smithf8379a02012-01-18 23:55:52 +00004896/// Check that the specified conversion is permitted in a converted constant
4897/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4898/// is acceptable.
4899static bool CheckConvertedConstantConversions(Sema &S,
4900 StandardConversionSequence &SCS) {
4901 // Since we know that the target type is an integral or unscoped enumeration
4902 // type, most conversion kinds are impossible. All possible First and Third
4903 // conversions are fine.
4904 switch (SCS.Second) {
4905 case ICK_Identity:
4906 case ICK_Integral_Promotion:
4907 case ICK_Integral_Conversion:
Guy Benyei259f9f42013-02-07 16:05:33 +00004908 case ICK_Zero_Event_Conversion:
Richard Smithf8379a02012-01-18 23:55:52 +00004909 return true;
4910
4911 case ICK_Boolean_Conversion:
Richard Smithca24ed42012-09-13 22:00:12 +00004912 // Conversion from an integral or unscoped enumeration type to bool is
4913 // classified as ICK_Boolean_Conversion, but it's also an integral
4914 // conversion, so it's permitted in a converted constant expression.
4915 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4916 SCS.getToType(2)->isBooleanType();
4917
Richard Smithf8379a02012-01-18 23:55:52 +00004918 case ICK_Floating_Integral:
4919 case ICK_Complex_Real:
4920 return false;
4921
4922 case ICK_Lvalue_To_Rvalue:
4923 case ICK_Array_To_Pointer:
4924 case ICK_Function_To_Pointer:
4925 case ICK_NoReturn_Adjustment:
4926 case ICK_Qualification:
4927 case ICK_Compatible_Conversion:
4928 case ICK_Vector_Conversion:
4929 case ICK_Vector_Splat:
4930 case ICK_Derived_To_Base:
4931 case ICK_Pointer_Conversion:
4932 case ICK_Pointer_Member:
4933 case ICK_Block_Pointer_Conversion:
4934 case ICK_Writeback_Conversion:
4935 case ICK_Floating_Promotion:
4936 case ICK_Complex_Promotion:
4937 case ICK_Complex_Conversion:
4938 case ICK_Floating_Conversion:
4939 case ICK_TransparentUnionConversion:
4940 llvm_unreachable("unexpected second conversion kind");
4941
4942 case ICK_Num_Conversion_Kinds:
4943 break;
4944 }
4945
4946 llvm_unreachable("unknown conversion kind");
4947}
4948
4949/// CheckConvertedConstantExpression - Check that the expression From is a
4950/// converted constant expression of type T, perform the conversion and produce
4951/// the converted expression, per C++11 [expr.const]p3.
4952ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4953 llvm::APSInt &Value,
4954 CCEKind CCE) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004955 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smithf8379a02012-01-18 23:55:52 +00004956 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4957
4958 if (checkPlaceholderForOverload(*this, From))
4959 return ExprError();
4960
4961 // C++11 [expr.const]p3 with proposed wording fixes:
4962 // A converted constant expression of type T is a core constant expression,
4963 // implicitly converted to a prvalue of type T, where the converted
4964 // expression is a literal constant expression and the implicit conversion
4965 // sequence contains only user-defined conversions, lvalue-to-rvalue
4966 // conversions, integral promotions, and integral conversions other than
4967 // narrowing conversions.
4968 ImplicitConversionSequence ICS =
4969 TryImplicitConversion(From, T,
4970 /*SuppressUserConversions=*/false,
4971 /*AllowExplicit=*/false,
4972 /*InOverloadResolution=*/false,
4973 /*CStyle=*/false,
4974 /*AllowObjcWritebackConversion=*/false);
4975 StandardConversionSequence *SCS = 0;
4976 switch (ICS.getKind()) {
4977 case ImplicitConversionSequence::StandardConversion:
4978 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004979 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004980 diag::err_typecheck_converted_constant_expression_disallowed)
4981 << From->getType() << From->getSourceRange() << T;
4982 SCS = &ICS.Standard;
4983 break;
4984 case ImplicitConversionSequence::UserDefinedConversion:
4985 // We are converting from class type to an integral or enumeration type, so
4986 // the Before sequence must be trivial.
4987 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004988 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004989 diag::err_typecheck_converted_constant_expression_disallowed)
4990 << From->getType() << From->getSourceRange() << T;
4991 SCS = &ICS.UserDefined.After;
4992 break;
4993 case ImplicitConversionSequence::AmbiguousConversion:
4994 case ImplicitConversionSequence::BadConversion:
4995 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar62ee6412012-03-09 18:35:03 +00004996 return Diag(From->getLocStart(),
Richard Smithf8379a02012-01-18 23:55:52 +00004997 diag::err_typecheck_converted_constant_expression)
4998 << From->getType() << From->getSourceRange() << T;
4999 return ExprError();
5000
5001 case ImplicitConversionSequence::EllipsisConversion:
5002 llvm_unreachable("ellipsis conversion in converted constant expression");
5003 }
5004
5005 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
5006 if (Result.isInvalid())
5007 return Result;
5008
5009 // Check for a narrowing implicit conversion.
5010 APValue PreNarrowingValue;
Richard Smith5614ca72012-03-23 23:55:39 +00005011 QualType PreNarrowingType;
Richard Smith5614ca72012-03-23 23:55:39 +00005012 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
5013 PreNarrowingType)) {
Richard Smithf8379a02012-01-18 23:55:52 +00005014 case NK_Variable_Narrowing:
5015 // Implicit conversion to a narrower type, and the value is not a constant
5016 // expression. We'll diagnose this in a moment.
5017 case NK_Not_Narrowing:
5018 break;
5019
5020 case NK_Constant_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005021 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005022 << CCE << /*Constant*/1
Richard Smith5614ca72012-03-23 23:55:39 +00005023 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smithf8379a02012-01-18 23:55:52 +00005024 break;
5025
5026 case NK_Type_Narrowing:
Richard Smith16e1b072013-11-12 02:41:45 +00005027 Diag(From->getLocStart(), diag::ext_cce_narrowing)
Richard Smithf8379a02012-01-18 23:55:52 +00005028 << CCE << /*Constant*/0 << From->getType() << T;
5029 break;
5030 }
5031
5032 // Check the expression is a constant expression.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005033 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithf8379a02012-01-18 23:55:52 +00005034 Expr::EvalResult Eval;
5035 Eval.Diag = &Notes;
5036
Douglas Gregorebe2db72013-04-08 23:24:07 +00005037 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smithf8379a02012-01-18 23:55:52 +00005038 // The expression can't be folded, so we can't keep it at this position in
5039 // the AST.
5040 Result = ExprError();
Richard Smith911e1422012-01-30 22:27:01 +00005041 } else {
Richard Smithf8379a02012-01-18 23:55:52 +00005042 Value = Eval.Val.getInt();
Richard Smith911e1422012-01-30 22:27:01 +00005043
5044 if (Notes.empty()) {
5045 // It's a constant expression.
5046 return Result;
5047 }
Richard Smithf8379a02012-01-18 23:55:52 +00005048 }
5049
5050 // It's not a constant expression. Produce an appropriate diagnostic.
5051 if (Notes.size() == 1 &&
5052 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5053 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5054 else {
Daniel Dunbar62ee6412012-03-09 18:35:03 +00005055 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smithf8379a02012-01-18 23:55:52 +00005056 << CCE << From->getSourceRange();
5057 for (unsigned I = 0; I < Notes.size(); ++I)
5058 Diag(Notes[I].first, Notes[I].second);
5059 }
Richard Smith911e1422012-01-30 22:27:01 +00005060 return Result;
Richard Smithf8379a02012-01-18 23:55:52 +00005061}
5062
John McCallfec112d2011-09-09 06:11:02 +00005063/// dropPointerConversions - If the given standard conversion sequence
5064/// involves any pointer conversions, remove them. This may change
5065/// the result type of the conversion sequence.
5066static void dropPointerConversion(StandardConversionSequence &SCS) {
5067 if (SCS.Second == ICK_Pointer_Conversion) {
5068 SCS.Second = ICK_Identity;
5069 SCS.Third = ICK_Identity;
5070 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5071 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005072}
John McCall5c32be02010-08-24 20:38:10 +00005073
John McCallfec112d2011-09-09 06:11:02 +00005074/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5075/// convert the expression From to an Objective-C pointer type.
5076static ImplicitConversionSequence
5077TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5078 // Do an implicit conversion to 'id'.
5079 QualType Ty = S.Context.getObjCIdType();
5080 ImplicitConversionSequence ICS
5081 = TryImplicitConversion(S, From, Ty,
5082 // FIXME: Are these flags correct?
5083 /*SuppressUserConversions=*/false,
5084 /*AllowExplicit=*/true,
5085 /*InOverloadResolution=*/false,
5086 /*CStyle=*/false,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005087 /*AllowObjCWritebackConversion=*/false,
5088 /*AllowObjCConversionOnExplicit=*/true);
John McCallfec112d2011-09-09 06:11:02 +00005089
5090 // Strip off any final conversions to 'id'.
5091 switch (ICS.getKind()) {
5092 case ImplicitConversionSequence::BadConversion:
5093 case ImplicitConversionSequence::AmbiguousConversion:
5094 case ImplicitConversionSequence::EllipsisConversion:
5095 break;
5096
5097 case ImplicitConversionSequence::UserDefinedConversion:
5098 dropPointerConversion(ICS.UserDefined.After);
5099 break;
5100
5101 case ImplicitConversionSequence::StandardConversion:
5102 dropPointerConversion(ICS.Standard);
5103 break;
5104 }
5105
5106 return ICS;
5107}
5108
5109/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5110/// conversion of the expression From to an Objective-C pointer type.
5111ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00005112 if (checkPlaceholderForOverload(*this, From))
5113 return ExprError();
5114
John McCall8b07ec22010-05-15 11:32:37 +00005115 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00005116 ImplicitConversionSequence ICS =
5117 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005118 if (!ICS.isBad())
5119 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00005120 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00005121}
Douglas Gregor5fb53972009-01-14 15:45:31 +00005122
Richard Smith8dd34252012-02-04 07:07:42 +00005123/// Determine whether the provided type is an integral type, or an enumeration
5124/// type of a permitted flavor.
Richard Smithccc11812013-05-21 19:05:48 +00005125bool Sema::ICEConvertDiagnoser::match(QualType T) {
5126 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5127 : T->isIntegralOrUnscopedEnumerationType();
Richard Smith8dd34252012-02-04 07:07:42 +00005128}
5129
Larisse Voufo236bec22013-06-10 06:50:24 +00005130static ExprResult
5131diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5132 Sema::ContextualImplicitConverter &Converter,
5133 QualType T, UnresolvedSetImpl &ViableConversions) {
5134
5135 if (Converter.Suppress)
5136 return ExprError();
5137
5138 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5139 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5140 CXXConversionDecl *Conv =
5141 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5142 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5143 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5144 }
5145 return SemaRef.Owned(From);
5146}
5147
5148static bool
5149diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5150 Sema::ContextualImplicitConverter &Converter,
5151 QualType T, bool HadMultipleCandidates,
5152 UnresolvedSetImpl &ExplicitConversions) {
5153 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5154 DeclAccessPair Found = ExplicitConversions[0];
5155 CXXConversionDecl *Conversion =
5156 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5157
5158 // The user probably meant to invoke the given explicit
5159 // conversion; use it.
5160 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5161 std::string TypeStr;
5162 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5163
5164 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5165 << FixItHint::CreateInsertion(From->getLocStart(),
5166 "static_cast<" + TypeStr + ">(")
5167 << FixItHint::CreateInsertion(
5168 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5169 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5170
5171 // If we aren't in a SFINAE context, build a call to the
5172 // explicit conversion function.
5173 if (SemaRef.isSFINAEContext())
5174 return true;
5175
5176 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5177 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5178 HadMultipleCandidates);
5179 if (Result.isInvalid())
5180 return true;
5181 // Record usage of conversion in an implicit cast.
5182 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5183 CK_UserDefinedConversion, Result.get(), 0,
5184 Result.get()->getValueKind());
5185 }
5186 return false;
5187}
5188
5189static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5190 Sema::ContextualImplicitConverter &Converter,
5191 QualType T, bool HadMultipleCandidates,
5192 DeclAccessPair &Found) {
5193 CXXConversionDecl *Conversion =
5194 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5195 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5196
5197 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5198 if (!Converter.SuppressConversion) {
5199 if (SemaRef.isSFINAEContext())
5200 return true;
5201
5202 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5203 << From->getSourceRange();
5204 }
5205
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 return false;
5215}
5216
5217static ExprResult finishContextualImplicitConversion(
5218 Sema &SemaRef, SourceLocation Loc, Expr *From,
5219 Sema::ContextualImplicitConverter &Converter) {
5220 if (!Converter.match(From->getType()) && !Converter.Suppress)
5221 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5222 << From->getSourceRange();
5223
5224 return SemaRef.DefaultLvalueConversion(From);
5225}
5226
5227static void
5228collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5229 UnresolvedSetImpl &ViableConversions,
5230 OverloadCandidateSet &CandidateSet) {
5231 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5232 DeclAccessPair FoundDecl = ViableConversions[I];
5233 NamedDecl *D = FoundDecl.getDecl();
5234 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5235 if (isa<UsingShadowDecl>(D))
5236 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5237
5238 CXXConversionDecl *Conv;
5239 FunctionTemplateDecl *ConvTemplate;
5240 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5241 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5242 else
5243 Conv = cast<CXXConversionDecl>(D);
5244
5245 if (ConvTemplate)
5246 SemaRef.AddTemplateConversionCandidate(
Douglas Gregor4b60a152013-11-07 22:34:54 +00005247 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet,
5248 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005249 else
5250 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
Douglas Gregor4b60a152013-11-07 22:34:54 +00005251 ToType, CandidateSet,
5252 /*AllowObjCConversionOnExplicit=*/false);
Larisse Voufo236bec22013-06-10 06:50:24 +00005253 }
5254}
5255
Richard Smithccc11812013-05-21 19:05:48 +00005256/// \brief Attempt to convert the given expression to a type which is accepted
5257/// by the given converter.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005258///
Richard Smithccc11812013-05-21 19:05:48 +00005259/// This routine will attempt to convert an expression of class type to a
5260/// type accepted by the specified converter. In C++11 and before, the class
5261/// must have a single non-explicit conversion function converting to a matching
5262/// type. In C++1y, there can be multiple such conversion functions, but only
5263/// one target type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005264///
Douglas Gregor4799d032010-06-30 00:20:43 +00005265/// \param Loc The source location of the construct that requires the
5266/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005267///
James Dennett18348b62012-06-22 08:52:37 +00005268/// \param From The expression we're converting from.
Douglas Gregor4799d032010-06-30 00:20:43 +00005269///
Richard Smithccc11812013-05-21 19:05:48 +00005270/// \param Converter Used to control and diagnose the conversion process.
Richard Smith8dd34252012-02-04 07:07:42 +00005271///
Douglas Gregor4799d032010-06-30 00:20:43 +00005272/// \returns The expression, converted to an integral or enumeration type if
5273/// successful.
Richard Smithccc11812013-05-21 19:05:48 +00005274ExprResult Sema::PerformContextualImplicitConversion(
5275 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005276 // We can't perform any more checking for type-dependent expressions.
5277 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00005278 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005279
Eli Friedman1da70392012-01-26 00:26:18 +00005280 // Process placeholders immediately.
5281 if (From->hasPlaceholderType()) {
5282 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo236bec22013-06-10 06:50:24 +00005283 if (result.isInvalid())
5284 return result;
Eli Friedman1da70392012-01-26 00:26:18 +00005285 From = result.take();
5286 }
5287
Richard Smithccc11812013-05-21 19:05:48 +00005288 // If the expression already has a matching type, we're golden.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005289 QualType T = From->getType();
Richard Smithccc11812013-05-21 19:05:48 +00005290 if (Converter.match(T))
Eli Friedman1da70392012-01-26 00:26:18 +00005291 return DefaultLvalueConversion(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005292
5293 // FIXME: Check for missing '()' if T is a function type?
5294
Richard Smithccc11812013-05-21 19:05:48 +00005295 // We can only perform contextual implicit conversions on objects of class
5296 // type.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005297 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +00005298 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smithccc11812013-05-21 19:05:48 +00005299 if (!Converter.Suppress)
5300 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00005301 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005302 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005303
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005304 // We must have a complete class type.
Douglas Gregora6c5abb2012-05-04 16:48:41 +00005305 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smithccc11812013-05-21 19:05:48 +00005306 ContextualImplicitConverter &Converter;
Douglas Gregore2b37442012-05-04 22:38:52 +00005307 Expr *From;
Richard Smithccc11812013-05-21 19:05:48 +00005308
5309 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5310 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5311
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005312 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smithccc11812013-05-21 19:05:48 +00005313 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005314 }
Richard Smithccc11812013-05-21 19:05:48 +00005315 } IncompleteDiagnoser(Converter, From);
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00005316
5317 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCallb268a282010-08-23 23:25:46 +00005318 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005319
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005320 // Look for a conversion to an integral or enumeration type.
Larisse Voufo236bec22013-06-10 06:50:24 +00005321 UnresolvedSet<4>
5322 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005323 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00005324 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo236bec22013-06-10 06:50:24 +00005325 CXXRecordDecl::conversion_iterator> Conversions =
5326 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005327
Larisse Voufo236bec22013-06-10 06:50:24 +00005328 bool HadMultipleCandidates =
5329 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005330
Larisse Voufo236bec22013-06-10 06:50:24 +00005331 // To check that there is only one target type, in C++1y:
5332 QualType ToType;
5333 bool HasUniqueTargetType = true;
5334
5335 // Collect explicit or viable (potentially in C++1y) conversions.
5336 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5337 E = Conversions.second;
5338 I != E; ++I) {
5339 NamedDecl *D = (*I)->getUnderlyingDecl();
5340 CXXConversionDecl *Conversion;
5341 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5342 if (ConvTemplate) {
5343 if (getLangOpts().CPlusPlus1y)
5344 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5345 else
5346 continue; // C++11 does not consider conversion operator templates(?).
5347 } else
5348 Conversion = cast<CXXConversionDecl>(D);
5349
5350 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5351 "Conversion operator templates are considered potentially "
5352 "viable in C++1y");
5353
5354 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5355 if (Converter.match(CurToType) || ConvTemplate) {
5356
5357 if (Conversion->isExplicit()) {
5358 // FIXME: For C++1y, do we need this restriction?
5359 // cf. diagnoseNoViableConversion()
5360 if (!ConvTemplate)
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005361 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo236bec22013-06-10 06:50:24 +00005362 } else {
5363 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5364 if (ToType.isNull())
5365 ToType = CurToType.getUnqualifiedType();
5366 else if (HasUniqueTargetType &&
5367 (CurToType.getUnqualifiedType() != ToType))
5368 HasUniqueTargetType = false;
5369 }
5370 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005371 }
Richard Smith8dd34252012-02-04 07:07:42 +00005372 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005373 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374
Larisse Voufo236bec22013-06-10 06:50:24 +00005375 if (getLangOpts().CPlusPlus1y) {
5376 // C++1y [conv]p6:
5377 // ... An expression e of class type E appearing in such a context
5378 // is said to be contextually implicitly converted to a specified
5379 // type T and is well-formed if and only if e can be implicitly
5380 // converted to a type T that is determined as follows: E is searched
Larisse Voufo67170bd2013-06-10 08:25:58 +00005381 // for conversion functions whose return type is cv T or reference to
5382 // cv T such that T is allowed by the context. There shall be
Larisse Voufo236bec22013-06-10 06:50:24 +00005383 // exactly one such T.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005384
Larisse Voufo236bec22013-06-10 06:50:24 +00005385 // If no unique T is found:
5386 if (ToType.isNull()) {
5387 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5388 HadMultipleCandidates,
5389 ExplicitConversions))
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005390 return ExprError();
Larisse Voufo236bec22013-06-10 06:50:24 +00005391 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005392 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005393
Larisse Voufo236bec22013-06-10 06:50:24 +00005394 // If more than one unique Ts are found:
5395 if (!HasUniqueTargetType)
5396 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5397 ViableConversions);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005398
Larisse Voufo236bec22013-06-10 06:50:24 +00005399 // If one unique T is found:
5400 // First, build a candidate set from the previously recorded
5401 // potentially viable conversions.
5402 OverloadCandidateSet CandidateSet(Loc);
5403 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5404 CandidateSet);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005405
Larisse Voufo236bec22013-06-10 06:50:24 +00005406 // Then, perform overload resolution over the candidate set.
5407 OverloadCandidateSet::iterator Best;
5408 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5409 case OR_Success: {
5410 // Apply this conversion.
5411 DeclAccessPair Found =
5412 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5413 if (recordConversion(*this, Loc, From, Converter, T,
5414 HadMultipleCandidates, Found))
5415 return ExprError();
5416 break;
5417 }
5418 case OR_Ambiguous:
5419 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5420 ViableConversions);
5421 case OR_No_Viable_Function:
5422 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5423 HadMultipleCandidates,
5424 ExplicitConversions))
5425 return ExprError();
5426 // fall through 'OR_Deleted' case.
5427 case OR_Deleted:
5428 // We'll complain below about a non-integral condition type.
5429 break;
5430 }
5431 } else {
5432 switch (ViableConversions.size()) {
5433 case 0: {
5434 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5435 HadMultipleCandidates,
5436 ExplicitConversions))
Douglas Gregor4799d032010-06-30 00:20:43 +00005437 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005438
Larisse Voufo236bec22013-06-10 06:50:24 +00005439 // We'll complain below about a non-integral condition type.
5440 break;
Douglas Gregor4799d032010-06-30 00:20:43 +00005441 }
Larisse Voufo236bec22013-06-10 06:50:24 +00005442 case 1: {
5443 // Apply this conversion.
5444 DeclAccessPair Found = ViableConversions[0];
5445 if (recordConversion(*this, Loc, From, Converter, T,
5446 HadMultipleCandidates, Found))
5447 return ExprError();
5448 break;
5449 }
5450 default:
5451 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5452 ViableConversions);
5453 }
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005455
Larisse Voufo236bec22013-06-10 06:50:24 +00005456 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00005457}
5458
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005459/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00005460/// candidate functions, using the given function call arguments. If
5461/// @p SuppressUserConversions, then don't allow user-defined
5462/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00005463///
James Dennett2a4d13c2012-06-15 07:13:21 +00005464/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregorcabea402009-09-22 15:41:20 +00005465/// based on an incomplete set of function arguments. This feature is used by
5466/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00005467void
5468Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00005469 DeclAccessPair FoundDecl,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005470 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005471 OverloadCandidateSet &CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00005472 bool SuppressUserConversions,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005473 bool PartialOverloading,
5474 bool AllowExplicit) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005475 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005476 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005477 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00005478 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00005479 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00005480
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005481 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00005482 if (!isa<CXXConstructorDecl>(Method)) {
5483 // If we get here, it's because we're calling a member function
5484 // that is named without a member access expression (e.g.,
5485 // "this->f") that was either written explicitly or created
5486 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00005487 // function, e.g., X::f(). We use an empty type for the implied
5488 // object argument (C++ [over.call.func]p3), and the acting context
5489 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00005490 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005491 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005492 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00005493 return;
5494 }
5495 // We treat a constructor like a non-member function, since its object
5496 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005497 }
5498
Douglas Gregorff7028a2009-11-13 23:59:09 +00005499 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005500 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00005501
Richard Smith8b86f2d2013-11-04 01:48:18 +00005502 // C++11 [class.copy]p11: [DR1402]
5503 // A defaulted move constructor that is defined as deleted is ignored by
5504 // overload resolution.
5505 CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function);
5506 if (Constructor && Constructor->isDefaulted() && Constructor->isDeleted() &&
5507 Constructor->isMoveConstructor())
5508 return;
5509
Douglas Gregor27381f32009-11-23 12:27:39 +00005510 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005511 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005512
Richard Smith8b86f2d2013-11-04 01:48:18 +00005513 if (Constructor) {
Douglas Gregorffe14e32009-11-14 01:20:54 +00005514 // C++ [class.copy]p3:
5515 // A member function template is never instantiated to perform the copy
5516 // of a class object to an object of its class type.
5517 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005518 if (Args.size() == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00005519 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00005520 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5521 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00005522 return;
5523 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005524
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005525 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005526 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00005527 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005528 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005529 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005530 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005531 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005532 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005533
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005534 unsigned NumArgsInProto = Proto->getNumArgs();
5535
5536 // (C++ 13.3.2p2): A candidate function having fewer than m
5537 // parameters is viable only if it has an ellipsis in its parameter
5538 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005539 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00005540 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005541 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005542 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005543 return;
5544 }
5545
5546 // (C++ 13.3.2p2): A candidate function having more than m parameters
5547 // is viable only if the (m+1)st parameter has a default argument
5548 // (8.3.6). For the purposes of overload resolution, the
5549 // parameter list is truncated on the right, so that there are
5550 // exactly m parameters.
5551 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005552 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005553 // Not enough arguments.
5554 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005555 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005556 return;
5557 }
5558
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005559 // (CUDA B.1): Check for invalid calls between targets.
David Blaikiebbafb8a2012-03-11 07:00:24 +00005560 if (getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00005561 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5562 if (CheckCUDATarget(Caller, Function)) {
5563 Candidate.Viable = false;
5564 Candidate.FailureKind = ovl_fail_bad_target;
5565 return;
5566 }
5567
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005568 // Determine the implicit conversion sequences for each of the
5569 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005570 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005571 if (ArgIdx < NumArgsInProto) {
5572 // (C++ 13.3.2p3): for F to be a viable function, there shall
5573 // exist for each argument an implicit conversion sequence
5574 // (13.3.3.1) that converts that argument to the corresponding
5575 // parameter of F.
5576 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005577 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005578 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005579 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005580 /*InOverloadResolution=*/true,
5581 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005582 getLangOpts().ObjCAutoRefCount,
Douglas Gregor6073dca2012-02-24 23:56:31 +00005583 AllowExplicit);
John McCall0d1da222010-01-12 00:44:57 +00005584 if (Candidate.Conversions[ArgIdx].isBad()) {
5585 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005586 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005587 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005588 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005589 } else {
5590 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5591 // argument for which there is no corresponding parameter is
5592 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005593 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005594 }
5595 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005596
5597 if (EnableIfAttr *FailedAttr = CheckEnableIf(Function, Args)) {
5598 Candidate.Viable = false;
5599 Candidate.FailureKind = ovl_fail_enable_if;
5600 Candidate.DeductionFailure.Data = FailedAttr;
5601 return;
5602 }
5603}
5604
5605static bool IsNotEnableIfAttr(Attr *A) { return !isa<EnableIfAttr>(A); }
5606
5607EnableIfAttr *Sema::CheckEnableIf(FunctionDecl *Function, ArrayRef<Expr *> Args,
5608 bool MissingImplicitThis) {
5609 // FIXME: specific_attr_iterator<EnableIfAttr> iterates in reverse order, but
5610 // we need to find the first failing one.
5611 if (!Function->hasAttrs())
5612 return 0;
5613 AttrVec Attrs = Function->getAttrs();
5614 AttrVec::iterator E = std::remove_if(Attrs.begin(), Attrs.end(),
5615 IsNotEnableIfAttr);
5616 if (Attrs.begin() == E)
5617 return 0;
5618 std::reverse(Attrs.begin(), E);
5619
5620 SFINAETrap Trap(*this);
5621
5622 // Convert the arguments.
5623 SmallVector<Expr *, 16> ConvertedArgs;
5624 bool InitializationFailed = false;
5625 for (unsigned i = 0, e = Args.size(); i != e; ++i) {
5626 if (i == 0 && !MissingImplicitThis && isa<CXXMethodDecl>(Function) &&
5627 !cast<CXXMethodDecl>(Function)->isStatic()) {
5628 CXXMethodDecl *Method = cast<CXXMethodDecl>(Function);
5629 ExprResult R =
5630 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
5631 Method, Method);
5632 if (R.isInvalid()) {
5633 InitializationFailed = true;
5634 break;
5635 }
5636 ConvertedArgs.push_back(R.take());
5637 } else {
5638 ExprResult R =
5639 PerformCopyInitialization(InitializedEntity::InitializeParameter(
5640 Context,
5641 Function->getParamDecl(i)),
5642 SourceLocation(),
5643 Args[i]);
5644 if (R.isInvalid()) {
5645 InitializationFailed = true;
5646 break;
5647 }
5648 ConvertedArgs.push_back(R.take());
5649 }
5650 }
5651
5652 if (InitializationFailed || Trap.hasErrorOccurred())
5653 return cast<EnableIfAttr>(Attrs[0]);
5654
5655 for (AttrVec::iterator I = Attrs.begin(); I != E; ++I) {
5656 APValue Result;
5657 EnableIfAttr *EIA = cast<EnableIfAttr>(*I);
5658 if (!EIA->getCond()->EvaluateWithSubstitution(
5659 Result, Context, Function,
5660 llvm::ArrayRef<const Expr*>(ConvertedArgs.data(),
5661 ConvertedArgs.size())) ||
5662 !Result.isInt() || !Result.getInt().getBoolValue()) {
5663 return EIA;
5664 }
5665 }
5666 return 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005667}
5668
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005669/// \brief Add all of the function declarations in the given function set to
Nick Lewyckyed4265c2013-09-22 10:06:01 +00005670/// the overload candidate set.
John McCall4c4c1df2010-01-26 03:27:55 +00005671void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005672 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005673 OverloadCandidateSet& CandidateSet,
Richard Smithbcc22fc2012-03-09 08:00:36 +00005674 bool SuppressUserConversions,
5675 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall4c4c1df2010-01-26 03:27:55 +00005676 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00005677 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005679 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005680 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005681 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00005682 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005683 Args.slice(1), CandidateSet,
5684 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005685 else
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005686 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005687 SuppressUserConversions);
5688 } else {
John McCalla0296f72010-03-19 07:35:19 +00005689 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005690 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5691 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00005692 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00005693 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005694 ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005695 Args[0]->getType(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005696 Args[0]->Classify(Context), Args.slice(1),
5697 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005698 else
John McCalla0296f72010-03-19 07:35:19 +00005699 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smithbcc22fc2012-03-09 08:00:36 +00005700 ExplicitTemplateArgs, Args,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005701 CandidateSet, SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005702 }
Douglas Gregor15448f82009-06-27 21:05:07 +00005703 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005704}
5705
John McCallf0f1cf02009-11-17 07:50:12 +00005706/// AddMethodCandidate - Adds a named decl (which is some kind of
5707/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00005708void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005709 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005710 Expr::Classification ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005711 ArrayRef<Expr *> Args,
John McCallf0f1cf02009-11-17 07:50:12 +00005712 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005713 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00005714 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00005715 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00005716
5717 if (isa<UsingShadowDecl>(Decl))
5718 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005719
John McCallf0f1cf02009-11-17 07:50:12 +00005720 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5721 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5722 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00005723 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5724 /*ExplicitArgs*/ 0,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005725 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005726 Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005727 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005728 } else {
John McCalla0296f72010-03-19 07:35:19 +00005729 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005730 ObjectType, ObjectClassification,
Rafael Espindola51629df2013-04-29 19:29:25 +00005731 Args,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005732 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00005733 }
5734}
5735
Douglas Gregor436424c2008-11-18 23:14:02 +00005736/// AddMethodCandidate - Adds the given C++ member function to the set
5737/// of candidate functions, using the given function call arguments
5738/// and the object argument (@c Object). For example, in a call
5739/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5740/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5741/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00005742/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00005743void
John McCalla0296f72010-03-19 07:35:19 +00005744Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00005745 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005746 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005747 ArrayRef<Expr *> Args,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005748 OverloadCandidateSet &CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005749 bool SuppressUserConversions) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005750 const FunctionProtoType *Proto
John McCall9dd450b2009-09-21 23:43:11 +00005751 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00005752 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00005753 assert(!isa<CXXConstructorDecl>(Method) &&
5754 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00005755
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005756 if (!CandidateSet.isNewCandidate(Method))
5757 return;
5758
Richard Smith8b86f2d2013-11-04 01:48:18 +00005759 // C++11 [class.copy]p23: [DR1402]
5760 // A defaulted move assignment operator that is defined as deleted is
5761 // ignored by overload resolution.
5762 if (Method->isDefaulted() && Method->isDeleted() &&
5763 Method->isMoveAssignmentOperator())
5764 return;
5765
Douglas Gregor27381f32009-11-23 12:27:39 +00005766 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005767 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005768
Douglas Gregor436424c2008-11-18 23:14:02 +00005769 // Add this candidate
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005770 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00005771 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00005772 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005773 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005774 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005775 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor436424c2008-11-18 23:14:02 +00005776
5777 unsigned NumArgsInProto = Proto->getNumArgs();
5778
5779 // (C++ 13.3.2p2): A candidate function having fewer than m
5780 // parameters is viable only if it has an ellipsis in its parameter
5781 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005782 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005783 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005784 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005785 return;
5786 }
5787
5788 // (C++ 13.3.2p2): A candidate function having more than m parameters
5789 // is viable only if the (m+1)st parameter has a default argument
5790 // (8.3.6). For the purposes of overload resolution, the
5791 // parameter list is truncated on the right, so that there are
5792 // exactly m parameters.
5793 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005794 if (Args.size() < MinRequiredArgs) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005795 // Not enough arguments.
5796 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005797 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00005798 return;
5799 }
5800
5801 Candidate.Viable = true;
Douglas Gregor436424c2008-11-18 23:14:02 +00005802
John McCall6e9f8f62009-12-03 04:06:58 +00005803 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005804 // The implicit object argument is ignored.
5805 Candidate.IgnoreObjectArgument = true;
5806 else {
5807 // Determine the implicit conversion sequence for the object
5808 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00005809 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00005810 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5811 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005812 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005813 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005814 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005815 return;
5816 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005817 }
5818
5819 // Determine the implicit conversion sequences for each of the
5820 // arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005821 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005822 if (ArgIdx < NumArgsInProto) {
5823 // (C++ 13.3.2p3): for F to be a viable function, there shall
5824 // exist for each argument an implicit conversion sequence
5825 // (13.3.3.1) that converts that argument to the corresponding
5826 // parameter of F.
5827 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005828 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005829 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005830 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00005831 /*InOverloadResolution=*/true,
5832 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00005833 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005834 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005835 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005836 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005837 return;
Douglas Gregor436424c2008-11-18 23:14:02 +00005838 }
5839 } else {
5840 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5841 // argument for which there is no corresponding parameter is
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005842 // considered to "match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005843 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00005844 }
5845 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00005846
5847 if (EnableIfAttr *FailedAttr = CheckEnableIf(Method, Args, true)) {
5848 Candidate.Viable = false;
5849 Candidate.FailureKind = ovl_fail_enable_if;
5850 Candidate.DeductionFailure.Data = FailedAttr;
5851 return;
5852 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005853}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005854
Douglas Gregor97628d62009-08-21 00:16:32 +00005855/// \brief Add a C++ member function template as a candidate to the candidate
5856/// set, using template argument deduction to produce an appropriate member
5857/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005858void
Douglas Gregor97628d62009-08-21 00:16:32 +00005859Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00005860 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005861 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005862 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00005863 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00005864 Expr::Classification ObjectClassification,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005865 ArrayRef<Expr *> Args,
Douglas Gregor97628d62009-08-21 00:16:32 +00005866 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005867 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005868 if (!CandidateSet.isNewCandidate(MethodTmpl))
5869 return;
5870
Douglas Gregor97628d62009-08-21 00:16:32 +00005871 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005872 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00005873 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005874 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00005875 // candidate functions in the usual way.113) A given name can refer to one
5876 // or more function templates and also to a set of overloaded non-template
5877 // functions. In such a case, the candidate functions generated from each
5878 // function template are combined with the set of non-template candidate
5879 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005880 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00005881 FunctionDecl *Specialization = 0;
5882 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005883 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5884 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005885 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005886 Candidate.FoundDecl = FoundDecl;
5887 Candidate.Function = MethodTmpl->getTemplatedDecl();
5888 Candidate.Viable = false;
5889 Candidate.FailureKind = ovl_fail_bad_deduction;
5890 Candidate.IsSurrogate = false;
5891 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005892 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005893 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005894 Info);
5895 return;
5896 }
Mike Stump11289f42009-09-09 15:08:12 +00005897
Douglas Gregor97628d62009-08-21 00:16:32 +00005898 // Add the function template specialization produced by template argument
5899 // deduction as a candidate.
5900 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00005901 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00005902 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00005903 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005904 ActingContext, ObjectType, ObjectClassification, Args,
5905 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00005906}
5907
Douglas Gregor05155d82009-08-21 23:19:43 +00005908/// \brief Add a C++ function template specialization as a candidate
5909/// in the candidate set, using template argument deduction to produce
5910/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00005911void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005912Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005913 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00005914 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00005915 ArrayRef<Expr *> Args,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005916 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005917 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005918 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5919 return;
5920
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005921 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00005922 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005923 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00005924 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005925 // candidate functions in the usual way.113) A given name can refer to one
5926 // or more function templates and also to a set of overloaded non-template
5927 // functions. In such a case, the candidate functions generated from each
5928 // function template are combined with the set of non-template candidate
5929 // functions.
Craig Toppere6706e42012-09-19 02:26:47 +00005930 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005931 FunctionDecl *Specialization = 0;
5932 if (TemplateDeductionResult Result
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005933 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5934 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00005935 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCalla0296f72010-03-19 07:35:19 +00005936 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00005937 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5938 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005939 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00005940 Candidate.IsSurrogate = false;
5941 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005942 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005943 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005944 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005945 return;
5946 }
Mike Stump11289f42009-09-09 15:08:12 +00005947
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005948 // Add the function template specialization produced by template argument
5949 // deduction as a candidate.
5950 assert(Specialization && "Missing function template specialization?");
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00005951 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00005952 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00005953}
Mike Stump11289f42009-09-09 15:08:12 +00005954
Douglas Gregor4b60a152013-11-07 22:34:54 +00005955/// Determine whether this is an allowable conversion from the result
5956/// of an explicit conversion operator to the expected type, per C++
5957/// [over.match.conv]p1 and [over.match.ref]p1.
5958///
5959/// \param ConvType The return type of the conversion function.
5960///
5961/// \param ToType The type we are converting to.
5962///
5963/// \param AllowObjCPointerConversion Allow a conversion from one
5964/// Objective-C pointer to another.
5965///
5966/// \returns true if the conversion is allowable, false otherwise.
5967static bool isAllowableExplicitConversion(Sema &S,
5968 QualType ConvType, QualType ToType,
5969 bool AllowObjCPointerConversion) {
5970 QualType ToNonRefType = ToType.getNonReferenceType();
5971
5972 // Easy case: the types are the same.
5973 if (S.Context.hasSameUnqualifiedType(ConvType, ToNonRefType))
5974 return true;
5975
5976 // Allow qualification conversions.
5977 bool ObjCLifetimeConversion;
5978 if (S.IsQualificationConversion(ConvType, ToNonRefType, /*CStyle*/false,
5979 ObjCLifetimeConversion))
5980 return true;
5981
5982 // If we're not allowed to consider Objective-C pointer conversions,
5983 // we're done.
5984 if (!AllowObjCPointerConversion)
5985 return false;
5986
5987 // Is this an Objective-C pointer conversion?
5988 bool IncompatibleObjC = false;
5989 QualType ConvertedType;
5990 return S.isObjCPointerConversion(ConvType, ToNonRefType, ConvertedType,
5991 IncompatibleObjC);
5992}
5993
Douglas Gregora1f013e2008-11-07 22:36:19 +00005994/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00005995/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00005996/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00005997/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00005998/// (which may or may not be the same type as the type that the
5999/// conversion function produces).
6000void
6001Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006002 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006003 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006004 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006005 OverloadCandidateSet& CandidateSet,
6006 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006007 assert(!Conversion->getDescribedFunctionTemplate() &&
6008 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00006009 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006010 if (!CandidateSet.isNewCandidate(Conversion))
6011 return;
6012
Richard Smith2a7d4812013-05-04 07:00:32 +00006013 // If the conversion function has an undeduced return type, trigger its
6014 // deduction now.
6015 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
6016 if (DeduceReturnType(Conversion, From->getExprLoc()))
6017 return;
6018 ConvType = Conversion->getConversionType().getNonReferenceType();
6019 }
6020
Richard Smith089c3162013-09-21 21:55:46 +00006021 // Per C++ [over.match.conv]p1, [over.match.ref]p1, an explicit conversion
6022 // operator is only a candidate if its return type is the target type or
6023 // can be converted to the target type with a qualification conversion.
Douglas Gregor4b60a152013-11-07 22:34:54 +00006024 if (Conversion->isExplicit() &&
6025 !isAllowableExplicitConversion(*this, ConvType, ToType,
6026 AllowObjCConversionOnExplicit))
Richard Smith089c3162013-09-21 21:55:46 +00006027 return;
6028
Douglas Gregor27381f32009-11-23 12:27:39 +00006029 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006030 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006031
Douglas Gregora1f013e2008-11-07 22:36:19 +00006032 // Add this candidate
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006033 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCalla0296f72010-03-19 07:35:19 +00006034 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006035 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006036 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006037 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006038 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00006039 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00006040 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00006041 Candidate.Viable = true;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006042 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006043
Douglas Gregor6affc782010-08-19 15:37:02 +00006044 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006045 // For conversion functions, the function is considered to be a member of
6046 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00006047 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006048 //
6049 // Determine the implicit conversion sequence for the implicit
6050 // object parameter.
6051 QualType ImplicitParamType = From->getType();
6052 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
6053 ImplicitParamType = FromPtrType->getPointeeType();
6054 CXXRecordDecl *ConversionContext
6055 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006056
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006057 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006058 = TryObjectArgumentInitialization(*this, From->getType(),
6059 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00006060 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006061
John McCall0d1da222010-01-12 00:44:57 +00006062 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006063 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006064 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006065 return;
6066 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00006067
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006068 // We won't go through a user-defined type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006069 // derived to base as such conversions are given Conversion Rank. They only
6070 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
6071 QualType FromCanon
6072 = Context.getCanonicalType(From->getType().getUnqualifiedType());
6073 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
6074 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
6075 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006076 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00006077 return;
6078 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006079
Douglas Gregora1f013e2008-11-07 22:36:19 +00006080 // To determine what the conversion from the result of calling the
6081 // conversion function to the type we're eventually trying to
6082 // convert to (ToType), we need to synthesize a call to the
6083 // conversion function and attempt copy initialization from it. This
6084 // makes sure that we get the right semantics with respect to
6085 // lvalues/rvalues and the type. Fortunately, we can allocate this
6086 // call on the stack and we don't need its arguments to be
6087 // well-formed.
John McCall113bee02012-03-10 09:33:50 +00006088 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00006089 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00006090 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
6091 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00006092 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00006093 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00006094
Richard Smith48d24642011-07-13 22:53:21 +00006095 QualType ConversionType = Conversion->getConversionType();
6096 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00006097 Candidate.Viable = false;
6098 Candidate.FailureKind = ovl_fail_bad_final_conversion;
6099 return;
6100 }
6101
Richard Smith48d24642011-07-13 22:53:21 +00006102 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00006103
Mike Stump11289f42009-09-09 15:08:12 +00006104 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00006105 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
6106 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00006107 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko78852e92013-05-05 20:40:26 +00006108 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00006109 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00006110 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006111 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006112 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00006113 /*InOverloadResolution=*/false,
6114 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00006115
John McCall0d1da222010-01-12 00:44:57 +00006116 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00006117 case ImplicitConversionSequence::StandardConversion:
6118 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006119
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006120 // C++ [over.ics.user]p3:
6121 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006122 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006123 // shall have exact match rank.
6124 if (Conversion->getPrimaryTemplate() &&
6125 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
6126 Candidate.Viable = false;
6127 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006128 return;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006129 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006130
Douglas Gregorcba72b12011-01-21 05:18:22 +00006131 // C++0x [dcl.init.ref]p5:
6132 // In the second case, if the reference is an rvalue reference and
6133 // the second standard conversion sequence of the user-defined
6134 // conversion sequence includes an lvalue-to-rvalue conversion, the
6135 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006136 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00006137 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
6138 Candidate.Viable = false;
6139 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006140 return;
Douglas Gregorcba72b12011-01-21 05:18:22 +00006141 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006142 break;
6143
6144 case ImplicitConversionSequence::BadConversion:
6145 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00006146 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006147 return;
Douglas Gregora1f013e2008-11-07 22:36:19 +00006148
6149 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006150 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00006151 "Can only end up with a standard conversion sequence or failure");
6152 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006153
6154 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6155 Candidate.Viable = false;
6156 Candidate.FailureKind = ovl_fail_enable_if;
6157 Candidate.DeductionFailure.Data = FailedAttr;
6158 return;
6159 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00006160}
6161
Douglas Gregor05155d82009-08-21 23:19:43 +00006162/// \brief Adds a conversion function template specialization
6163/// candidate to the overload set, using template argument deduction
6164/// to deduce the template arguments of the conversion function
6165/// template from the type that we are converting to (C++
6166/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00006167void
Douglas Gregor05155d82009-08-21 23:19:43 +00006168Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00006169 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006170 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00006171 Expr *From, QualType ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006172 OverloadCandidateSet &CandidateSet,
6173 bool AllowObjCConversionOnExplicit) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006174 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
6175 "Only conversion function templates permitted here");
6176
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006177 if (!CandidateSet.isNewCandidate(FunctionTemplate))
6178 return;
6179
Craig Toppere6706e42012-09-19 02:26:47 +00006180 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00006181 CXXConversionDecl *Specialization = 0;
6182 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00006183 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00006184 Specialization, Info)) {
Benjamin Kramerfb761ff2012-01-14 16:31:55 +00006185 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006186 Candidate.FoundDecl = FoundDecl;
6187 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6188 Candidate.Viable = false;
6189 Candidate.FailureKind = ovl_fail_bad_deduction;
6190 Candidate.IsSurrogate = false;
6191 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00006192 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006193 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00006194 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00006195 return;
6196 }
Mike Stump11289f42009-09-09 15:08:12 +00006197
Douglas Gregor05155d82009-08-21 23:19:43 +00006198 // Add the conversion function template specialization produced by
6199 // template argument deduction as a candidate.
6200 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00006201 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
Douglas Gregor4b60a152013-11-07 22:34:54 +00006202 CandidateSet, AllowObjCConversionOnExplicit);
Douglas Gregor05155d82009-08-21 23:19:43 +00006203}
6204
Douglas Gregorab7897a2008-11-19 22:57:39 +00006205/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6206/// converts the given @c Object to a function pointer via the
6207/// conversion function @c Conversion, and then attempts to call it
6208/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6209/// the type of function that we'll eventually be calling.
6210void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00006211 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00006212 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00006213 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00006214 Expr *Object,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006215 ArrayRef<Expr *> Args,
Douglas Gregorab7897a2008-11-19 22:57:39 +00006216 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00006217 if (!CandidateSet.isNewCandidate(Conversion))
6218 return;
6219
Douglas Gregor27381f32009-11-23 12:27:39 +00006220 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006221 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006222
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006223 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCalla0296f72010-03-19 07:35:19 +00006224 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006225 Candidate.Function = 0;
6226 Candidate.Surrogate = Conversion;
6227 Candidate.Viable = true;
6228 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006229 Candidate.IgnoreObjectArgument = false;
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006230 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006231
6232 // Determine the implicit conversion sequence for the implicit
6233 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00006234 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006235 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00006236 Object->Classify(Context),
6237 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00006238 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006239 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006240 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00006241 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006242 return;
6243 }
6244
6245 // The first conversion is actually a user-defined conversion whose
6246 // first conversion is ObjectInit's standard conversion (which is
6247 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00006248 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006249 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00006250 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00006251 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006252 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00006253 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00006254 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00006255 = Candidate.Conversions[0].UserDefined.Before;
6256 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6257
Mike Stump11289f42009-09-09 15:08:12 +00006258 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00006259 unsigned NumArgsInProto = Proto->getNumArgs();
6260
6261 // (C++ 13.3.2p2): A candidate function having fewer than m
6262 // parameters is viable only if it has an ellipsis in its parameter
6263 // list (8.3.5).
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006264 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006265 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006266 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006267 return;
6268 }
6269
6270 // Function types don't have any default arguments, so just check if
6271 // we have enough arguments.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00006272 if (Args.size() < NumArgsInProto) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006273 // Not enough arguments.
6274 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006275 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006276 return;
6277 }
6278
6279 // Determine the implicit conversion sequences for each of the
6280 // arguments.
Richard Smithe54c3072013-05-05 15:51:06 +00006281 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006282 if (ArgIdx < NumArgsInProto) {
6283 // (C++ 13.3.2p3): for F to be a viable function, there shall
6284 // exist for each argument an implicit conversion sequence
6285 // (13.3.3.1) that converts that argument to the corresponding
6286 // parameter of F.
6287 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00006288 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006289 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00006290 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00006291 /*InOverloadResolution=*/false,
6292 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006293 getLangOpts().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00006294 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00006295 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006296 Candidate.FailureKind = ovl_fail_bad_conversion;
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006297 return;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006298 }
6299 } else {
6300 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6301 // argument for which there is no corresponding parameter is
6302 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00006303 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006304 }
6305 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006306
6307 if (EnableIfAttr *FailedAttr = CheckEnableIf(Conversion, ArrayRef<Expr*>())) {
6308 Candidate.Viable = false;
6309 Candidate.FailureKind = ovl_fail_enable_if;
6310 Candidate.DeductionFailure.Data = FailedAttr;
6311 return;
6312 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00006313}
6314
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006315/// \brief Add overload candidates for overloaded operators that are
6316/// member functions.
6317///
6318/// Add the overloaded operator candidates that are member functions
6319/// for the operator Op that was used in an operator expression such
6320/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6321/// CandidateSet will store the added overload candidates. (C++
6322/// [over.match.oper]).
6323void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6324 SourceLocation OpLoc,
Richard Smithe54c3072013-05-05 15:51:06 +00006325 ArrayRef<Expr *> Args,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006326 OverloadCandidateSet& CandidateSet,
6327 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00006328 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6329
6330 // C++ [over.match.oper]p3:
6331 // For a unary operator @ with an operand of a type whose
6332 // cv-unqualified version is T1, and for a binary operator @ with
6333 // a left operand of a type whose cv-unqualified version is T1 and
6334 // a right operand of a type whose cv-unqualified version is T2,
6335 // three sets of candidate functions, designated member
6336 // candidates, non-member candidates and built-in candidates, are
6337 // constructed as follows:
6338 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00006339
Richard Smith0feaf0c2013-04-20 12:41:22 +00006340 // -- If T1 is a complete class type or a class currently being
6341 // defined, the set of member candidates is the result of the
6342 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6343 // the set of member candidates is empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006344 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smith0feaf0c2013-04-20 12:41:22 +00006345 // Complete the type if it can be completed.
6346 RequireCompleteType(OpLoc, T1, 0);
6347 // If the type is neither complete nor being defined, bail out now.
6348 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006349 return;
Mike Stump11289f42009-09-09 15:08:12 +00006350
John McCall27b18f82009-11-17 02:14:36 +00006351 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6352 LookupQualifiedName(Operators, T1Rec->getDecl());
6353 Operators.suppressDiagnostics();
6354
Mike Stump11289f42009-09-09 15:08:12 +00006355 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00006356 OperEnd = Operators.end();
6357 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00006358 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00006359 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola51629df2013-04-29 19:29:25 +00006360 Args[0]->Classify(Context),
Richard Smithe54c3072013-05-05 15:51:06 +00006361 Args.slice(1),
Douglas Gregor02824322011-01-26 19:30:28 +00006362 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006363 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00006364 }
Douglas Gregor436424c2008-11-18 23:14:02 +00006365}
6366
Douglas Gregora11693b2008-11-12 17:17:38 +00006367/// AddBuiltinCandidate - Add a candidate for a built-in
6368/// operator. ResultTy and ParamTys are the result and parameter types
6369/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00006370/// arguments being passed to the candidate. IsAssignmentOperator
6371/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00006372/// operator. NumContextualBoolArguments is the number of arguments
6373/// (at the beginning of the argument list) that will be contextually
6374/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00006375void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smithe54c3072013-05-05 15:51:06 +00006376 ArrayRef<Expr *> Args,
Douglas Gregorc5e61072009-01-13 00:52:54 +00006377 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006378 bool IsAssignmentOperator,
6379 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00006380 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00006381 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00006382
Douglas Gregora11693b2008-11-12 17:17:38 +00006383 // Add this candidate
Richard Smithe54c3072013-05-05 15:51:06 +00006384 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCalla0296f72010-03-19 07:35:19 +00006385 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00006386 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00006387 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006388 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00006389 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smithe54c3072013-05-05 15:51:06 +00006390 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregora11693b2008-11-12 17:17:38 +00006391 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6392
6393 // Determine the implicit conversion sequences for each of the
6394 // arguments.
6395 Candidate.Viable = true;
Richard Smithe54c3072013-05-05 15:51:06 +00006396 Candidate.ExplicitCallArguments = Args.size();
6397 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00006398 // C++ [over.match.oper]p4:
6399 // For the built-in assignment operators, conversions of the
6400 // left operand are restricted as follows:
6401 // -- no temporaries are introduced to hold the left operand, and
6402 // -- no user-defined conversions are applied to the left
6403 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00006404 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00006405 //
6406 // We block these conversions by turning off user-defined
6407 // conversions, since that is the only way that initialization of
6408 // a reference to a non-class type can occur from something that
6409 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006410 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00006411 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00006412 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00006413 Candidate.Conversions[ArgIdx]
6414 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006415 } else {
Mike Stump11289f42009-09-09 15:08:12 +00006416 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006417 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00006418 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00006419 /*InOverloadResolution=*/false,
6420 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00006421 getLangOpts().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00006422 }
John McCall0d1da222010-01-12 00:44:57 +00006423 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006424 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00006425 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00006426 break;
6427 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006428 }
6429}
6430
Craig Toppercd7b0332013-07-01 06:29:40 +00006431namespace {
6432
Douglas Gregora11693b2008-11-12 17:17:38 +00006433/// BuiltinCandidateTypeSet - A set of types that will be used for the
6434/// candidate operator functions for built-in operators (C++
6435/// [over.built]). The types are separated into pointer types and
6436/// enumeration types.
6437class BuiltinCandidateTypeSet {
6438 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006439 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00006440
6441 /// PointerTypes - The set of pointer types that will be used in the
6442 /// built-in candidates.
6443 TypeSet PointerTypes;
6444
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006445 /// MemberPointerTypes - The set of member pointer types that will be
6446 /// used in the built-in candidates.
6447 TypeSet MemberPointerTypes;
6448
Douglas Gregora11693b2008-11-12 17:17:38 +00006449 /// EnumerationTypes - The set of enumeration types that will be
6450 /// used in the built-in candidates.
6451 TypeSet EnumerationTypes;
6452
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006454 /// candidates.
6455 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00006456
6457 /// \brief A flag indicating non-record types are viable candidates
6458 bool HasNonRecordTypes;
6459
6460 /// \brief A flag indicating whether either arithmetic or enumeration types
6461 /// were present in the candidate set.
6462 bool HasArithmeticOrEnumeralTypes;
6463
Douglas Gregor80af3132011-05-21 23:15:46 +00006464 /// \brief A flag indicating whether the nullptr type was present in the
6465 /// candidate set.
6466 bool HasNullPtrType;
6467
Douglas Gregor8a2e6012009-08-24 15:23:48 +00006468 /// Sema - The semantic analysis instance where we are building the
6469 /// candidate type set.
6470 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00006471
Douglas Gregora11693b2008-11-12 17:17:38 +00006472 /// Context - The AST context in which we will build the type sets.
6473 ASTContext &Context;
6474
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006475 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6476 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006477 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00006478
6479public:
6480 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006481 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00006482
Mike Stump11289f42009-09-09 15:08:12 +00006483 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00006484 : HasNonRecordTypes(false),
6485 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00006486 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00006487 SemaRef(SemaRef),
6488 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00006489
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006490 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006491 SourceLocation Loc,
6492 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006493 bool AllowExplicitConversions,
6494 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006495
6496 /// pointer_begin - First pointer type found;
6497 iterator pointer_begin() { return PointerTypes.begin(); }
6498
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006499 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006500 iterator pointer_end() { return PointerTypes.end(); }
6501
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006502 /// member_pointer_begin - First member pointer type found;
6503 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6504
6505 /// member_pointer_end - Past the last member pointer type found;
6506 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6507
Douglas Gregora11693b2008-11-12 17:17:38 +00006508 /// enumeration_begin - First enumeration type found;
6509 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6510
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006511 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00006512 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006513
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006514 iterator vector_begin() { return VectorTypes.begin(); }
6515 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00006516
6517 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6518 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00006519 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00006520};
6521
Craig Toppercd7b0332013-07-01 06:29:40 +00006522} // end anonymous namespace
6523
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006524/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00006525/// the set of pointer types along with any more-qualified variants of
6526/// that type. For example, if @p Ty is "int const *", this routine
6527/// will add "int const *", "int const volatile *", "int const
6528/// restrict *", and "int const volatile restrict *" to the set of
6529/// pointer types. Returns true if the add of @p Ty itself succeeded,
6530/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006531///
6532/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006533bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006534BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6535 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00006536
Douglas Gregora11693b2008-11-12 17:17:38 +00006537 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00006538 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00006539 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006540
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006541 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00006542 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006543 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006544 if (!PointerTy) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006545 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6546 PointeeTy = PTy->getPointeeType();
6547 buildObjCPtr = true;
6548 } else {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006549 PointeeTy = PointerTy->getPointeeType();
Douglas Gregor5bee2582012-06-04 00:15:09 +00006550 }
6551
Sebastian Redl4990a632009-11-18 20:39:26 +00006552 // Don't add qualified variants of arrays. For one, they're not allowed
6553 // (the qualifier would sink to the element type), and for another, the
6554 // only overload situation where it matters is subscript or pointer +- int,
6555 // and those shouldn't have qualifier variants anyway.
6556 if (PointeeTy->isArrayType())
6557 return true;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006558
John McCall8ccfcb52009-09-24 19:53:00 +00006559 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006560 bool hasVolatile = VisibleQuals.hasVolatile();
6561 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006562
John McCall8ccfcb52009-09-24 19:53:00 +00006563 // Iterate through all strict supersets of BaseCVR.
6564 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6565 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006566 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006567 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregor5bee2582012-06-04 00:15:09 +00006568
6569 // Skip over restrict if no restrict found anywhere in the types, or if
6570 // the type cannot be restrict-qualified.
6571 if ((CVR & Qualifiers::Restrict) &&
6572 (!hasRestrict ||
6573 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6574 continue;
6575
6576 // Build qualified pointee type.
John McCall8ccfcb52009-09-24 19:53:00 +00006577 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006578
6579 // Build qualified pointer type.
6580 QualType QPointerTy;
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006581 if (!buildObjCPtr)
Douglas Gregor5bee2582012-06-04 00:15:09 +00006582 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00006583 else
Douglas Gregor5bee2582012-06-04 00:15:09 +00006584 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6585
6586 // Insert qualified pointer type.
6587 PointerTypes.insert(QPointerTy);
Douglas Gregora11693b2008-11-12 17:17:38 +00006588 }
6589
6590 return true;
6591}
6592
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006593/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6594/// to the set of pointer types along with any more-qualified variants of
6595/// that type. For example, if @p Ty is "int const *", this routine
6596/// will add "int const *", "int const volatile *", "int const
6597/// restrict *", and "int const volatile restrict *" to the set of
6598/// pointer types. Returns true if the add of @p Ty itself succeeded,
6599/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00006600///
6601/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006602bool
6603BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6604 QualType Ty) {
6605 // Insert this type.
6606 if (!MemberPointerTypes.insert(Ty))
6607 return false;
6608
John McCall8ccfcb52009-09-24 19:53:00 +00006609 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6610 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006611
John McCall8ccfcb52009-09-24 19:53:00 +00006612 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00006613 // Don't add qualified variants of arrays. For one, they're not allowed
6614 // (the qualifier would sink to the element type), and for another, the
6615 // only overload situation where it matters is subscript or pointer +- int,
6616 // and those shouldn't have qualifier variants anyway.
6617 if (PointeeTy->isArrayType())
6618 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00006619 const Type *ClassTy = PointerTy->getClass();
6620
6621 // Iterate through all strict supersets of the pointee type's CVR
6622 // qualifiers.
6623 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6624 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6625 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006626
John McCall8ccfcb52009-09-24 19:53:00 +00006627 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006628 MemberPointerTypes.insert(
6629 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006630 }
6631
6632 return true;
6633}
6634
Douglas Gregora11693b2008-11-12 17:17:38 +00006635/// AddTypesConvertedFrom - Add each of the types to which the type @p
6636/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006637/// primarily interested in pointer types and enumeration types. We also
6638/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00006639/// AllowUserConversions is true if we should look at the conversion
6640/// functions of a class type, and AllowExplicitConversions if we
6641/// should also include the explicit conversion functions of a class
6642/// type.
Mike Stump11289f42009-09-09 15:08:12 +00006643void
Douglas Gregor5fb53972009-01-14 15:45:31 +00006644BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006645 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00006646 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006647 bool AllowExplicitConversions,
6648 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006649 // Only deal with canonical types.
6650 Ty = Context.getCanonicalType(Ty);
6651
6652 // Look through reference types; they aren't part of the type of an
6653 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006654 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00006655 Ty = RefTy->getPointeeType();
6656
John McCall33ddac02011-01-19 10:06:00 +00006657 // If we're dealing with an array type, decay to the pointer.
6658 if (Ty->isArrayType())
6659 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6660
6661 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00006662 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00006663
Chandler Carruth00a38332010-12-13 01:44:01 +00006664 // Flag if we ever add a non-record type.
6665 const RecordType *TyRec = Ty->getAs<RecordType>();
6666 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6667
Chandler Carruth00a38332010-12-13 01:44:01 +00006668 // Flag if we encounter an arithmetic type.
6669 HasArithmeticOrEnumeralTypes =
6670 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6671
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00006672 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6673 PointerTypes.insert(Ty);
6674 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006675 // Insert our type, and its more-qualified variants, into the set
6676 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006677 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00006678 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00006679 } else if (Ty->isMemberPointerType()) {
6680 // Member pointers are far easier, since the pointee can't be converted.
6681 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6682 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00006683 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006684 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00006685 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006686 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006687 // We treat vector types as arithmetic types in many contexts as an
6688 // extension.
6689 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006690 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00006691 } else if (Ty->isNullPtrType()) {
6692 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00006693 } else if (AllowUserConversions && TyRec) {
6694 // No conversion functions in incomplete types.
6695 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6696 return;
Mike Stump11289f42009-09-09 15:08:12 +00006697
Chandler Carruth00a38332010-12-13 01:44:01 +00006698 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006699 std::pair<CXXRecordDecl::conversion_iterator,
6700 CXXRecordDecl::conversion_iterator>
6701 Conversions = ClassDecl->getVisibleConversionFunctions();
6702 for (CXXRecordDecl::conversion_iterator
6703 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006704 NamedDecl *D = I.getDecl();
6705 if (isa<UsingShadowDecl>(D))
6706 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00006707
Chandler Carruth00a38332010-12-13 01:44:01 +00006708 // Skip conversion function templates; they don't tell us anything
6709 // about which builtin types we can convert to.
6710 if (isa<FunctionTemplateDecl>(D))
6711 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006712
Chandler Carruth00a38332010-12-13 01:44:01 +00006713 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6714 if (AllowExplicitConversions || !Conv->isExplicit()) {
6715 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6716 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00006717 }
6718 }
6719 }
6720}
6721
Douglas Gregor84605ae2009-08-24 13:43:27 +00006722/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6723/// the volatile- and non-volatile-qualified assignment operators for the
6724/// given type to the candidate set.
6725static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6726 QualType T,
Richard Smithe54c3072013-05-05 15:51:06 +00006727 ArrayRef<Expr *> Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006728 OverloadCandidateSet &CandidateSet) {
6729 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00006730
Douglas Gregor84605ae2009-08-24 13:43:27 +00006731 // T& operator=(T&, T)
6732 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6733 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006734 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor84605ae2009-08-24 13:43:27 +00006735 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00006736
Douglas Gregor84605ae2009-08-24 13:43:27 +00006737 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6738 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00006739 ParamTypes[0]
6740 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00006741 ParamTypes[1] = T;
Richard Smithe54c3072013-05-05 15:51:06 +00006742 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00006743 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00006744 }
6745}
Mike Stump11289f42009-09-09 15:08:12 +00006746
Sebastian Redl1054fae2009-10-25 17:03:50 +00006747/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6748/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006749static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6750 Qualifiers VRQuals;
6751 const RecordType *TyRec;
6752 if (const MemberPointerType *RHSMPType =
6753 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00006754 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006755 else
6756 TyRec = ArgExpr->getType()->getAs<RecordType>();
6757 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00006758 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006759 VRQuals.addVolatile();
6760 VRQuals.addRestrict();
6761 return VRQuals;
6762 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006763
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006764 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00006765 if (!ClassDecl->hasDefinition())
6766 return VRQuals;
6767
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006768 std::pair<CXXRecordDecl::conversion_iterator,
6769 CXXRecordDecl::conversion_iterator>
6770 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006771
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00006772 for (CXXRecordDecl::conversion_iterator
6773 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00006774 NamedDecl *D = I.getDecl();
6775 if (isa<UsingShadowDecl>(D))
6776 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6777 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006778 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6779 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6780 CanTy = ResTypeRef->getPointeeType();
6781 // Need to go down the pointer/mempointer chain and add qualifiers
6782 // as see them.
6783 bool done = false;
6784 while (!done) {
Douglas Gregor5bee2582012-06-04 00:15:09 +00006785 if (CanTy.isRestrictQualified())
6786 VRQuals.addRestrict();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006787 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6788 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006789 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006790 CanTy->getAs<MemberPointerType>())
6791 CanTy = ResTypeMPtr->getPointeeType();
6792 else
6793 done = true;
6794 if (CanTy.isVolatileQualified())
6795 VRQuals.addVolatile();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006796 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6797 return VRQuals;
6798 }
6799 }
6800 }
6801 return VRQuals;
6802}
John McCall52872982010-11-13 05:51:15 +00006803
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006804namespace {
John McCall52872982010-11-13 05:51:15 +00006805
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006806/// \brief Helper class to manage the addition of builtin operator overload
6807/// candidates. It provides shared state and utility methods used throughout
6808/// the process, as well as a helper method to add each group of builtin
6809/// operator overloads from the standard to a candidate set.
6810class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006811 // Common instance state available to all overload candidate addition methods.
6812 Sema &S;
Richard Smithe54c3072013-05-05 15:51:06 +00006813 ArrayRef<Expr *> Args;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006814 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00006815 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006816 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00006817 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006818
Chandler Carruthc6586e52010-12-12 10:35:00 +00006819 // Define some constants used to index and iterate over the arithemetic types
6820 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00006821 // The "promoted arithmetic types" are the arithmetic
6822 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00006823 static const unsigned FirstIntegralType = 3;
Richard Smith521ecc12012-06-10 08:00:26 +00006824 static const unsigned LastIntegralType = 20;
John McCall52872982010-11-13 05:51:15 +00006825 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith521ecc12012-06-10 08:00:26 +00006826 LastPromotedIntegralType = 11;
John McCall52872982010-11-13 05:51:15 +00006827 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith521ecc12012-06-10 08:00:26 +00006828 LastPromotedArithmeticType = 11;
6829 static const unsigned NumArithmeticTypes = 20;
John McCall52872982010-11-13 05:51:15 +00006830
Chandler Carruthc6586e52010-12-12 10:35:00 +00006831 /// \brief Get the canonical type for a given arithmetic type index.
6832 CanQualType getArithmeticType(unsigned index) {
6833 assert(index < NumArithmeticTypes);
6834 static CanQualType ASTContext::* const
6835 ArithmeticTypes[NumArithmeticTypes] = {
6836 // Start of promoted types.
6837 &ASTContext::FloatTy,
6838 &ASTContext::DoubleTy,
6839 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00006840
Chandler Carruthc6586e52010-12-12 10:35:00 +00006841 // Start of integral types.
6842 &ASTContext::IntTy,
6843 &ASTContext::LongTy,
6844 &ASTContext::LongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006845 &ASTContext::Int128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006846 &ASTContext::UnsignedIntTy,
6847 &ASTContext::UnsignedLongTy,
6848 &ASTContext::UnsignedLongLongTy,
Richard Smith521ecc12012-06-10 08:00:26 +00006849 &ASTContext::UnsignedInt128Ty,
Chandler Carruthc6586e52010-12-12 10:35:00 +00006850 // End of promoted types.
6851
6852 &ASTContext::BoolTy,
6853 &ASTContext::CharTy,
6854 &ASTContext::WCharTy,
6855 &ASTContext::Char16Ty,
6856 &ASTContext::Char32Ty,
6857 &ASTContext::SignedCharTy,
6858 &ASTContext::ShortTy,
6859 &ASTContext::UnsignedCharTy,
6860 &ASTContext::UnsignedShortTy,
6861 // End of integral types.
Richard Smith521ecc12012-06-10 08:00:26 +00006862 // FIXME: What about complex? What about half?
Chandler Carruthc6586e52010-12-12 10:35:00 +00006863 };
6864 return S.Context.*ArithmeticTypes[index];
6865 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006866
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006867 /// \brief Gets the canonical type resulting from the usual arithemetic
6868 /// converions for the given arithmetic types.
6869 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6870 // Accelerator table for performing the usual arithmetic conversions.
6871 // The rules are basically:
6872 // - if either is floating-point, use the wider floating-point
6873 // - if same signedness, use the higher rank
6874 // - if same size, use unsigned of the higher rank
6875 // - use the larger type
6876 // These rules, together with the axiom that higher ranks are
6877 // never smaller, are sufficient to precompute all of these results
6878 // *except* when dealing with signed types of higher rank.
6879 // (we could precompute SLL x UI for all known platforms, but it's
6880 // better not to make any assumptions).
Richard Smith521ecc12012-06-10 08:00:26 +00006881 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006882 enum PromotedType {
Richard Smith521ecc12012-06-10 08:00:26 +00006883 Dep=-1,
6884 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006885 };
Nuno Lopes9af6b032012-04-21 14:45:25 +00006886 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006887 [LastPromotedArithmeticType] = {
Richard Smith521ecc12012-06-10 08:00:26 +00006888/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6889/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6890/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6891/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6892/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6893/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6894/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6895/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6896/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6897/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6898/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006899 };
6900
6901 assert(L < LastPromotedArithmeticType);
6902 assert(R < LastPromotedArithmeticType);
6903 int Idx = ConversionsTable[L][R];
6904
6905 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006906 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006907
6908 // Slow path: we need to compare widths.
6909 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006910 CanQualType LT = getArithmeticType(L),
6911 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006912 unsigned LW = S.Context.getIntWidth(LT),
6913 RW = S.Context.getIntWidth(RT);
6914
6915 // If they're different widths, use the signed type.
6916 if (LW > RW) return LT;
6917 else if (LW < RW) return RT;
6918
6919 // Otherwise, use the unsigned type of the signed type's rank.
6920 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6921 assert(L == SLL || R == SLL);
6922 return S.Context.UnsignedLongLongTy;
6923 }
6924
Chandler Carruth5659c0c2010-12-12 09:22:45 +00006925 /// \brief Helper method to factor out the common pattern of adding overloads
6926 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006927 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregor5bee2582012-06-04 00:15:09 +00006928 bool HasVolatile,
6929 bool HasRestrict) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006930 QualType ParamTypes[2] = {
6931 S.Context.getLValueReferenceType(CandidateTy),
6932 S.Context.IntTy
6933 };
6934
6935 // Non-volatile version.
Richard Smithe54c3072013-05-05 15:51:06 +00006936 if (Args.size() == 1)
6937 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006938 else
Richard Smithe54c3072013-05-05 15:51:06 +00006939 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006940
6941 // Use a heuristic to reduce number of builtin candidates in the set:
6942 // add volatile version only if there are conversions to a volatile type.
6943 if (HasVolatile) {
6944 ParamTypes[0] =
6945 S.Context.getLValueReferenceType(
6946 S.Context.getVolatileType(CandidateTy));
Richard Smithe54c3072013-05-05 15:51:06 +00006947 if (Args.size() == 1)
6948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006949 else
Richard Smithe54c3072013-05-05 15:51:06 +00006950 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006951 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00006952
6953 // Add restrict version only if there are conversions to a restrict type
6954 // and our candidate type is a non-restrict-qualified pointer.
6955 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6956 !CandidateTy.isRestrictQualified()) {
6957 ParamTypes[0]
6958 = S.Context.getLValueReferenceType(
6959 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smithe54c3072013-05-05 15:51:06 +00006960 if (Args.size() == 1)
6961 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006962 else
Richard Smithe54c3072013-05-05 15:51:06 +00006963 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006964
6965 if (HasVolatile) {
6966 ParamTypes[0]
6967 = S.Context.getLValueReferenceType(
6968 S.Context.getCVRQualifiedType(CandidateTy,
6969 (Qualifiers::Volatile |
6970 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00006971 if (Args.size() == 1)
6972 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006973 else
Richard Smithe54c3072013-05-05 15:51:06 +00006974 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregor5bee2582012-06-04 00:15:09 +00006975 }
6976 }
6977
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006978 }
6979
6980public:
6981 BuiltinOperatorOverloadBuilder(
Richard Smithe54c3072013-05-05 15:51:06 +00006982 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006983 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006984 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006985 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006986 OverloadCandidateSet &CandidateSet)
Richard Smithe54c3072013-05-05 15:51:06 +00006987 : S(S), Args(Args),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006988 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00006989 HasArithmeticOrEnumeralCandidateType(
6990 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006991 CandidateTypes(CandidateTypes),
6992 CandidateSet(CandidateSet) {
6993 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00006994 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006995 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006996 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00006997 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006998 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00006999 assert(getArithmeticType(FirstPromotedArithmeticType)
7000 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007001 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00007002 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith521ecc12012-06-10 08:00:26 +00007003 == S.Context.UnsignedInt128Ty &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007004 "Invalid last promoted arithmetic type");
7005 }
7006
7007 // C++ [over.built]p3:
7008 //
7009 // For every pair (T, VQ), where T is an arithmetic type, and VQ
7010 // is either volatile or empty, there exist candidate operator
7011 // functions of the form
7012 //
7013 // VQ T& operator++(VQ T&);
7014 // T operator++(VQ T&, int);
7015 //
7016 // C++ [over.built]p4:
7017 //
7018 // For every pair (T, VQ), where T is an arithmetic type other
7019 // than bool, and VQ is either volatile or empty, there exist
7020 // candidate operator functions of the form
7021 //
7022 // VQ T& operator--(VQ T&);
7023 // T operator--(VQ T&, int);
7024 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007025 if (!HasArithmeticOrEnumeralCandidateType)
7026 return;
7027
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007028 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
7029 Arith < NumArithmeticTypes; ++Arith) {
7030 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00007031 getArithmeticType(Arith),
Douglas Gregor5bee2582012-06-04 00:15:09 +00007032 VisibleTypeConversionsQuals.hasVolatile(),
7033 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007034 }
7035 }
7036
7037 // C++ [over.built]p5:
7038 //
7039 // For every pair (T, VQ), where T is a cv-qualified or
7040 // cv-unqualified object type, and VQ is either volatile or
7041 // empty, there exist candidate operator functions of the form
7042 //
7043 // T*VQ& operator++(T*VQ&);
7044 // T*VQ& operator--(T*VQ&);
7045 // T* operator++(T*VQ&, int);
7046 // T* operator--(T*VQ&, int);
7047 void addPlusPlusMinusMinusPointerOverloads() {
7048 for (BuiltinCandidateTypeSet::iterator
7049 Ptr = CandidateTypes[0].pointer_begin(),
7050 PtrEnd = CandidateTypes[0].pointer_end();
7051 Ptr != PtrEnd; ++Ptr) {
7052 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00007053 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007054 continue;
7055
7056 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007057 (!(*Ptr).isVolatileQualified() &&
7058 VisibleTypeConversionsQuals.hasVolatile()),
7059 (!(*Ptr).isRestrictQualified() &&
7060 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007061 }
7062 }
7063
7064 // C++ [over.built]p6:
7065 // For every cv-qualified or cv-unqualified object type T, there
7066 // exist candidate operator functions of the form
7067 //
7068 // T& operator*(T*);
7069 //
7070 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007071 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00007072 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007073 // T& operator*(T*);
7074 void addUnaryStarPointerOverloads() {
7075 for (BuiltinCandidateTypeSet::iterator
7076 Ptr = CandidateTypes[0].pointer_begin(),
7077 PtrEnd = CandidateTypes[0].pointer_end();
7078 Ptr != PtrEnd; ++Ptr) {
7079 QualType ParamTy = *Ptr;
7080 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007081 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
7082 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007083
Douglas Gregor02824322011-01-26 19:30:28 +00007084 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
7085 if (Proto->getTypeQuals() || Proto->getRefQualifier())
7086 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007087
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007088 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smithe54c3072013-05-05 15:51:06 +00007089 &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007090 }
7091 }
7092
7093 // C++ [over.built]p9:
7094 // For every promoted arithmetic type T, there exist candidate
7095 // operator functions of the form
7096 //
7097 // T operator+(T);
7098 // T operator-(T);
7099 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007100 if (!HasArithmeticOrEnumeralCandidateType)
7101 return;
7102
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007103 for (unsigned Arith = FirstPromotedArithmeticType;
7104 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007105 QualType ArithTy = getArithmeticType(Arith);
Richard Smithe54c3072013-05-05 15:51:06 +00007106 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007107 }
7108
7109 // Extension: We also add these operators for vector types.
7110 for (BuiltinCandidateTypeSet::iterator
7111 Vec = CandidateTypes[0].vector_begin(),
7112 VecEnd = CandidateTypes[0].vector_end();
7113 Vec != VecEnd; ++Vec) {
7114 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007115 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007116 }
7117 }
7118
7119 // C++ [over.built]p8:
7120 // For every type T, there exist candidate operator functions of
7121 // the form
7122 //
7123 // T* operator+(T*);
7124 void addUnaryPlusPointerOverloads() {
7125 for (BuiltinCandidateTypeSet::iterator
7126 Ptr = CandidateTypes[0].pointer_begin(),
7127 PtrEnd = CandidateTypes[0].pointer_end();
7128 Ptr != PtrEnd; ++Ptr) {
7129 QualType ParamTy = *Ptr;
Richard Smithe54c3072013-05-05 15:51:06 +00007130 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007131 }
7132 }
7133
7134 // C++ [over.built]p10:
7135 // For every promoted integral type T, there exist candidate
7136 // operator functions of the form
7137 //
7138 // T operator~(T);
7139 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007140 if (!HasArithmeticOrEnumeralCandidateType)
7141 return;
7142
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007143 for (unsigned Int = FirstPromotedIntegralType;
7144 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007145 QualType IntTy = getArithmeticType(Int);
Richard Smithe54c3072013-05-05 15:51:06 +00007146 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007147 }
7148
7149 // Extension: We also add this operator for vector types.
7150 for (BuiltinCandidateTypeSet::iterator
7151 Vec = CandidateTypes[0].vector_begin(),
7152 VecEnd = CandidateTypes[0].vector_end();
7153 Vec != VecEnd; ++Vec) {
7154 QualType VecTy = *Vec;
Richard Smithe54c3072013-05-05 15:51:06 +00007155 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007156 }
7157 }
7158
7159 // C++ [over.match.oper]p16:
7160 // For every pointer to member type T, there exist candidate operator
7161 // functions of the form
7162 //
7163 // bool operator==(T,T);
7164 // bool operator!=(T,T);
7165 void addEqualEqualOrNotEqualMemberPointerOverloads() {
7166 /// Set of (canonical) types that we've already handled.
7167 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7168
Richard Smithe54c3072013-05-05 15:51:06 +00007169 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007170 for (BuiltinCandidateTypeSet::iterator
7171 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7172 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7173 MemPtr != MemPtrEnd;
7174 ++MemPtr) {
7175 // Don't add the same builtin candidate twice.
7176 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7177 continue;
7178
7179 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007180 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007181 }
7182 }
7183 }
7184
7185 // C++ [over.built]p15:
7186 //
Douglas Gregor80af3132011-05-21 23:15:46 +00007187 // For every T, where T is an enumeration type, a pointer type, or
7188 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007189 //
7190 // bool operator<(T, T);
7191 // bool operator>(T, T);
7192 // bool operator<=(T, T);
7193 // bool operator>=(T, T);
7194 // bool operator==(T, T);
7195 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007196 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman14f082b2012-09-18 21:52:24 +00007197 // C++ [over.match.oper]p3:
7198 // [...]the built-in candidates include all of the candidate operator
7199 // functions defined in 13.6 that, compared to the given operator, [...]
7200 // do not have the same parameter-type-list as any non-template non-member
7201 // candidate.
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007202 //
Eli Friedman14f082b2012-09-18 21:52:24 +00007203 // Note that in practice, this only affects enumeration types because there
7204 // aren't any built-in candidates of record type, and a user-defined operator
7205 // must have an operand of record or enumeration type. Also, the only other
7206 // overloaded operator with enumeration arguments, operator=,
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007207 // cannot be overloaded for enumeration types, so this is the only place
7208 // where we must suppress candidates like this.
7209 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7210 UserDefinedBinaryOperators;
7211
Richard Smithe54c3072013-05-05 15:51:06 +00007212 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007213 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7214 CandidateTypes[ArgIdx].enumeration_end()) {
7215 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7216 CEnd = CandidateSet.end();
7217 C != CEnd; ++C) {
7218 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7219 continue;
7220
Eli Friedman14f082b2012-09-18 21:52:24 +00007221 if (C->Function->isFunctionTemplateSpecialization())
7222 continue;
7223
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007224 QualType FirstParamType =
7225 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7226 QualType SecondParamType =
7227 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7228
7229 // Skip if either parameter isn't of enumeral type.
7230 if (!FirstParamType->isEnumeralType() ||
7231 !SecondParamType->isEnumeralType())
7232 continue;
7233
7234 // Add this operator to the set of known user-defined operators.
7235 UserDefinedBinaryOperators.insert(
7236 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7237 S.Context.getCanonicalType(SecondParamType)));
7238 }
7239 }
7240 }
7241
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007242 /// Set of (canonical) types that we've already handled.
7243 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7244
Richard Smithe54c3072013-05-05 15:51:06 +00007245 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007246 for (BuiltinCandidateTypeSet::iterator
7247 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7248 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7249 Ptr != PtrEnd; ++Ptr) {
7250 // Don't add the same builtin candidate twice.
7251 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7252 continue;
7253
7254 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007255 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007256 }
7257 for (BuiltinCandidateTypeSet::iterator
7258 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7259 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7260 Enum != EnumEnd; ++Enum) {
7261 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7262
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007263 // Don't add the same builtin candidate twice, or if a user defined
7264 // candidate exists.
7265 if (!AddedTypes.insert(CanonType) ||
7266 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7267 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007268 continue;
7269
7270 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007271 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007272 }
Douglas Gregor80af3132011-05-21 23:15:46 +00007273
7274 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7275 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7276 if (AddedTypes.insert(NullPtrTy) &&
Richard Smithe54c3072013-05-05 15:51:06 +00007277 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor80af3132011-05-21 23:15:46 +00007278 NullPtrTy))) {
7279 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007280 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor80af3132011-05-21 23:15:46 +00007281 CandidateSet);
7282 }
7283 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007284 }
7285 }
7286
7287 // C++ [over.built]p13:
7288 //
7289 // For every cv-qualified or cv-unqualified object type T
7290 // there exist candidate operator functions of the form
7291 //
7292 // T* operator+(T*, ptrdiff_t);
7293 // T& operator[](T*, ptrdiff_t); [BELOW]
7294 // T* operator-(T*, ptrdiff_t);
7295 // T* operator+(ptrdiff_t, T*);
7296 // T& operator[](ptrdiff_t, T*); [BELOW]
7297 //
7298 // C++ [over.built]p14:
7299 //
7300 // For every T, where T is a pointer to object type, there
7301 // exist candidate operator functions of the form
7302 //
7303 // ptrdiff_t operator-(T, T);
7304 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7305 /// Set of (canonical) types that we've already handled.
7306 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7307
7308 for (int Arg = 0; Arg < 2; ++Arg) {
7309 QualType AsymetricParamTypes[2] = {
7310 S.Context.getPointerDiffType(),
7311 S.Context.getPointerDiffType(),
7312 };
7313 for (BuiltinCandidateTypeSet::iterator
7314 Ptr = CandidateTypes[Arg].pointer_begin(),
7315 PtrEnd = CandidateTypes[Arg].pointer_end();
7316 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00007317 QualType PointeeTy = (*Ptr)->getPointeeType();
7318 if (!PointeeTy->isObjectType())
7319 continue;
7320
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007321 AsymetricParamTypes[Arg] = *Ptr;
7322 if (Arg == 0 || Op == OO_Plus) {
7323 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7324 // T* operator+(ptrdiff_t, T*);
Richard Smithe54c3072013-05-05 15:51:06 +00007325 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007326 }
7327 if (Op == OO_Minus) {
7328 // ptrdiff_t operator-(T, T);
7329 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7330 continue;
7331
7332 QualType ParamTypes[2] = { *Ptr, *Ptr };
7333 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smithe54c3072013-05-05 15:51:06 +00007334 Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007335 }
7336 }
7337 }
7338 }
7339
7340 // C++ [over.built]p12:
7341 //
7342 // For every pair of promoted arithmetic types L and R, there
7343 // exist candidate operator functions of the form
7344 //
7345 // LR operator*(L, R);
7346 // LR operator/(L, R);
7347 // LR operator+(L, R);
7348 // LR operator-(L, R);
7349 // bool operator<(L, R);
7350 // bool operator>(L, R);
7351 // bool operator<=(L, R);
7352 // bool operator>=(L, R);
7353 // bool operator==(L, R);
7354 // bool operator!=(L, R);
7355 //
7356 // where LR is the result of the usual arithmetic conversions
7357 // between types L and R.
7358 //
7359 // C++ [over.built]p24:
7360 //
7361 // For every pair of promoted arithmetic types L and R, there exist
7362 // candidate operator functions of the form
7363 //
7364 // LR operator?(bool, L, R);
7365 //
7366 // where LR is the result of the usual arithmetic conversions
7367 // between types L and R.
7368 // Our candidates ignore the first parameter.
7369 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007370 if (!HasArithmeticOrEnumeralCandidateType)
7371 return;
7372
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007373 for (unsigned Left = FirstPromotedArithmeticType;
7374 Left < LastPromotedArithmeticType; ++Left) {
7375 for (unsigned Right = FirstPromotedArithmeticType;
7376 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007377 QualType LandR[2] = { getArithmeticType(Left),
7378 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007379 QualType Result =
7380 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007381 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007382 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007383 }
7384 }
7385
7386 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7387 // conditional operator for vector types.
7388 for (BuiltinCandidateTypeSet::iterator
7389 Vec1 = CandidateTypes[0].vector_begin(),
7390 Vec1End = CandidateTypes[0].vector_end();
7391 Vec1 != Vec1End; ++Vec1) {
7392 for (BuiltinCandidateTypeSet::iterator
7393 Vec2 = CandidateTypes[1].vector_begin(),
7394 Vec2End = CandidateTypes[1].vector_end();
7395 Vec2 != Vec2End; ++Vec2) {
7396 QualType LandR[2] = { *Vec1, *Vec2 };
7397 QualType Result = S.Context.BoolTy;
7398 if (!isComparison) {
7399 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7400 Result = *Vec1;
7401 else
7402 Result = *Vec2;
7403 }
7404
Richard Smithe54c3072013-05-05 15:51:06 +00007405 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007406 }
7407 }
7408 }
7409
7410 // C++ [over.built]p17:
7411 //
7412 // For every pair of promoted integral types L and R, there
7413 // exist candidate operator functions of the form
7414 //
7415 // LR operator%(L, R);
7416 // LR operator&(L, R);
7417 // LR operator^(L, R);
7418 // LR operator|(L, R);
7419 // L operator<<(L, R);
7420 // L operator>>(L, R);
7421 //
7422 // where LR is the result of the usual arithmetic conversions
7423 // between types L and R.
7424 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007425 if (!HasArithmeticOrEnumeralCandidateType)
7426 return;
7427
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007428 for (unsigned Left = FirstPromotedIntegralType;
7429 Left < LastPromotedIntegralType; ++Left) {
7430 for (unsigned Right = FirstPromotedIntegralType;
7431 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00007432 QualType LandR[2] = { getArithmeticType(Left),
7433 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007434 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7435 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00007436 : getUsualArithmeticConversions(Left, Right);
Richard Smithe54c3072013-05-05 15:51:06 +00007437 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007438 }
7439 }
7440 }
7441
7442 // C++ [over.built]p20:
7443 //
7444 // For every pair (T, VQ), where T is an enumeration or
7445 // pointer to member type and VQ is either volatile or
7446 // empty, there exist candidate operator functions of the form
7447 //
7448 // VQ T& operator=(VQ T&, T);
7449 void addAssignmentMemberPointerOrEnumeralOverloads() {
7450 /// Set of (canonical) types that we've already handled.
7451 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7452
7453 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7454 for (BuiltinCandidateTypeSet::iterator
7455 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7456 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7457 Enum != EnumEnd; ++Enum) {
7458 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7459 continue;
7460
Richard Smithe54c3072013-05-05 15:51:06 +00007461 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007462 }
7463
7464 for (BuiltinCandidateTypeSet::iterator
7465 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7466 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7467 MemPtr != MemPtrEnd; ++MemPtr) {
7468 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7469 continue;
7470
Richard Smithe54c3072013-05-05 15:51:06 +00007471 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007472 }
7473 }
7474 }
7475
7476 // C++ [over.built]p19:
7477 //
7478 // For every pair (T, VQ), where T is any type and VQ is either
7479 // volatile or empty, there exist candidate operator functions
7480 // of the form
7481 //
7482 // T*VQ& operator=(T*VQ&, T*);
7483 //
7484 // C++ [over.built]p21:
7485 //
7486 // For every pair (T, VQ), where T is a cv-qualified or
7487 // cv-unqualified object type and VQ is either volatile or
7488 // empty, there exist candidate operator functions of the form
7489 //
7490 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7491 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7492 void addAssignmentPointerOverloads(bool isEqualOp) {
7493 /// Set of (canonical) types that we've already handled.
7494 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7495
7496 for (BuiltinCandidateTypeSet::iterator
7497 Ptr = CandidateTypes[0].pointer_begin(),
7498 PtrEnd = CandidateTypes[0].pointer_end();
7499 Ptr != PtrEnd; ++Ptr) {
7500 // If this is operator=, keep track of the builtin candidates we added.
7501 if (isEqualOp)
7502 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00007503 else if (!(*Ptr)->getPointeeType()->isObjectType())
7504 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007505
7506 // non-volatile version
7507 QualType ParamTypes[2] = {
7508 S.Context.getLValueReferenceType(*Ptr),
7509 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7510 };
Richard Smithe54c3072013-05-05 15:51:06 +00007511 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007512 /*IsAssigmentOperator=*/ isEqualOp);
7513
Douglas Gregor5bee2582012-06-04 00:15:09 +00007514 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7515 VisibleTypeConversionsQuals.hasVolatile();
7516 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007517 // volatile version
7518 ParamTypes[0] =
7519 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007520 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007521 /*IsAssigmentOperator=*/isEqualOp);
7522 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007523
7524 if (!(*Ptr).isRestrictQualified() &&
7525 VisibleTypeConversionsQuals.hasRestrict()) {
7526 // restrict version
7527 ParamTypes[0]
7528 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007529 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007530 /*IsAssigmentOperator=*/isEqualOp);
7531
7532 if (NeedVolatile) {
7533 // volatile restrict version
7534 ParamTypes[0]
7535 = S.Context.getLValueReferenceType(
7536 S.Context.getCVRQualifiedType(*Ptr,
7537 (Qualifiers::Volatile |
7538 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor5bee2582012-06-04 00:15:09 +00007540 /*IsAssigmentOperator=*/isEqualOp);
7541 }
7542 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007543 }
7544
7545 if (isEqualOp) {
7546 for (BuiltinCandidateTypeSet::iterator
7547 Ptr = CandidateTypes[1].pointer_begin(),
7548 PtrEnd = CandidateTypes[1].pointer_end();
7549 Ptr != PtrEnd; ++Ptr) {
7550 // Make sure we don't add the same candidate twice.
7551 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7552 continue;
7553
Chandler Carruth8e543b32010-12-12 08:17:55 +00007554 QualType ParamTypes[2] = {
7555 S.Context.getLValueReferenceType(*Ptr),
7556 *Ptr,
7557 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007558
7559 // non-volatile version
Richard Smithe54c3072013-05-05 15:51:06 +00007560 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007561 /*IsAssigmentOperator=*/true);
7562
Douglas Gregor5bee2582012-06-04 00:15:09 +00007563 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7564 VisibleTypeConversionsQuals.hasVolatile();
7565 if (NeedVolatile) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007566 // volatile version
7567 ParamTypes[0] =
7568 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007569 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7570 /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007571 }
Douglas Gregor5bee2582012-06-04 00:15:09 +00007572
7573 if (!(*Ptr).isRestrictQualified() &&
7574 VisibleTypeConversionsQuals.hasRestrict()) {
7575 // restrict version
7576 ParamTypes[0]
7577 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smithe54c3072013-05-05 15:51:06 +00007578 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7579 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007580
7581 if (NeedVolatile) {
7582 // volatile restrict version
7583 ParamTypes[0]
7584 = S.Context.getLValueReferenceType(
7585 S.Context.getCVRQualifiedType(*Ptr,
7586 (Qualifiers::Volatile |
7587 Qualifiers::Restrict)));
Richard Smithe54c3072013-05-05 15:51:06 +00007588 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7589 /*IsAssigmentOperator=*/true);
Douglas Gregor5bee2582012-06-04 00:15:09 +00007590 }
7591 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007592 }
7593 }
7594 }
7595
7596 // C++ [over.built]p18:
7597 //
7598 // For every triple (L, VQ, R), where L is an arithmetic type,
7599 // VQ is either volatile or empty, and R is a promoted
7600 // arithmetic type, there exist candidate operator functions of
7601 // the form
7602 //
7603 // VQ L& operator=(VQ L&, R);
7604 // VQ L& operator*=(VQ L&, R);
7605 // VQ L& operator/=(VQ L&, R);
7606 // VQ L& operator+=(VQ L&, R);
7607 // VQ L& operator-=(VQ L&, R);
7608 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00007609 if (!HasArithmeticOrEnumeralCandidateType)
7610 return;
7611
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007612 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7613 for (unsigned Right = FirstPromotedArithmeticType;
7614 Right < LastPromotedArithmeticType; ++Right) {
7615 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007616 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007617
7618 // Add this built-in operator as a candidate (VQ is empty).
7619 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007620 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007621 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007622 /*IsAssigmentOperator=*/isEqualOp);
7623
7624 // Add this built-in operator as a candidate (VQ is 'volatile').
7625 if (VisibleTypeConversionsQuals.hasVolatile()) {
7626 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007627 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007628 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007629 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007630 /*IsAssigmentOperator=*/isEqualOp);
7631 }
7632 }
7633 }
7634
7635 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7636 for (BuiltinCandidateTypeSet::iterator
7637 Vec1 = CandidateTypes[0].vector_begin(),
7638 Vec1End = CandidateTypes[0].vector_end();
7639 Vec1 != Vec1End; ++Vec1) {
7640 for (BuiltinCandidateTypeSet::iterator
7641 Vec2 = CandidateTypes[1].vector_begin(),
7642 Vec2End = CandidateTypes[1].vector_end();
7643 Vec2 != Vec2End; ++Vec2) {
7644 QualType ParamTypes[2];
7645 ParamTypes[1] = *Vec2;
7646 // Add this built-in operator as a candidate (VQ is empty).
7647 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smithe54c3072013-05-05 15:51:06 +00007648 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007649 /*IsAssigmentOperator=*/isEqualOp);
7650
7651 // Add this built-in operator as a candidate (VQ is 'volatile').
7652 if (VisibleTypeConversionsQuals.hasVolatile()) {
7653 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7654 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007655 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007656 /*IsAssigmentOperator=*/isEqualOp);
7657 }
7658 }
7659 }
7660 }
7661
7662 // C++ [over.built]p22:
7663 //
7664 // For every triple (L, VQ, R), where L is an integral type, VQ
7665 // is either volatile or empty, and R is a promoted integral
7666 // type, there exist candidate operator functions of the form
7667 //
7668 // VQ L& operator%=(VQ L&, R);
7669 // VQ L& operator<<=(VQ L&, R);
7670 // VQ L& operator>>=(VQ L&, R);
7671 // VQ L& operator&=(VQ L&, R);
7672 // VQ L& operator^=(VQ L&, R);
7673 // VQ L& operator|=(VQ L&, R);
7674 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00007675 if (!HasArithmeticOrEnumeralCandidateType)
7676 return;
7677
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007678 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7679 for (unsigned Right = FirstPromotedIntegralType;
7680 Right < LastPromotedIntegralType; ++Right) {
7681 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00007682 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007683
7684 // Add this built-in operator as a candidate (VQ is empty).
7685 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00007686 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smithe54c3072013-05-05 15:51:06 +00007687 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007688 if (VisibleTypeConversionsQuals.hasVolatile()) {
7689 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00007690 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007691 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7692 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smithe54c3072013-05-05 15:51:06 +00007693 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007694 }
7695 }
7696 }
7697 }
7698
7699 // C++ [over.operator]p23:
7700 //
7701 // There also exist candidate operator functions of the form
7702 //
7703 // bool operator!(bool);
7704 // bool operator&&(bool, bool);
7705 // bool operator||(bool, bool);
7706 void addExclaimOverload() {
7707 QualType ParamTy = S.Context.BoolTy;
Richard Smithe54c3072013-05-05 15:51:06 +00007708 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007709 /*IsAssignmentOperator=*/false,
7710 /*NumContextualBoolArguments=*/1);
7711 }
7712 void addAmpAmpOrPipePipeOverload() {
7713 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smithe54c3072013-05-05 15:51:06 +00007714 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007715 /*IsAssignmentOperator=*/false,
7716 /*NumContextualBoolArguments=*/2);
7717 }
7718
7719 // C++ [over.built]p13:
7720 //
7721 // For every cv-qualified or cv-unqualified object type T there
7722 // exist candidate operator functions of the form
7723 //
7724 // T* operator+(T*, ptrdiff_t); [ABOVE]
7725 // T& operator[](T*, ptrdiff_t);
7726 // T* operator-(T*, ptrdiff_t); [ABOVE]
7727 // T* operator+(ptrdiff_t, T*); [ABOVE]
7728 // T& operator[](ptrdiff_t, T*);
7729 void addSubscriptOverloads() {
7730 for (BuiltinCandidateTypeSet::iterator
7731 Ptr = CandidateTypes[0].pointer_begin(),
7732 PtrEnd = CandidateTypes[0].pointer_end();
7733 Ptr != PtrEnd; ++Ptr) {
7734 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7735 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007736 if (!PointeeType->isObjectType())
7737 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007738
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007739 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7740
7741 // T& operator[](T*, ptrdiff_t)
Richard Smithe54c3072013-05-05 15:51:06 +00007742 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007743 }
7744
7745 for (BuiltinCandidateTypeSet::iterator
7746 Ptr = CandidateTypes[1].pointer_begin(),
7747 PtrEnd = CandidateTypes[1].pointer_end();
7748 Ptr != PtrEnd; ++Ptr) {
7749 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7750 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00007751 if (!PointeeType->isObjectType())
7752 continue;
7753
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007754 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7755
7756 // T& operator[](ptrdiff_t, T*)
Richard Smithe54c3072013-05-05 15:51:06 +00007757 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007758 }
7759 }
7760
7761 // C++ [over.built]p11:
7762 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7763 // C1 is the same type as C2 or is a derived class of C2, T is an object
7764 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7765 // there exist candidate operator functions of the form
7766 //
7767 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7768 //
7769 // where CV12 is the union of CV1 and CV2.
7770 void addArrowStarOverloads() {
7771 for (BuiltinCandidateTypeSet::iterator
7772 Ptr = CandidateTypes[0].pointer_begin(),
7773 PtrEnd = CandidateTypes[0].pointer_end();
7774 Ptr != PtrEnd; ++Ptr) {
7775 QualType C1Ty = (*Ptr);
7776 QualType C1;
7777 QualifierCollector Q1;
7778 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7779 if (!isa<RecordType>(C1))
7780 continue;
7781 // heuristic to reduce number of builtin candidates in the set.
7782 // Add volatile/restrict version only if there are conversions to a
7783 // volatile/restrict type.
7784 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7785 continue;
7786 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7787 continue;
7788 for (BuiltinCandidateTypeSet::iterator
7789 MemPtr = CandidateTypes[1].member_pointer_begin(),
7790 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7791 MemPtr != MemPtrEnd; ++MemPtr) {
7792 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7793 QualType C2 = QualType(mptr->getClass(), 0);
7794 C2 = C2.getUnqualifiedType();
7795 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7796 break;
7797 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7798 // build CV12 T&
7799 QualType T = mptr->getPointeeType();
7800 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7801 T.isVolatileQualified())
7802 continue;
7803 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7804 T.isRestrictQualified())
7805 continue;
7806 T = Q1.apply(S.Context, T);
7807 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smithe54c3072013-05-05 15:51:06 +00007808 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007809 }
7810 }
7811 }
7812
7813 // Note that we don't consider the first argument, since it has been
7814 // contextually converted to bool long ago. The candidates below are
7815 // therefore added as binary.
7816 //
7817 // C++ [over.built]p25:
7818 // For every type T, where T is a pointer, pointer-to-member, or scoped
7819 // enumeration type, there exist candidate operator functions of the form
7820 //
7821 // T operator?(bool, T, T);
7822 //
7823 void addConditionalOperatorOverloads() {
7824 /// Set of (canonical) types that we've already handled.
7825 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7826
7827 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7828 for (BuiltinCandidateTypeSet::iterator
7829 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7830 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7831 Ptr != PtrEnd; ++Ptr) {
7832 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7833 continue;
7834
7835 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smithe54c3072013-05-05 15:51:06 +00007836 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007837 }
7838
7839 for (BuiltinCandidateTypeSet::iterator
7840 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7841 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7842 MemPtr != MemPtrEnd; ++MemPtr) {
7843 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7844 continue;
7845
7846 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smithe54c3072013-05-05 15:51:06 +00007847 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007848 }
7849
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007850 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007851 for (BuiltinCandidateTypeSet::iterator
7852 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7853 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7854 Enum != EnumEnd; ++Enum) {
7855 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7856 continue;
7857
7858 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7859 continue;
7860
7861 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smithe54c3072013-05-05 15:51:06 +00007862 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007863 }
7864 }
7865 }
7866 }
7867};
7868
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007869} // end anonymous namespace
7870
7871/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7872/// operator overloads to the candidate set (C++ [over.built]), based
7873/// on the operator @p Op and the arguments given. For example, if the
7874/// operator is a binary '+', this routine might add "int
7875/// operator+(int, int)" to cover integer addition.
Robert Wilhelm16e94b92013-08-09 18:02:13 +00007876void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7877 SourceLocation OpLoc,
7878 ArrayRef<Expr *> Args,
7879 OverloadCandidateSet &CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00007880 // Find all of the types that the arguments can convert to, but only
7881 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00007882 // that make use of these types. Also record whether we encounter non-record
7883 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00007884 Qualifiers VisibleTypeConversionsQuals;
7885 VisibleTypeConversionsQuals.addConst();
Richard Smithe54c3072013-05-05 15:51:06 +00007886 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00007887 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00007888
7889 bool HasNonRecordCandidateType = false;
7890 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007891 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smithe54c3072013-05-05 15:51:06 +00007892 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007893 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7894 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7895 OpLoc,
7896 true,
7897 (Op == OO_Exclaim ||
7898 Op == OO_AmpAmp ||
7899 Op == OO_PipePipe),
7900 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00007901 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7902 CandidateTypes[ArgIdx].hasNonRecordTypes();
7903 HasArithmeticOrEnumeralCandidateType =
7904 HasArithmeticOrEnumeralCandidateType ||
7905 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00007906 }
Douglas Gregora11693b2008-11-12 17:17:38 +00007907
Chandler Carruth00a38332010-12-13 01:44:01 +00007908 // Exit early when no non-record types have been added to the candidate set
7909 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007910 //
7911 // We can't exit early for !, ||, or &&, since there we have always have
7912 // 'bool' overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007913 if (!HasNonRecordCandidateType &&
Douglas Gregor877d4eb2011-10-10 14:05:31 +00007914 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00007915 return;
7916
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007917 // Setup an object to manage the common state for building overloads.
Richard Smithe54c3072013-05-05 15:51:06 +00007918 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007919 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00007920 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007921 CandidateTypes, CandidateSet);
7922
7923 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00007924 switch (Op) {
7925 case OO_None:
7926 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00007927 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00007928
Chandler Carruth5184de02010-12-12 08:51:33 +00007929 case OO_New:
7930 case OO_Delete:
7931 case OO_Array_New:
7932 case OO_Array_Delete:
7933 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00007934 llvm_unreachable(
7935 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00007936
7937 case OO_Comma:
7938 case OO_Arrow:
7939 // C++ [over.match.oper]p3:
7940 // -- For the operator ',', the unary operator '&', or the
7941 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00007942 break;
7943
7944 case OO_Plus: // '+' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007945 if (Args.size() == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007946 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00007947 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00007948
7949 case OO_Minus: // '-' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007950 if (Args.size() == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007951 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00007952 } else {
7953 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7954 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7955 }
Douglas Gregord08452f2008-11-19 15:42:04 +00007956 break;
7957
Chandler Carruth5184de02010-12-12 08:51:33 +00007958 case OO_Star: // '*' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007959 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007960 OpBuilder.addUnaryStarPointerOverloads();
7961 else
7962 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7963 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007964
Chandler Carruth5184de02010-12-12 08:51:33 +00007965 case OO_Slash:
7966 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007967 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00007968
7969 case OO_PlusPlus:
7970 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007971 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7972 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00007973 break;
7974
Douglas Gregor84605ae2009-08-24 13:43:27 +00007975 case OO_EqualEqual:
7976 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007977 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007978 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00007979
Douglas Gregora11693b2008-11-12 17:17:38 +00007980 case OO_Less:
7981 case OO_Greater:
7982 case OO_LessEqual:
7983 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00007984 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00007985 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7986 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00007987
Douglas Gregora11693b2008-11-12 17:17:38 +00007988 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00007989 case OO_Caret:
7990 case OO_Pipe:
7991 case OO_LessLess:
7992 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00007993 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00007994 break;
7995
Chandler Carruth5184de02010-12-12 08:51:33 +00007996 case OO_Amp: // '&' is either unary or binary
Richard Smithe54c3072013-05-05 15:51:06 +00007997 if (Args.size() == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00007998 // C++ [over.match.oper]p3:
7999 // -- For the operator ',', the unary operator '&', or the
8000 // operator '->', the built-in candidates set is empty.
8001 break;
8002
8003 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
8004 break;
8005
8006 case OO_Tilde:
8007 OpBuilder.addUnaryTildePromotedIntegralOverloads();
8008 break;
8009
Douglas Gregora11693b2008-11-12 17:17:38 +00008010 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008011 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00008012 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00008013
8014 case OO_PlusEqual:
8015 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008016 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008017 // Fall through.
8018
8019 case OO_StarEqual:
8020 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008021 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00008022 break;
8023
8024 case OO_PercentEqual:
8025 case OO_LessLessEqual:
8026 case OO_GreaterGreaterEqual:
8027 case OO_AmpEqual:
8028 case OO_CaretEqual:
8029 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008030 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008031 break;
8032
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008033 case OO_Exclaim:
8034 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00008035 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00008036
Douglas Gregora11693b2008-11-12 17:17:38 +00008037 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008038 case OO_PipePipe:
8039 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00008040 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008041
8042 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008043 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008044 break;
8045
8046 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008047 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00008048 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00008049
8050 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00008051 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00008052 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
8053 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00008054 }
8055}
8056
Douglas Gregore254f902009-02-04 00:32:51 +00008057/// \brief Add function candidates found via argument-dependent lookup
8058/// to the set of overloading candidates.
8059///
8060/// This routine performs argument-dependent name lookup based on the
8061/// given function name (which may also be an operator name) and adds
8062/// all of the overload candidates found by ADL to the overload
8063/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00008064void
Douglas Gregore254f902009-02-04 00:32:51 +00008065Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithe06a2c12012-02-25 06:24:24 +00008066 bool Operator, SourceLocation Loc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008067 ArrayRef<Expr *> Args,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008068 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008069 OverloadCandidateSet& CandidateSet,
Richard Smithb6626742012-10-18 17:56:02 +00008070 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00008071 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00008072
John McCall91f61fc2010-01-26 06:04:06 +00008073 // FIXME: This approach for uniquing ADL results (and removing
8074 // redundant candidates from the set) relies on pointer-equality,
8075 // which means we need to key off the canonical decl. However,
8076 // always going back to the canonical decl might not get us the
8077 // right set of default arguments. What default arguments are
8078 // we supposed to consider on ADL candidates, anyway?
8079
Douglas Gregorcabea402009-09-22 15:41:20 +00008080 // FIXME: Pass in the explicit template arguments?
Richard Smithb6626742012-10-18 17:56:02 +00008081 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00008082
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008083 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008084 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
8085 CandEnd = CandidateSet.end();
8086 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00008087 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00008088 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00008089 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00008090 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00008091 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00008092
8093 // For each of the ADL candidates we found, add it to the overload
8094 // set.
John McCall8fe68082010-01-26 07:16:45 +00008095 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00008096 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00008097 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00008098 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00008099 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008101 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
8102 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008103 } else
John McCall4c4c1df2010-01-26 03:27:55 +00008104 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00008105 FoundDecl, ExplicitTemplateArgs,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008106 Args, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00008107 }
Douglas Gregore254f902009-02-04 00:32:51 +00008108}
8109
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008110/// isBetterOverloadCandidate - Determines whether the first overload
8111/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00008112bool
John McCall5c32be02010-08-24 20:38:10 +00008113isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008114 const OverloadCandidate &Cand1,
8115 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008116 SourceLocation Loc,
8117 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008118 // Define viable functions to be better candidates than non-viable
8119 // functions.
8120 if (!Cand2.Viable)
8121 return Cand1.Viable;
8122 else if (!Cand1.Viable)
8123 return false;
8124
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008125 // C++ [over.match.best]p1:
8126 //
8127 // -- if F is a static member function, ICS1(F) is defined such
8128 // that ICS1(F) is neither better nor worse than ICS1(G) for
8129 // any function G, and, symmetrically, ICS1(G) is neither
8130 // better nor worse than ICS1(F).
8131 unsigned StartArg = 0;
8132 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
8133 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008134
Douglas Gregord3cb3562009-07-07 23:38:56 +00008135 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00008136 // A viable function F1 is defined to be a better function than another
8137 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00008138 // conversion sequence than ICSi(F2), and then...
Benjamin Kramerb0095172012-01-14 16:32:05 +00008139 unsigned NumArgs = Cand1.NumConversions;
8140 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008141 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008142 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00008143 switch (CompareImplicitConversionSequences(S,
8144 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008145 Cand2.Conversions[ArgIdx])) {
8146 case ImplicitConversionSequence::Better:
8147 // Cand1 has a better conversion sequence.
8148 HasBetterConversion = true;
8149 break;
8150
8151 case ImplicitConversionSequence::Worse:
8152 // Cand1 can't be better than Cand2.
8153 return false;
8154
8155 case ImplicitConversionSequence::Indistinguishable:
8156 // Do nothing.
8157 break;
8158 }
8159 }
8160
Mike Stump11289f42009-09-09 15:08:12 +00008161 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00008162 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008163 if (HasBetterConversion)
8164 return true;
8165
Mike Stump11289f42009-09-09 15:08:12 +00008166 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00008167 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00008168 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00008169 Cand2.Function && Cand2.Function->getPrimaryTemplate())
8170 return true;
Mike Stump11289f42009-09-09 15:08:12 +00008171
8172 // -- F1 and F2 are function template specializations, and the function
8173 // template for F1 is more specialized than the template for F2
8174 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00008175 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00008176 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00008177 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00008178 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00008179 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
8180 Cand2.Function->getPrimaryTemplate(),
8181 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008182 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00008183 : TPOC_Call,
Richard Smithe5b52202013-09-11 00:52:39 +00008184 Cand1.ExplicitCallArguments,
8185 Cand2.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00008186 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00008187 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008188
Douglas Gregora1f013e2008-11-07 22:36:19 +00008189 // -- the context is an initialization by user-defined conversion
8190 // (see 8.5, 13.3.1.5) and the standard conversion sequence
8191 // from the return type of F1 to the destination type (i.e.,
8192 // the type of the entity being initialized) is a better
8193 // conversion sequence than the standard conversion sequence
8194 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00008195 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00008196 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00008197 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregor2837aa22012-02-22 17:32:19 +00008198 // First check whether we prefer one of the conversion functions over the
8199 // other. This only distinguishes the results in non-standard, extension
8200 // cases such as the conversion from a lambda closure type to a function
8201 // pointer or block.
8202 ImplicitConversionSequence::CompareKind FuncResult
8203 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8204 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8205 return FuncResult;
8206
John McCall5c32be02010-08-24 20:38:10 +00008207 switch (CompareStandardConversionSequences(S,
8208 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00008209 Cand2.FinalConversion)) {
8210 case ImplicitConversionSequence::Better:
8211 // Cand1 has a better conversion sequence.
8212 return true;
8213
8214 case ImplicitConversionSequence::Worse:
8215 // Cand1 can't be better than Cand2.
8216 return false;
8217
8218 case ImplicitConversionSequence::Indistinguishable:
8219 // Do nothing
8220 break;
8221 }
8222 }
8223
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008224 // Check for enable_if value-based overload resolution.
8225 if (Cand1.Function && Cand2.Function &&
8226 (Cand1.Function->hasAttr<EnableIfAttr>() ||
8227 Cand2.Function->hasAttr<EnableIfAttr>())) {
8228 // FIXME: The next several lines are just
8229 // specific_attr_iterator<EnableIfAttr> but going in declaration order,
8230 // instead of reverse order which is how they're stored in the AST.
8231 AttrVec Cand1Attrs;
8232 AttrVec::iterator Cand1E = Cand1Attrs.end();
8233 if (Cand1.Function->hasAttrs()) {
8234 Cand1Attrs = Cand1.Function->getAttrs();
8235 Cand1E = std::remove_if(Cand1Attrs.begin(), Cand1Attrs.end(),
8236 IsNotEnableIfAttr);
8237 std::reverse(Cand1Attrs.begin(), Cand1E);
8238 }
8239
8240 AttrVec Cand2Attrs;
8241 AttrVec::iterator Cand2E = Cand2Attrs.end();
8242 if (Cand2.Function->hasAttrs()) {
8243 Cand2Attrs = Cand2.Function->getAttrs();
8244 Cand2E = std::remove_if(Cand2Attrs.begin(), Cand2Attrs.end(),
8245 IsNotEnableIfAttr);
8246 std::reverse(Cand2Attrs.begin(), Cand2E);
8247 }
8248 for (AttrVec::iterator
8249 Cand1I = Cand1Attrs.begin(), Cand2I = Cand2Attrs.begin();
8250 Cand1I != Cand1E || Cand2I != Cand2E; ++Cand1I, ++Cand2I) {
8251 if (Cand1I == Cand1E)
8252 return false;
8253 if (Cand2I == Cand2E)
8254 return true;
8255 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
8256 cast<EnableIfAttr>(*Cand1I)->getCond()->Profile(Cand1ID,
8257 S.getASTContext(), true);
8258 cast<EnableIfAttr>(*Cand2I)->getCond()->Profile(Cand2ID,
8259 S.getASTContext(), true);
8260 if (!(Cand1ID == Cand2ID))
8261 return false;
8262 }
8263 }
8264
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008265 return false;
8266}
8267
Mike Stump11289f42009-09-09 15:08:12 +00008268/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008269/// within an overload candidate set.
8270///
James Dennettffad8b72012-06-22 08:10:18 +00008271/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008272/// which overload resolution occurs.
8273///
James Dennettffad8b72012-06-22 08:10:18 +00008274/// \param Best If overload resolution was successful or found a deleted
8275/// function, \p Best points to the candidate function found.
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00008276///
8277/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00008278OverloadingResult
8279OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00008280 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00008281 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008282 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00008283 Best = end();
8284 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8285 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008286 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008287 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008288 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008289 }
8290
8291 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00008292 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008293 return OR_No_Viable_Function;
8294
8295 // Make sure that this function is better than every other viable
8296 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00008297 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00008298 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008299 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008300 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00008301 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00008302 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008303 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00008304 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008305 }
Mike Stump11289f42009-09-09 15:08:12 +00008306
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008307 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00008308 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00008309 (Best->Function->isDeleted() ||
8310 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00008311 return OR_Deleted;
8312
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008313 return OR_Success;
8314}
8315
John McCall53262c92010-01-12 02:15:36 +00008316namespace {
8317
8318enum OverloadCandidateKind {
8319 oc_function,
8320 oc_method,
8321 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00008322 oc_function_template,
8323 oc_method_template,
8324 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00008325 oc_implicit_default_constructor,
8326 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008327 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00008328 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00008329 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00008330 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00008331};
8332
John McCalle1ac8d12010-01-13 00:25:19 +00008333OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8334 FunctionDecl *Fn,
8335 std::string &Description) {
8336 bool isTemplate = false;
8337
8338 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8339 isTemplate = true;
8340 Description = S.getTemplateArgumentBindingsText(
8341 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8342 }
John McCallfd0b2f82010-01-06 09:43:14 +00008343
8344 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00008345 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008346 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008347
Sebastian Redl08905022011-02-05 19:23:19 +00008348 if (Ctor->getInheritedConstructor())
8349 return oc_implicit_inherited_constructor;
8350
Alexis Hunt119c10e2011-05-25 23:16:36 +00008351 if (Ctor->isDefaultConstructor())
8352 return oc_implicit_default_constructor;
8353
8354 if (Ctor->isMoveConstructor())
8355 return oc_implicit_move_constructor;
8356
8357 assert(Ctor->isCopyConstructor() &&
8358 "unexpected sort of implicit constructor");
8359 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00008360 }
8361
8362 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8363 // This actually gets spelled 'candidate function' for now, but
8364 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00008365 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00008366 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00008367
Alexis Hunt119c10e2011-05-25 23:16:36 +00008368 if (Meth->isMoveAssignmentOperator())
8369 return oc_implicit_move_assignment;
8370
Douglas Gregor12695102012-02-10 08:36:38 +00008371 if (Meth->isCopyAssignmentOperator())
8372 return oc_implicit_copy_assignment;
8373
8374 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8375 return oc_method;
John McCall53262c92010-01-12 02:15:36 +00008376 }
8377
John McCalle1ac8d12010-01-13 00:25:19 +00008378 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00008379}
8380
Larisse Voufo98b20f12013-07-19 23:00:19 +00008381void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redl08905022011-02-05 19:23:19 +00008382 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8383 if (!Ctor) return;
8384
8385 Ctor = Ctor->getInheritedConstructor();
8386 if (!Ctor) return;
8387
8388 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8389}
8390
John McCall53262c92010-01-12 02:15:36 +00008391} // end anonymous namespace
8392
8393// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00008394void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00008395 std::string FnDesc;
8396 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00008397 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8398 << (unsigned) K << FnDesc;
8399 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8400 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00008401 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00008402}
8403
Nick Lewyckyed4265c2013-09-22 10:06:01 +00008404// Notes the location of all overload candidates designated through
Douglas Gregorb491ed32011-02-19 21:32:49 +00008405// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00008406void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008407 assert(OverloadedExpr->getType() == Context.OverloadTy);
8408
8409 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8410 OverloadExpr *OvlExpr = Ovl.Expression;
8411
8412 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8413 IEnd = OvlExpr->decls_end();
8414 I != IEnd; ++I) {
8415 if (FunctionTemplateDecl *FunTmpl =
8416 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008417 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008418 } else if (FunctionDecl *Fun
8419 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00008420 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008421 }
8422 }
8423}
8424
John McCall0d1da222010-01-12 00:44:57 +00008425/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8426/// "lead" diagnostic; it will be given two arguments, the source and
8427/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00008428void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8429 Sema &S,
8430 SourceLocation CaretLoc,
8431 const PartialDiagnostic &PDiag) const {
8432 S.Diag(CaretLoc, PDiag)
8433 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008434 // FIXME: The note limiting machinery is borrowed from
8435 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8436 // refactoring here.
8437 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8438 unsigned CandsShown = 0;
8439 AmbiguousConversionSequence::const_iterator I, E;
8440 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8441 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8442 break;
8443 ++CandsShown;
John McCall5c32be02010-08-24 20:38:10 +00008444 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00008445 }
Matt Beaumont-Gay641bd892012-11-08 20:50:02 +00008446 if (I != E)
8447 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall12f97bc2010-01-08 04:41:39 +00008448}
8449
John McCall0d1da222010-01-12 00:44:57 +00008450namespace {
8451
John McCall6a61b522010-01-13 09:16:55 +00008452void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8453 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8454 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00008455 assert(Cand->Function && "for now, candidate must be a function");
8456 FunctionDecl *Fn = Cand->Function;
8457
8458 // There's a conversion slot for the object argument if this is a
8459 // non-constructor method. Note that 'I' corresponds the
8460 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00008461 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00008462 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00008463 if (I == 0)
8464 isObjectArgument = true;
8465 else
8466 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00008467 }
8468
John McCalle1ac8d12010-01-13 00:25:19 +00008469 std::string FnDesc;
8470 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8471
John McCall6a61b522010-01-13 09:16:55 +00008472 Expr *FromExpr = Conv.Bad.FromExpr;
8473 QualType FromTy = Conv.Bad.getFromType();
8474 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00008475
John McCallfb7ad0f2010-02-02 02:42:52 +00008476 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00008477 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00008478 Expr *E = FromExpr->IgnoreParens();
8479 if (isa<UnaryOperator>(E))
8480 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00008481 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00008482
8483 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8484 << (unsigned) FnKind << FnDesc
8485 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8486 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008487 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00008488 return;
8489 }
8490
John McCall6d174642010-01-23 08:10:49 +00008491 // Do some hand-waving analysis to see if the non-viability is due
8492 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00008493 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8494 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8495 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8496 CToTy = RT->getPointeeType();
8497 else {
8498 // TODO: detect and diagnose the full richness of const mismatches.
8499 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8500 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8501 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8502 }
8503
8504 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8505 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall47000992010-01-14 03:28:57 +00008506 Qualifiers FromQs = CFromTy.getQualifiers();
8507 Qualifiers ToQs = CToTy.getQualifiers();
8508
8509 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8510 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8511 << (unsigned) FnKind << FnDesc
8512 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8513 << FromTy
8514 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8515 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008516 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008517 return;
8518 }
8519
John McCall31168b02011-06-15 23:02:42 +00008520 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00008521 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00008522 << (unsigned) FnKind << FnDesc
8523 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8524 << FromTy
8525 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8526 << (unsigned) isObjectArgument << I+1;
8527 MaybeEmitInheritedConstructorNote(S, Fn);
8528 return;
8529 }
8530
Douglas Gregoraec25842011-04-26 23:16:46 +00008531 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8532 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8533 << (unsigned) FnKind << FnDesc
8534 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8535 << FromTy
8536 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8537 << (unsigned) isObjectArgument << I+1;
8538 MaybeEmitInheritedConstructorNote(S, Fn);
8539 return;
8540 }
8541
John McCall47000992010-01-14 03:28:57 +00008542 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8543 assert(CVR && "unexpected qualifiers mismatch");
8544
8545 if (isObjectArgument) {
8546 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8547 << (unsigned) FnKind << FnDesc
8548 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8549 << FromTy << (CVR - 1);
8550 } else {
8551 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8552 << (unsigned) FnKind << FnDesc
8553 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8554 << FromTy << (CVR - 1) << I+1;
8555 }
Sebastian Redl08905022011-02-05 19:23:19 +00008556 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00008557 return;
8558 }
8559
Sebastian Redla72462c2011-09-24 17:48:32 +00008560 // Special diagnostic for failure to convert an initializer list, since
8561 // telling the user that it has type void is not useful.
8562 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8563 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8564 << (unsigned) FnKind << FnDesc
8565 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8566 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8567 MaybeEmitInheritedConstructorNote(S, Fn);
8568 return;
8569 }
8570
John McCall6d174642010-01-23 08:10:49 +00008571 // Diagnose references or pointers to incomplete types differently,
8572 // since it's far from impossible that the incompleteness triggered
8573 // the failure.
8574 QualType TempFromTy = FromTy.getNonReferenceType();
8575 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8576 TempFromTy = PTy->getPointeeType();
8577 if (TempFromTy->isIncompleteType()) {
8578 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8579 << (unsigned) FnKind << FnDesc
8580 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8581 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008582 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00008583 return;
8584 }
8585
Douglas Gregor56f2e342010-06-30 23:01:39 +00008586 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008587 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008588 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8589 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8590 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8591 FromPtrTy->getPointeeType()) &&
8592 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8593 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008594 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00008595 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008596 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00008597 }
8598 } else if (const ObjCObjectPointerType *FromPtrTy
8599 = FromTy->getAs<ObjCObjectPointerType>()) {
8600 if (const ObjCObjectPointerType *ToPtrTy
8601 = ToTy->getAs<ObjCObjectPointerType>())
8602 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8603 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8604 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8605 FromPtrTy->getPointeeType()) &&
8606 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008607 BaseToDerivedConversion = 2;
8608 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008609 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8610 !FromTy->isIncompleteType() &&
8611 !ToRefTy->getPointeeType()->isIncompleteType() &&
8612 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8613 BaseToDerivedConversion = 3;
8614 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8615 ToTy.getNonReferenceType().getCanonicalType() ==
8616 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008617 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8618 << (unsigned) FnKind << FnDesc
8619 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8620 << (unsigned) isObjectArgument << I + 1;
8621 MaybeEmitInheritedConstructorNote(S, Fn);
8622 return;
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008623 }
Kaelyn Uhrain9ea8f7e2012-06-19 00:37:47 +00008624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008625
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008626 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008627 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008628 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00008629 << (unsigned) FnKind << FnDesc
8630 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00008631 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008632 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00008633 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00008634 return;
8635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008636
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00008637 if (isa<ObjCObjectPointerType>(CFromTy) &&
8638 isa<PointerType>(CToTy)) {
8639 Qualifiers FromQs = CFromTy.getQualifiers();
8640 Qualifiers ToQs = CToTy.getQualifiers();
8641 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8642 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8643 << (unsigned) FnKind << FnDesc
8644 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8645 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8646 MaybeEmitInheritedConstructorNote(S, Fn);
8647 return;
8648 }
8649 }
8650
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008651 // Emit the generic diagnostic and, optionally, add the hints to it.
8652 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8653 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00008654 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008655 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8656 << (unsigned) (Cand->Fix.Kind);
8657
8658 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer490afa62012-01-14 21:05:10 +00008659 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8660 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksdf92ddf2011-07-19 19:49:12 +00008661 FDiag << *HI;
8662 S.Diag(Fn->getLocation(), FDiag);
8663
Sebastian Redl08905022011-02-05 19:23:19 +00008664 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00008665}
8666
Larisse Voufo98b20f12013-07-19 23:00:19 +00008667/// Additional arity mismatch diagnosis specific to a function overload
8668/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8669/// over a candidate in any candidate set.
8670bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8671 unsigned NumArgs) {
John McCall6a61b522010-01-13 09:16:55 +00008672 FunctionDecl *Fn = Cand->Function;
John McCall6a61b522010-01-13 09:16:55 +00008673 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008674
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008675 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo98b20f12013-07-19 23:00:19 +00008676 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008677 // right number of arguments, because only overloaded operators have
8678 // the weird behavior of overloading member and non-member functions.
8679 // Just don't report anything.
8680 if (Fn->isInvalidDecl() &&
8681 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008682 return true;
8683
8684 if (NumArgs < MinParams) {
8685 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8686 (Cand->FailureKind == ovl_fail_bad_deduction &&
8687 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8688 } else {
8689 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8690 (Cand->FailureKind == ovl_fail_bad_deduction &&
8691 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8692 }
8693
8694 return false;
8695}
8696
8697/// General arity mismatch diagnosis over a candidate in a candidate set.
8698void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8699 assert(isa<FunctionDecl>(D) &&
8700 "The templated declaration should at least be a function"
8701 " when diagnosing bad template argument deduction due to too many"
8702 " or too few arguments");
8703
8704 FunctionDecl *Fn = cast<FunctionDecl>(D);
8705
8706 // TODO: treat calls to a missing default constructor as a special case
8707 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8708 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00008709
John McCall6a61b522010-01-13 09:16:55 +00008710 // at least / at most / exactly
8711 unsigned mode, modeCount;
8712 if (NumFormalArgs < MinParams) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008713 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00008714 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00008715 mode = 0; // "at least"
8716 else
8717 mode = 2; // "exactly"
8718 modeCount = MinParams;
8719 } else {
John McCall6a61b522010-01-13 09:16:55 +00008720 if (MinParams != FnTy->getNumArgs())
8721 mode = 1; // "at most"
8722 else
8723 mode = 2; // "exactly"
8724 modeCount = FnTy->getNumArgs();
8725 }
8726
8727 std::string Description;
8728 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8729
Richard Smith10ff50d2012-05-11 05:16:41 +00008730 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8731 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8732 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8733 << Fn->getParamDecl(0) << NumFormalArgs;
8734 else
8735 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8736 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8737 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00008738 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00008739}
8740
Larisse Voufo98b20f12013-07-19 23:00:19 +00008741/// Arity mismatch diagnosis specific to a function overload candidate.
8742void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8743 unsigned NumFormalArgs) {
8744 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8745 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8746}
Larisse Voufo47c08452013-07-19 22:53:23 +00008747
Larisse Voufo98b20f12013-07-19 23:00:19 +00008748TemplateDecl *getDescribedTemplate(Decl *Templated) {
8749 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8750 return FD->getDescribedFunctionTemplate();
8751 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8752 return RD->getDescribedClassTemplate();
8753
8754 llvm_unreachable("Unsupported: Getting the described template declaration"
8755 " for bad deduction diagnosis");
8756}
8757
8758/// Diagnose a failed template-argument deduction.
8759void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8760 DeductionFailureInfo &DeductionFailure,
8761 unsigned NumArgs) {
8762 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008763 NamedDecl *ParamD;
8764 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8765 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8766 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo98b20f12013-07-19 23:00:19 +00008767 switch (DeductionFailure.Result) {
John McCall8b9ed552010-02-01 18:53:26 +00008768 case Sema::TDK_Success:
8769 llvm_unreachable("TDK_success while diagnosing bad deduction");
8770
8771 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00008772 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo98b20f12013-07-19 23:00:19 +00008773 S.Diag(Templated->getLocation(),
8774 diag::note_ovl_candidate_incomplete_deduction)
8775 << ParamD->getDeclName();
8776 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008777 return;
8778 }
8779
John McCall42d7d192010-08-05 09:05:08 +00008780 case Sema::TDK_Underqualified: {
8781 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8782 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8783
Larisse Voufo98b20f12013-07-19 23:00:19 +00008784 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008785
8786 // Param will have been canonicalized, but it should just be a
8787 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00008788 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00008789 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00008790 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00008791 assert(S.Context.hasSameType(Param, NonCanonParam));
8792
8793 // Arg has also been canonicalized, but there's nothing we can do
8794 // about that. It also doesn't matter as much, because it won't
8795 // have any template parameters in it (because deduction isn't
8796 // done on dependent types).
Larisse Voufo98b20f12013-07-19 23:00:19 +00008797 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall42d7d192010-08-05 09:05:08 +00008798
Larisse Voufo98b20f12013-07-19 23:00:19 +00008799 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8800 << ParamD->getDeclName() << Arg << NonCanonParam;
8801 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall42d7d192010-08-05 09:05:08 +00008802 return;
8803 }
8804
8805 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008806 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008807 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008808 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008809 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008810 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008811 which = 1;
8812 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008813 which = 2;
8814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008815
Larisse Voufo98b20f12013-07-19 23:00:19 +00008816 S.Diag(Templated->getLocation(),
8817 diag::note_ovl_candidate_inconsistent_deduction)
8818 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8819 << *DeductionFailure.getSecondArg();
8820 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00008821 return;
8822 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00008823
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008824 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008825 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008826 if (ParamD->getDeclName())
Larisse Voufo98b20f12013-07-19 23:00:19 +00008827 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008828 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008829 << ParamD->getDeclName();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008830 else {
8831 int index = 0;
8832 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8833 index = TTP->getIndex();
8834 else if (NonTypeTemplateParmDecl *NTTP
8835 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8836 index = NTTP->getIndex();
8837 else
8838 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo98b20f12013-07-19 23:00:19 +00008839 S.Diag(Templated->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008840 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008841 << (index + 1);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008842 }
Larisse Voufo98b20f12013-07-19 23:00:19 +00008843 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00008844 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008845
Douglas Gregor02eb4832010-05-08 18:13:28 +00008846 case Sema::TDK_TooManyArguments:
8847 case Sema::TDK_TooFewArguments:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008848 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregor02eb4832010-05-08 18:13:28 +00008849 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00008850
8851 case Sema::TDK_InstantiationDepth:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008852 S.Diag(Templated->getLocation(),
8853 diag::note_ovl_candidate_instantiation_depth);
8854 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008855 return;
8856
8857 case Sema::TDK_SubstitutionFailure: {
Richard Smith9ca64612012-05-07 09:03:25 +00008858 // Format the template argument list into the argument string.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008859 SmallString<128> TemplateArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008860 if (TemplateArgumentList *Args =
Larisse Voufo98b20f12013-07-19 23:00:19 +00008861 DeductionFailure.getTemplateArgumentList()) {
Richard Smith9ca64612012-05-07 09:03:25 +00008862 TemplateArgString = " ";
8863 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo98b20f12013-07-19 23:00:19 +00008864 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smith9ca64612012-05-07 09:03:25 +00008865 }
8866
Richard Smith6f8d2c62012-05-09 05:17:00 +00008867 // If this candidate was disabled by enable_if, say so.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008868 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith6f8d2c62012-05-09 05:17:00 +00008869 if (PDiag && PDiag->second.getDiagID() ==
8870 diag::err_typename_nested_not_found_enable_if) {
8871 // FIXME: Use the source range of the condition, and the fully-qualified
8872 // name of the enable_if template. These are both present in PDiag.
8873 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8874 << "'enable_if'" << TemplateArgString;
8875 return;
8876 }
8877
Richard Smith9ca64612012-05-07 09:03:25 +00008878 // Format the SFINAE diagnostic into the argument string.
8879 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8880 // formatted message in another diagnostic.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008881 SmallString<128> SFINAEArgString;
Richard Smith9ca64612012-05-07 09:03:25 +00008882 SourceRange R;
Richard Smith6f8d2c62012-05-09 05:17:00 +00008883 if (PDiag) {
Richard Smith9ca64612012-05-07 09:03:25 +00008884 SFINAEArgString = ": ";
8885 R = SourceRange(PDiag->first, PDiag->first);
8886 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8887 }
8888
Larisse Voufo98b20f12013-07-19 23:00:19 +00008889 S.Diag(Templated->getLocation(),
8890 diag::note_ovl_candidate_substitution_failure)
8891 << TemplateArgString << SFINAEArgString << R;
8892 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregord09efd42010-05-08 20:07:26 +00008893 return;
8894 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008895
Richard Smith8c6eeb92013-01-31 04:03:12 +00008896 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo98b20f12013-07-19 23:00:19 +00008897 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8898 S.Diag(Templated->getLocation(),
Richard Smith8c6eeb92013-01-31 04:03:12 +00008899 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo98b20f12013-07-19 23:00:19 +00008900 << R.Expression->getName();
Richard Smith8c6eeb92013-01-31 04:03:12 +00008901 return;
8902 }
8903
Richard Trieue3732352013-04-08 21:11:40 +00008904 case Sema::TDK_NonDeducedMismatch: {
Richard Smith44ecdbd2013-01-31 05:19:49 +00008905 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008906 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8907 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieue3732352013-04-08 21:11:40 +00008908 if (FirstTA.getKind() == TemplateArgument::Template &&
8909 SecondTA.getKind() == TemplateArgument::Template) {
8910 TemplateName FirstTN = FirstTA.getAsTemplate();
8911 TemplateName SecondTN = SecondTA.getAsTemplate();
8912 if (FirstTN.getKind() == TemplateName::Template &&
8913 SecondTN.getKind() == TemplateName::Template) {
8914 if (FirstTN.getAsTemplateDecl()->getName() ==
8915 SecondTN.getAsTemplateDecl()->getName()) {
8916 // FIXME: This fixes a bad diagnostic where both templates are named
8917 // the same. This particular case is a bit difficult since:
8918 // 1) It is passed as a string to the diagnostic printer.
8919 // 2) The diagnostic printer only attempts to find a better
8920 // name for types, not decls.
8921 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008922 S.Diag(Templated->getLocation(),
Richard Trieue3732352013-04-08 21:11:40 +00008923 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8924 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8925 return;
8926 }
8927 }
8928 }
Faisal Vali2b391ab2013-09-26 19:54:12 +00008929 // FIXME: For generic lambda parameters, check if the function is a lambda
8930 // call operator, and if so, emit a prettier and more informative
8931 // diagnostic that mentions 'auto' and lambda in addition to
8932 // (or instead of?) the canonical template type parameters.
Larisse Voufo98b20f12013-07-19 23:00:19 +00008933 S.Diag(Templated->getLocation(),
8934 diag::note_ovl_candidate_non_deduced_mismatch)
8935 << FirstTA << SecondTA;
Richard Smith44ecdbd2013-01-31 05:19:49 +00008936 return;
Richard Trieue3732352013-04-08 21:11:40 +00008937 }
John McCall8b9ed552010-02-01 18:53:26 +00008938 // TODO: diagnose these individually, then kill off
8939 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith44ecdbd2013-01-31 05:19:49 +00008940 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo98b20f12013-07-19 23:00:19 +00008941 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8942 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall8b9ed552010-02-01 18:53:26 +00008943 return;
8944 }
8945}
8946
Larisse Voufo98b20f12013-07-19 23:00:19 +00008947/// Diagnose a failed template-argument deduction, for function calls.
8948void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8949 unsigned TDK = Cand->DeductionFailure.Result;
8950 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8951 if (CheckArityMismatch(S, Cand, NumArgs))
8952 return;
8953 }
8954 DiagnoseBadDeduction(S, Cand->Function, // pattern
8955 Cand->DeductionFailure, NumArgs);
8956}
8957
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008958/// CUDA: diagnose an invalid call across targets.
8959void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8960 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8961 FunctionDecl *Callee = Cand->Function;
8962
8963 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8964 CalleeTarget = S.IdentifyCUDATarget(Callee);
8965
8966 std::string FnDesc;
8967 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8968
8969 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8970 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8971}
8972
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008973void DiagnoseFailedEnableIfAttr(Sema &S, OverloadCandidate *Cand) {
8974 FunctionDecl *Callee = Cand->Function;
8975 EnableIfAttr *Attr = static_cast<EnableIfAttr*>(Cand->DeductionFailure.Data);
8976
8977 S.Diag(Callee->getLocation(),
8978 diag::note_ovl_candidate_disabled_by_enable_if_attr)
8979 << Attr->getCond()->getSourceRange() << Attr->getMessage();
8980}
8981
John McCall8b9ed552010-02-01 18:53:26 +00008982/// Generates a 'note' diagnostic for an overload candidate. We've
8983/// already generated a primary error at the call site.
8984///
8985/// It really does need to be a single diagnostic with its caret
8986/// pointed at the candidate declaration. Yes, this creates some
8987/// major challenges of technical writing. Yes, this makes pointing
8988/// out problems with specific arguments quite awkward. It's still
8989/// better than generating twenty screens of text for every failed
8990/// overload.
8991///
8992/// It would be great to be able to express per-candidate problems
8993/// more richly for those diagnostic clients that cared, but we'd
8994/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00008995void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00008996 unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00008997 FunctionDecl *Fn = Cand->Function;
8998
John McCall12f97bc2010-01-08 04:41:39 +00008999 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00009000 if (Cand->Viable && (Fn->isDeleted() ||
9001 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00009002 std::string FnDesc;
9003 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00009004
9005 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith6f1e2c62012-04-02 20:59:25 +00009006 << FnKind << FnDesc
9007 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redl08905022011-02-05 19:23:19 +00009008 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00009009 return;
John McCall12f97bc2010-01-08 04:41:39 +00009010 }
9011
John McCalle1ac8d12010-01-13 00:25:19 +00009012 // We don't really have anything else to say about viable candidates.
9013 if (Cand->Viable) {
9014 S.NoteOverloadCandidate(Fn);
9015 return;
9016 }
John McCall0d1da222010-01-12 00:44:57 +00009017
John McCall6a61b522010-01-13 09:16:55 +00009018 switch (Cand->FailureKind) {
9019 case ovl_fail_too_many_arguments:
9020 case ovl_fail_too_few_arguments:
9021 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00009022
John McCall6a61b522010-01-13 09:16:55 +00009023 case ovl_fail_bad_deduction:
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009024 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall8b9ed552010-02-01 18:53:26 +00009025
John McCallfe796dd2010-01-23 05:17:32 +00009026 case ovl_fail_trivial_conversion:
9027 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00009028 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00009029 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009030
John McCall65eb8792010-02-25 01:37:24 +00009031 case ovl_fail_bad_conversion: {
9032 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009033 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00009034 if (Cand->Conversions[I].isBad())
9035 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009036
John McCall6a61b522010-01-13 09:16:55 +00009037 // FIXME: this currently happens when we're called from SemaInit
9038 // when user-conversion overload fails. Figure out how to handle
9039 // those conditions and diagnose them well.
9040 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00009041 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009042
9043 case ovl_fail_bad_target:
9044 return DiagnoseBadTarget(S, Cand);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009045
9046 case ovl_fail_enable_if:
9047 return DiagnoseFailedEnableIfAttr(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00009048 }
John McCalld3224162010-01-08 00:58:21 +00009049}
9050
9051void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
9052 // Desugar the type of the surrogate down to a function type,
9053 // retaining as many typedefs as possible while still showing
9054 // the function type (and, therefore, its parameter types).
9055 QualType FnType = Cand->Surrogate->getConversionType();
9056 bool isLValueReference = false;
9057 bool isRValueReference = false;
9058 bool isPointer = false;
9059 if (const LValueReferenceType *FnTypeRef =
9060 FnType->getAs<LValueReferenceType>()) {
9061 FnType = FnTypeRef->getPointeeType();
9062 isLValueReference = true;
9063 } else if (const RValueReferenceType *FnTypeRef =
9064 FnType->getAs<RValueReferenceType>()) {
9065 FnType = FnTypeRef->getPointeeType();
9066 isRValueReference = true;
9067 }
9068 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
9069 FnType = FnTypePtr->getPointeeType();
9070 isPointer = true;
9071 }
9072 // Desugar down to a function type.
9073 FnType = QualType(FnType->getAs<FunctionType>(), 0);
9074 // Reconstruct the pointer/reference as appropriate.
9075 if (isPointer) FnType = S.Context.getPointerType(FnType);
9076 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
9077 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
9078
9079 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
9080 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00009081 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00009082}
9083
9084void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie1d202a62012-10-08 01:11:04 +00009085 StringRef Opc,
John McCalld3224162010-01-08 00:58:21 +00009086 SourceLocation OpLoc,
9087 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009088 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalld3224162010-01-08 00:58:21 +00009089 std::string TypeStr("operator");
9090 TypeStr += Opc;
9091 TypeStr += "(";
9092 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramerb0095172012-01-14 16:32:05 +00009093 if (Cand->NumConversions == 1) {
John McCalld3224162010-01-08 00:58:21 +00009094 TypeStr += ")";
9095 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
9096 } else {
9097 TypeStr += ", ";
9098 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
9099 TypeStr += ")";
9100 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
9101 }
9102}
9103
9104void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
9105 OverloadCandidate *Cand) {
Benjamin Kramerb0095172012-01-14 16:32:05 +00009106 unsigned NoOperands = Cand->NumConversions;
John McCalld3224162010-01-08 00:58:21 +00009107 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
9108 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00009109 if (ICS.isBad()) break; // all meaningless after first invalid
9110 if (!ICS.isAmbiguous()) continue;
9111
John McCall5c32be02010-08-24 20:38:10 +00009112 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00009113 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00009114 }
9115}
9116
Larisse Voufo98b20f12013-07-19 23:00:19 +00009117static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall3712d9e2010-01-15 23:32:50 +00009118 if (Cand->Function)
9119 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00009120 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00009121 return Cand->Surrogate->getLocation();
9122 return SourceLocation();
9123}
9124
Larisse Voufo98b20f12013-07-19 23:00:19 +00009125static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00009126 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009127 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00009128 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009129
Douglas Gregorc5c01a62012-09-13 21:01:57 +00009130 case Sema::TDK_Invalid:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009131 case Sema::TDK_Incomplete:
9132 return 1;
9133
9134 case Sema::TDK_Underqualified:
9135 case Sema::TDK_Inconsistent:
9136 return 2;
9137
9138 case Sema::TDK_SubstitutionFailure:
9139 case Sema::TDK_NonDeducedMismatch:
Richard Smith44ecdbd2013-01-31 05:19:49 +00009140 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009141 return 3;
9142
9143 case Sema::TDK_InstantiationDepth:
9144 case Sema::TDK_FailedOverloadResolution:
9145 return 4;
9146
9147 case Sema::TDK_InvalidExplicitArguments:
9148 return 5;
9149
9150 case Sema::TDK_TooManyArguments:
9151 case Sema::TDK_TooFewArguments:
9152 return 6;
9153 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00009154 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009155}
9156
John McCallad2587a2010-01-12 00:48:53 +00009157struct CompareOverloadCandidatesForDisplay {
9158 Sema &S;
9159 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00009160
9161 bool operator()(const OverloadCandidate *L,
9162 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00009163 // Fast-path this check.
9164 if (L == R) return false;
9165
John McCall12f97bc2010-01-08 04:41:39 +00009166 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00009167 if (L->Viable) {
9168 if (!R->Viable) return true;
9169
9170 // TODO: introduce a tri-valued comparison for overload
9171 // candidates. Would be more worthwhile if we had a sort
9172 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00009173 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
9174 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00009175 } else if (R->Viable)
9176 return false;
John McCall12f97bc2010-01-08 04:41:39 +00009177
John McCall3712d9e2010-01-15 23:32:50 +00009178 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00009179
John McCall3712d9e2010-01-15 23:32:50 +00009180 // Criteria by which we can sort non-viable candidates:
9181 if (!L->Viable) {
9182 // 1. Arity mismatches come after other candidates.
9183 if (L->FailureKind == ovl_fail_too_many_arguments ||
9184 L->FailureKind == ovl_fail_too_few_arguments)
9185 return false;
9186 if (R->FailureKind == ovl_fail_too_many_arguments ||
9187 R->FailureKind == ovl_fail_too_few_arguments)
9188 return true;
John McCall12f97bc2010-01-08 04:41:39 +00009189
John McCallfe796dd2010-01-23 05:17:32 +00009190 // 2. Bad conversions come first and are ordered by the number
9191 // of bad conversions and quality of good conversions.
9192 if (L->FailureKind == ovl_fail_bad_conversion) {
9193 if (R->FailureKind != ovl_fail_bad_conversion)
9194 return true;
9195
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009196 // The conversion that can be fixed with a smaller number of changes,
9197 // comes first.
9198 unsigned numLFixes = L->Fix.NumConversionsFixed;
9199 unsigned numRFixes = R->Fix.NumConversionsFixed;
9200 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
9201 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009202 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009203 if (numLFixes < numRFixes)
9204 return true;
9205 else
9206 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00009207 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009208
John McCallfe796dd2010-01-23 05:17:32 +00009209 // If there's any ordering between the defined conversions...
9210 // FIXME: this might not be transitive.
Benjamin Kramerb0095172012-01-14 16:32:05 +00009211 assert(L->NumConversions == R->NumConversions);
John McCallfe796dd2010-01-23 05:17:32 +00009212
9213 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00009214 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009215 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00009216 switch (CompareImplicitConversionSequences(S,
9217 L->Conversions[I],
9218 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00009219 case ImplicitConversionSequence::Better:
9220 leftBetter++;
9221 break;
9222
9223 case ImplicitConversionSequence::Worse:
9224 leftBetter--;
9225 break;
9226
9227 case ImplicitConversionSequence::Indistinguishable:
9228 break;
9229 }
9230 }
9231 if (leftBetter > 0) return true;
9232 if (leftBetter < 0) return false;
9233
9234 } else if (R->FailureKind == ovl_fail_bad_conversion)
9235 return false;
9236
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009237 if (L->FailureKind == ovl_fail_bad_deduction) {
9238 if (R->FailureKind != ovl_fail_bad_deduction)
9239 return true;
9240
9241 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9242 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00009243 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00009244 } else if (R->FailureKind == ovl_fail_bad_deduction)
9245 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00009246
John McCall3712d9e2010-01-15 23:32:50 +00009247 // TODO: others?
9248 }
9249
9250 // Sort everything else by location.
9251 SourceLocation LLoc = GetLocationForCandidate(L);
9252 SourceLocation RLoc = GetLocationForCandidate(R);
9253
9254 // Put candidates without locations (e.g. builtins) at the end.
9255 if (LLoc.isInvalid()) return false;
9256 if (RLoc.isInvalid()) return true;
9257
9258 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00009259 }
9260};
9261
John McCallfe796dd2010-01-23 05:17:32 +00009262/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009263/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00009264void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009265 ArrayRef<Expr *> Args) {
John McCallfe796dd2010-01-23 05:17:32 +00009266 assert(!Cand->Viable);
9267
9268 // Don't do anything on failures other than bad conversion.
9269 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
9270
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009271 // We only want the FixIts if all the arguments can be corrected.
9272 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00009273 // Use a implicit copy initialization to check conversion fixes.
9274 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009275
John McCallfe796dd2010-01-23 05:17:32 +00009276 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00009277 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramerb0095172012-01-14 16:32:05 +00009278 unsigned ConvCount = Cand->NumConversions;
John McCallfe796dd2010-01-23 05:17:32 +00009279 while (true) {
9280 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9281 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009282 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00009283 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00009284 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009285 }
John McCallfe796dd2010-01-23 05:17:32 +00009286 }
9287
9288 if (ConvIdx == ConvCount)
9289 return;
9290
John McCall65eb8792010-02-25 01:37:24 +00009291 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9292 "remaining conversion is initialized?");
9293
Douglas Gregoradc7a702010-04-16 17:45:54 +00009294 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00009295 // operation somehow.
9296 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00009297
9298 const FunctionProtoType* Proto;
9299 unsigned ArgIdx = ConvIdx;
9300
9301 if (Cand->IsSurrogate) {
9302 QualType ConvType
9303 = Cand->Surrogate->getConversionType().getNonReferenceType();
9304 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9305 ConvType = ConvPtrType->getPointeeType();
9306 Proto = ConvType->getAs<FunctionProtoType>();
9307 ArgIdx--;
9308 } else if (Cand->Function) {
9309 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9310 if (isa<CXXMethodDecl>(Cand->Function) &&
9311 !isa<CXXConstructorDecl>(Cand->Function))
9312 ArgIdx--;
9313 } else {
9314 // Builtin binary operator with a bad first conversion.
9315 assert(ConvCount <= 3);
9316 for (; ConvIdx != ConvCount; ++ConvIdx)
9317 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009318 = TryCopyInitialization(S, Args[ConvIdx],
9319 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009320 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009321 /*InOverloadResolution*/ true,
9322 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009323 S.getLangOpts().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00009324 return;
9325 }
9326
9327 // Fill in the rest of the conversions.
9328 unsigned NumArgsInProto = Proto->getNumArgs();
9329 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009330 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00009331 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00009332 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009333 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00009334 /*InOverloadResolution=*/true,
9335 /*AllowObjCWritebackConversion=*/
David Blaikiebbafb8a2012-03-11 07:00:24 +00009336 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009337 // Store the FixIt in the candidate if it exists.
9338 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00009339 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00009340 }
John McCallfe796dd2010-01-23 05:17:32 +00009341 else
9342 Cand->Conversions[ConvIdx].setEllipsis();
9343 }
9344}
9345
John McCalld3224162010-01-08 00:58:21 +00009346} // end anonymous namespace
9347
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009348/// PrintOverloadCandidates - When overload resolution fails, prints
9349/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00009350/// set.
John McCall5c32be02010-08-24 20:38:10 +00009351void OverloadCandidateSet::NoteCandidates(Sema &S,
9352 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009353 ArrayRef<Expr *> Args,
David Blaikie1d202a62012-10-08 01:11:04 +00009354 StringRef Opc,
John McCall5c32be02010-08-24 20:38:10 +00009355 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00009356 // Sort the candidates by viability and position. Sorting directly would
9357 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009358 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00009359 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9360 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00009361 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00009362 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00009363 else if (OCD == OCD_AllCandidates) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009364 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009365 if (Cand->Function || Cand->IsSurrogate)
9366 Cands.push_back(Cand);
9367 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9368 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00009369 }
9370 }
9371
John McCallad2587a2010-01-12 00:48:53 +00009372 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00009373 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009374
John McCall0d1da222010-01-12 00:44:57 +00009375 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00009376
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009377 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregor79591782012-10-23 23:11:23 +00009378 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009379 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00009380 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9381 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00009382
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009383 // Set an arbitrary limit on the number of candidate functions we'll spam
9384 // the user with. FIXME: This limit should depend on details of the
9385 // candidate list.
Douglas Gregor79591782012-10-23 23:11:23 +00009386 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009387 break;
9388 }
9389 ++CandsShown;
9390
John McCalld3224162010-01-08 00:58:21 +00009391 if (Cand->Function)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +00009392 NoteFunctionCandidate(S, Cand, Args.size());
John McCalld3224162010-01-08 00:58:21 +00009393 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00009394 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009395 else {
9396 assert(Cand->Viable &&
9397 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00009398 // Generally we only see ambiguities including viable builtin
9399 // operators if overload resolution got screwed up by an
9400 // ambiguous user-defined conversion.
9401 //
9402 // FIXME: It's quite possible for different conversions to see
9403 // different ambiguities, though.
9404 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00009405 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00009406 ReportedAmbiguousConversions = true;
9407 }
John McCalld3224162010-01-08 00:58:21 +00009408
John McCall0d1da222010-01-12 00:44:57 +00009409 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00009410 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00009411 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009412 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00009413
9414 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00009415 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009416}
9417
Larisse Voufo98b20f12013-07-19 23:00:19 +00009418static SourceLocation
9419GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9420 return Cand->Specialization ? Cand->Specialization->getLocation()
9421 : SourceLocation();
9422}
9423
9424struct CompareTemplateSpecCandidatesForDisplay {
9425 Sema &S;
9426 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9427
9428 bool operator()(const TemplateSpecCandidate *L,
9429 const TemplateSpecCandidate *R) {
9430 // Fast-path this check.
9431 if (L == R)
9432 return false;
9433
9434 // Assuming that both candidates are not matches...
9435
9436 // Sort by the ranking of deduction failures.
9437 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9438 return RankDeductionFailure(L->DeductionFailure) <
9439 RankDeductionFailure(R->DeductionFailure);
9440
9441 // Sort everything else by location.
9442 SourceLocation LLoc = GetLocationForCandidate(L);
9443 SourceLocation RLoc = GetLocationForCandidate(R);
9444
9445 // Put candidates without locations (e.g. builtins) at the end.
9446 if (LLoc.isInvalid())
9447 return false;
9448 if (RLoc.isInvalid())
9449 return true;
9450
9451 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9452 }
9453};
9454
9455/// Diagnose a template argument deduction failure.
9456/// We are treating these failures as overload failures due to bad
9457/// deductions.
9458void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9459 DiagnoseBadDeduction(S, Specialization, // pattern
9460 DeductionFailure, /*NumArgs=*/0);
9461}
9462
9463void TemplateSpecCandidateSet::destroyCandidates() {
9464 for (iterator i = begin(), e = end(); i != e; ++i) {
9465 i->DeductionFailure.Destroy();
9466 }
9467}
9468
9469void TemplateSpecCandidateSet::clear() {
9470 destroyCandidates();
9471 Candidates.clear();
9472}
9473
9474/// NoteCandidates - When no template specialization match is found, prints
9475/// diagnostic messages containing the non-matching specializations that form
9476/// the candidate set.
9477/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9478/// OCD == OCD_AllCandidates and Cand->Viable == false.
9479void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9480 // Sort the candidates by position (assuming no candidate is a match).
9481 // Sorting directly would be prohibitive, so we make a set of pointers
9482 // and sort those.
9483 SmallVector<TemplateSpecCandidate *, 32> Cands;
9484 Cands.reserve(size());
9485 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9486 if (Cand->Specialization)
9487 Cands.push_back(Cand);
Alp Tokerd4733632013-12-05 04:47:09 +00009488 // Otherwise, this is a non-matching builtin candidate. We do not,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009489 // in general, want to list every possible builtin candidate.
9490 }
9491
9492 std::sort(Cands.begin(), Cands.end(),
9493 CompareTemplateSpecCandidatesForDisplay(S));
9494
9495 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9496 // for generalization purposes (?).
9497 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9498
9499 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9500 unsigned CandsShown = 0;
9501 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9502 TemplateSpecCandidate *Cand = *I;
9503
9504 // Set an arbitrary limit on the number of candidates we'll spam
9505 // the user with. FIXME: This limit should depend on details of the
9506 // candidate list.
9507 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9508 break;
9509 ++CandsShown;
9510
9511 assert(Cand->Specialization &&
9512 "Non-matching built-in candidates are not added to Cands.");
9513 Cand->NoteDeductionFailure(S);
9514 }
9515
9516 if (I != E)
9517 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9518}
9519
Douglas Gregorb491ed32011-02-19 21:32:49 +00009520// [PossiblyAFunctionType] --> [Return]
9521// NonFunctionType --> NonFunctionType
9522// R (A) --> R(A)
9523// R (*)(A) --> R (A)
9524// R (&)(A) --> R (A)
9525// R (S::*)(A) --> R (A)
9526QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9527 QualType Ret = PossiblyAFunctionType;
9528 if (const PointerType *ToTypePtr =
9529 PossiblyAFunctionType->getAs<PointerType>())
9530 Ret = ToTypePtr->getPointeeType();
9531 else if (const ReferenceType *ToTypeRef =
9532 PossiblyAFunctionType->getAs<ReferenceType>())
9533 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009534 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00009535 PossiblyAFunctionType->getAs<MemberPointerType>())
9536 Ret = MemTypePtr->getPointeeType();
9537 Ret =
9538 Context.getCanonicalType(Ret).getUnqualifiedType();
9539 return Ret;
9540}
Douglas Gregorcd695e52008-11-10 20:40:00 +00009541
Douglas Gregorb491ed32011-02-19 21:32:49 +00009542// A helper class to help with address of function resolution
9543// - allows us to avoid passing around all those ugly parameters
9544class AddressOfFunctionResolver
9545{
9546 Sema& S;
9547 Expr* SourceExpr;
9548 const QualType& TargetType;
9549 QualType TargetFunctionType; // Extracted function type from target type
9550
9551 bool Complain;
9552 //DeclAccessPair& ResultFunctionAccessPair;
9553 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009554
Douglas Gregorb491ed32011-02-19 21:32:49 +00009555 bool TargetTypeIsNonStaticMemberFunction;
9556 bool FoundNonTemplateFunction;
David Majnemera4f7c7a2013-08-01 06:13:59 +00009557 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009558
Douglas Gregorb491ed32011-02-19 21:32:49 +00009559 OverloadExpr::FindResult OvlExprInfo;
9560 OverloadExpr *OvlExpr;
9561 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00009562 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009563 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009564
Douglas Gregorb491ed32011-02-19 21:32:49 +00009565public:
Larisse Voufo98b20f12013-07-19 23:00:19 +00009566 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9567 const QualType &TargetType, bool Complain)
9568 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9569 Complain(Complain), Context(S.getASTContext()),
9570 TargetTypeIsNonStaticMemberFunction(
9571 !!TargetType->getAs<MemberPointerType>()),
9572 FoundNonTemplateFunction(false),
David Majnemera4f7c7a2013-08-01 06:13:59 +00009573 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo98b20f12013-07-19 23:00:19 +00009574 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9575 OvlExpr(OvlExprInfo.Expression),
9576 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009577 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruthffce2452011-03-29 08:08:18 +00009578
David Majnemera4f7c7a2013-08-01 06:13:59 +00009579 if (TargetFunctionType->isFunctionType()) {
9580 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9581 if (!UME->isImplicitAccess() &&
9582 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9583 StaticMemberFunctionFromBoundPointer = true;
9584 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9585 DeclAccessPair dap;
9586 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9587 OvlExpr, false, &dap)) {
9588 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9589 if (!Method->isStatic()) {
9590 // If the target type is a non-function type and the function found
9591 // is a non-static member function, pretend as if that was the
9592 // target, it's the only possible type to end up with.
9593 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruthffce2452011-03-29 08:08:18 +00009594
David Majnemera4f7c7a2013-08-01 06:13:59 +00009595 // And skip adding the function if its not in the proper form.
9596 // We'll diagnose this due to an empty set of functions.
9597 if (!OvlExprInfo.HasFormOfMemberPointer)
9598 return;
Chandler Carruthffce2452011-03-29 08:08:18 +00009599 }
9600
David Majnemera4f7c7a2013-08-01 06:13:59 +00009601 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor9b146582009-07-08 20:55:45 +00009602 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009603 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00009604 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009605
9606 if (OvlExpr->hasExplicitTemplateArgs())
9607 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00009608
Douglas Gregorb491ed32011-02-19 21:32:49 +00009609 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9610 // C++ [over.over]p4:
9611 // If more than one function is selected, [...]
9612 if (Matches.size() > 1) {
9613 if (FoundNonTemplateFunction)
9614 EliminateAllTemplateMatches();
9615 else
9616 EliminateAllExceptMostSpecializedTemplate();
9617 }
9618 }
9619 }
9620
9621private:
9622 bool isTargetTypeAFunction() const {
9623 return TargetFunctionType->isFunctionType();
9624 }
9625
9626 // [ToType] [Return]
9627
9628 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9629 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9630 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9631 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9632 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9633 }
9634
9635 // return true if any matching specializations were found
9636 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9637 const DeclAccessPair& CurAccessFunPair) {
9638 if (CXXMethodDecl *Method
9639 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9640 // Skip non-static function templates when converting to pointer, and
9641 // static when converting to member pointer.
9642 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9643 return false;
9644 }
9645 else if (TargetTypeIsNonStaticMemberFunction)
9646 return false;
9647
9648 // C++ [over.over]p2:
9649 // If the name is a function template, template argument deduction is
9650 // done (14.8.2.2), and if the argument deduction succeeds, the
9651 // resulting template argument list is used to generate a single
9652 // function template specialization, which is added to the set of
9653 // overloaded functions considered.
9654 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009655 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregorb491ed32011-02-19 21:32:49 +00009656 if (Sema::TemplateDeductionResult Result
9657 = S.DeduceTemplateArguments(FunctionTemplate,
9658 &OvlExplicitTemplateArgs,
9659 TargetFunctionType, Specialization,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009660 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009661 // Make a note of the failed deduction for diagnostics.
9662 FailedCandidates.addCandidate()
9663 .set(FunctionTemplate->getTemplatedDecl(),
9664 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009665 return false;
9666 }
9667
Douglas Gregor19a41f12013-04-17 08:45:07 +00009668 // Template argument deduction ensures that we have an exact match or
9669 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009670 // This function template specicalization works.
9671 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor19a41f12013-04-17 08:45:07 +00009672 assert(S.isSameOrCompatibleFunctionType(
9673 Context.getCanonicalType(Specialization->getType()),
9674 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregorb491ed32011-02-19 21:32:49 +00009675 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9676 return true;
9677 }
9678
9679 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9680 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009681 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00009682 // Skip non-static functions when converting to pointer, and static
9683 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009684 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9685 return false;
9686 }
9687 else if (TargetTypeIsNonStaticMemberFunction)
9688 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009689
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00009690 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009691 if (S.getLangOpts().CUDA)
Peter Collingbourne7277fe82011-10-02 23:49:40 +00009692 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9693 if (S.CheckCUDATarget(Caller, FunDecl))
9694 return false;
9695
Richard Smith2a7d4812013-05-04 07:00:32 +00009696 // If any candidate has a placeholder return type, trigger its deduction
9697 // now.
9698 if (S.getLangOpts().CPlusPlus1y &&
9699 FunDecl->getResultType()->isUndeducedType() &&
9700 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9701 return false;
9702
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00009703 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009704 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9705 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00009706 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9707 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009708 Matches.push_back(std::make_pair(CurAccessFunPair,
9709 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009710 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00009711 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00009712 }
Mike Stump11289f42009-09-09 15:08:12 +00009713 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009714
9715 return false;
9716 }
9717
9718 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9719 bool Ret = false;
9720
9721 // If the overload expression doesn't have the form of a pointer to
9722 // member, don't try to convert it to a pointer-to-member type.
9723 if (IsInvalidFormOfPointerToMemberFunction())
9724 return false;
9725
9726 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9727 E = OvlExpr->decls_end();
9728 I != E; ++I) {
9729 // Look through any using declarations to find the underlying function.
9730 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9731
9732 // C++ [over.over]p3:
9733 // Non-member functions and static member functions match
9734 // targets of type "pointer-to-function" or "reference-to-function."
9735 // Nonstatic member functions match targets of
9736 // type "pointer-to-member-function."
9737 // Note that according to DR 247, the containing class does not matter.
9738 if (FunctionTemplateDecl *FunctionTemplate
9739 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9740 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9741 Ret = true;
9742 }
9743 // If we have explicit template arguments supplied, skip non-templates.
9744 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9745 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9746 Ret = true;
9747 }
9748 assert(Ret || Matches.empty());
9749 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009750 }
9751
Douglas Gregorb491ed32011-02-19 21:32:49 +00009752 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00009753 // [...] and any given function template specialization F1 is
9754 // eliminated if the set contains a second function template
9755 // specialization whose function template is more specialized
9756 // than the function template of F1 according to the partial
9757 // ordering rules of 14.5.5.2.
9758
9759 // The algorithm specified above is quadratic. We instead use a
9760 // two-pass algorithm (similar to the one used to identify the
9761 // best viable function in an overload set) that identifies the
9762 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00009763
9764 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9765 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9766 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009767
Larisse Voufo98b20f12013-07-19 23:00:19 +00009768 // TODO: It looks like FailedCandidates does not serve much purpose
9769 // here, since the no_viable diagnostic has index 0.
9770 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith35e1da22013-09-10 22:59:25 +00009771 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo98b20f12013-07-19 23:00:19 +00009772 SourceExpr->getLocStart(), S.PDiag(),
9773 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9774 .second->getDeclName(),
9775 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9776 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009777
Douglas Gregorb491ed32011-02-19 21:32:49 +00009778 if (Result != MatchesCopy.end()) {
9779 // Make it the first and only element
9780 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9781 Matches[0].second = cast<FunctionDecl>(*Result);
9782 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00009783 }
9784 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009785
Douglas Gregorb491ed32011-02-19 21:32:49 +00009786 void EliminateAllTemplateMatches() {
9787 // [...] any function template specializations in the set are
9788 // eliminated if the set also contains a non-template function, [...]
9789 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9790 if (Matches[I].second->getPrimaryTemplate() == 0)
9791 ++I;
9792 else {
9793 Matches[I] = Matches[--N];
9794 Matches.set_size(N);
9795 }
9796 }
9797 }
9798
9799public:
9800 void ComplainNoMatchesFound() const {
9801 assert(Matches.empty());
9802 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9803 << OvlExpr->getName() << TargetFunctionType
9804 << OvlExpr->getSourceRange();
Richard Smith0d905472013-08-14 00:00:44 +00009805 if (FailedCandidates.empty())
9806 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9807 else {
9808 // We have some deduction failure messages. Use them to diagnose
9809 // the function templates, and diagnose the non-template candidates
9810 // normally.
9811 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9812 IEnd = OvlExpr->decls_end();
9813 I != IEnd; ++I)
9814 if (FunctionDecl *Fun =
9815 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9816 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9817 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9818 }
9819 }
9820
Douglas Gregorb491ed32011-02-19 21:32:49 +00009821 bool IsInvalidFormOfPointerToMemberFunction() const {
9822 return TargetTypeIsNonStaticMemberFunction &&
9823 !OvlExprInfo.HasFormOfMemberPointer;
9824 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009825
Douglas Gregorb491ed32011-02-19 21:32:49 +00009826 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9827 // TODO: Should we condition this on whether any functions might
9828 // have matched, or is it more appropriate to do that in callers?
9829 // TODO: a fixit wouldn't hurt.
9830 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9831 << TargetType << OvlExpr->getSourceRange();
9832 }
David Majnemera4f7c7a2013-08-01 06:13:59 +00009833
9834 bool IsStaticMemberFunctionFromBoundPointer() const {
9835 return StaticMemberFunctionFromBoundPointer;
9836 }
9837
9838 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9839 S.Diag(OvlExpr->getLocStart(),
9840 diag::err_invalid_form_pointer_member_function)
9841 << OvlExpr->getSourceRange();
9842 }
9843
Douglas Gregorb491ed32011-02-19 21:32:49 +00009844 void ComplainOfInvalidConversion() const {
9845 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9846 << OvlExpr->getName() << TargetType;
9847 }
9848
9849 void ComplainMultipleMatchesFound() const {
9850 assert(Matches.size() > 1);
9851 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9852 << OvlExpr->getName()
9853 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00009854 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009855 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009856
9857 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9858
Douglas Gregorb491ed32011-02-19 21:32:49 +00009859 int getNumMatches() const { return Matches.size(); }
9860
9861 FunctionDecl* getMatchingFunctionDecl() const {
9862 if (Matches.size() != 1) return 0;
9863 return Matches[0].second;
9864 }
9865
9866 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9867 if (Matches.size() != 1) return 0;
9868 return &Matches[0].first;
9869 }
9870};
9871
9872/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9873/// an overloaded function (C++ [over.over]), where @p From is an
9874/// expression with overloaded function type and @p ToType is the type
9875/// we're trying to resolve to. For example:
9876///
9877/// @code
9878/// int f(double);
9879/// int f(int);
9880///
9881/// int (*pfd)(double) = f; // selects f(double)
9882/// @endcode
9883///
9884/// This routine returns the resulting FunctionDecl if it could be
9885/// resolved, and NULL otherwise. When @p Complain is true, this
9886/// routine will emit diagnostics if there is an error.
9887FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009888Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9889 QualType TargetType,
9890 bool Complain,
9891 DeclAccessPair &FoundResult,
9892 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009893 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009894
9895 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9896 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009897 int NumMatches = Resolver.getNumMatches();
9898 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009899 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009900 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9901 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9902 else
9903 Resolver.ComplainNoMatchesFound();
9904 }
9905 else if (NumMatches > 1 && Complain)
9906 Resolver.ComplainMultipleMatchesFound();
9907 else if (NumMatches == 1) {
9908 Fn = Resolver.getMatchingFunctionDecl();
9909 assert(Fn);
9910 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemera4f7c7a2013-08-01 06:13:59 +00009911 if (Complain) {
9912 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9913 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9914 else
9915 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9916 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00009917 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00009918
9919 if (pHadMultipleCandidates)
9920 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00009921 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009922}
9923
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009924/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009925/// resolve that overloaded function expression down to a single function.
9926///
9927/// This routine can only resolve template-ids that refer to a single function
9928/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009929/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009930/// as described in C++0x [temp.arg.explicit]p3.
Alp Toker67b47ac2013-10-20 18:48:56 +00009931///
9932/// If no template-ids are found, no diagnostics are emitted and NULL is
9933/// returned.
John McCall0009fcc2011-04-26 20:42:42 +00009934FunctionDecl *
9935Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9936 bool Complain,
9937 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009938 // C++ [over.over]p1:
9939 // [...] [Note: any redundant set of parentheses surrounding the
9940 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009941 // C++ [over.over]p1:
9942 // [...] The overloaded function name can be preceded by the &
9943 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009944
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009945 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00009946 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009947 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00009948
9949 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00009950 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo98b20f12013-07-19 23:00:19 +00009951 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009952
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009953 // Look through all of the overloaded functions, searching for one
9954 // whose type matches exactly.
9955 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00009956 for (UnresolvedSetIterator I = ovl->decls_begin(),
9957 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009958 // C++0x [temp.arg.explicit]p3:
9959 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009960 // where deduction is not done, if a template argument list is
9961 // specified and it, along with any default template arguments,
9962 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009963 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00009964 FunctionTemplateDecl *FunctionTemplate
9965 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009966
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009967 // C++ [over.over]p2:
9968 // If the name is a function template, template argument deduction is
9969 // done (14.8.2.2), and if the argument deduction succeeds, the
9970 // resulting template argument list is used to generate a single
9971 // function template specialization, which is added to the set of
9972 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009973 FunctionDecl *Specialization = 0;
Larisse Voufo98b20f12013-07-19 23:00:19 +00009974 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009975 if (TemplateDeductionResult Result
9976 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor19a41f12013-04-17 08:45:07 +00009977 Specialization, Info,
9978 /*InOverloadResolution=*/true)) {
Larisse Voufo98b20f12013-07-19 23:00:19 +00009979 // Make a note of the failed deduction for diagnostics.
9980 // TODO: Actually use the failed-deduction info?
9981 FailedCandidates.addCandidate()
9982 .set(FunctionTemplate->getTemplatedDecl(),
9983 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009984 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009985 }
9986
John McCall0009fcc2011-04-26 20:42:42 +00009987 assert(Specialization && "no specialization and no error?");
9988
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009989 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00009990 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00009991 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00009992 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9993 << ovl->getName();
9994 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00009995 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00009996 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00009997 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00009998
John McCall0009fcc2011-04-26 20:42:42 +00009999 Matched = Specialization;
10000 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010001 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010002
Richard Smith2a7d4812013-05-04 07:00:32 +000010003 if (Matched && getLangOpts().CPlusPlus1y &&
10004 Matched->getResultType()->isUndeducedType() &&
10005 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
10006 return 0;
10007
Douglas Gregor8364e6b2009-12-21 23:17:24 +000010008 return Matched;
10009}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010010
Douglas Gregor1beec452011-03-12 01:48:56 +000010011
10012
10013
John McCall50a2c2c2011-10-11 23:14:30 +000010014// Resolve and fix an overloaded expression that can be resolved
10015// because it identifies a single function template specialization.
10016//
Douglas Gregor1beec452011-03-12 01:48:56 +000010017// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +000010018//
10019// Return true if it was logically possible to so resolve the
10020// expression, regardless of whether or not it succeeded. Always
10021// returns true if 'complain' is set.
10022bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
10023 ExprResult &SrcExpr, bool doFunctionPointerConverion,
10024 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +000010025 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +000010026 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +000010027 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +000010028
John McCall50a2c2c2011-10-11 23:14:30 +000010029 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +000010030
John McCall0009fcc2011-04-26 20:42:42 +000010031 DeclAccessPair found;
10032 ExprResult SingleFunctionExpression;
10033 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
10034 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar62ee6412012-03-09 18:35:03 +000010035 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall50a2c2c2011-10-11 23:14:30 +000010036 SrcExpr = ExprError();
10037 return true;
10038 }
John McCall0009fcc2011-04-26 20:42:42 +000010039
10040 // It is only correct to resolve to an instance method if we're
10041 // resolving a form that's permitted to be a pointer to member.
10042 // Otherwise we'll end up making a bound member expression, which
10043 // is illegal in all the contexts we resolve like this.
10044 if (!ovl.HasFormOfMemberPointer &&
10045 isa<CXXMethodDecl>(fn) &&
10046 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +000010047 if (!complain) return false;
10048
10049 Diag(ovl.Expression->getExprLoc(),
10050 diag::err_bound_member_function)
10051 << 0 << ovl.Expression->getSourceRange();
10052
10053 // TODO: I believe we only end up here if there's a mix of
10054 // static and non-static candidates (otherwise the expression
10055 // would have 'bound member' type, not 'overload' type).
10056 // Ideally we would note which candidate was chosen and why
10057 // the static candidates were rejected.
10058 SrcExpr = ExprError();
10059 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010060 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +000010061
Sylvestre Ledrua5202662012-07-31 06:56:50 +000010062 // Fix the expression to refer to 'fn'.
John McCall0009fcc2011-04-26 20:42:42 +000010063 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +000010064 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +000010065
10066 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +000010067 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +000010068 SingleFunctionExpression =
10069 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +000010070 if (SingleFunctionExpression.isInvalid()) {
10071 SrcExpr = ExprError();
10072 return true;
10073 }
10074 }
John McCall0009fcc2011-04-26 20:42:42 +000010075 }
10076
10077 if (!SingleFunctionExpression.isUsable()) {
10078 if (complain) {
10079 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
10080 << ovl.Expression->getName()
10081 << DestTypeForComplaining
10082 << OpRangeForComplaining
10083 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +000010084 NoteAllOverloadCandidates(SrcExpr.get());
10085
10086 SrcExpr = ExprError();
10087 return true;
10088 }
10089
10090 return false;
John McCall0009fcc2011-04-26 20:42:42 +000010091 }
10092
John McCall50a2c2c2011-10-11 23:14:30 +000010093 SrcExpr = SingleFunctionExpression;
10094 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +000010095}
10096
Douglas Gregorcabea402009-09-22 15:41:20 +000010097/// \brief Add a single candidate to the overload set.
10098static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +000010099 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +000010100 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010101 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010102 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +000010103 bool PartialOverloading,
10104 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +000010105 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +000010106 if (isa<UsingShadowDecl>(Callee))
10107 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
10108
Douglas Gregorcabea402009-09-22 15:41:20 +000010109 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +000010110 if (ExplicitTemplateArgs) {
10111 assert(!KnownValid && "Explicit template arguments?");
10112 return;
10113 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010114 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
10115 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010116 return;
John McCalld14a8642009-11-21 08:51:07 +000010117 }
10118
10119 if (FunctionTemplateDecl *FuncTemplate
10120 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +000010121 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010122 ExplicitTemplateArgs, Args, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +000010123 return;
10124 }
10125
Richard Smith95ce4f62011-06-26 22:19:54 +000010126 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +000010127}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010128
Douglas Gregorcabea402009-09-22 15:41:20 +000010129/// \brief Add the overload candidates named by callee and/or found by argument
10130/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +000010131void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010132 ArrayRef<Expr *> Args,
Douglas Gregorcabea402009-09-22 15:41:20 +000010133 OverloadCandidateSet &CandidateSet,
10134 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +000010135
10136#ifndef NDEBUG
10137 // Verify that ArgumentDependentLookup is consistent with the rules
10138 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +000010139 //
Douglas Gregorcabea402009-09-22 15:41:20 +000010140 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10141 // and let Y be the lookup set produced by argument dependent
10142 // lookup (defined as follows). If X contains
10143 //
10144 // -- a declaration of a class member, or
10145 //
10146 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +000010147 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +000010148 //
10149 // -- a declaration that is neither a function or a function
10150 // template
10151 //
10152 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +000010153
John McCall57500772009-12-16 12:17:52 +000010154 if (ULE->requiresADL()) {
10155 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10156 E = ULE->decls_end(); I != E; ++I) {
10157 assert(!(*I)->getDeclContext()->isRecord());
10158 assert(isa<UsingShadowDecl>(*I) ||
10159 !(*I)->getDeclContext()->isFunctionOrMethod());
10160 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +000010161 }
10162 }
10163#endif
10164
John McCall57500772009-12-16 12:17:52 +000010165 // It would be nice to avoid this copy.
10166 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +000010167 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010168 if (ULE->hasExplicitTemplateArgs()) {
10169 ULE->copyTemplateArgumentsInto(TABuffer);
10170 ExplicitTemplateArgs = &TABuffer;
10171 }
10172
10173 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
10174 E = ULE->decls_end(); I != E; ++I)
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010175 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
10176 CandidateSet, PartialOverloading,
10177 /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +000010178
John McCall57500772009-12-16 12:17:52 +000010179 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +000010180 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithe06a2c12012-02-25 06:24:24 +000010181 ULE->getExprLoc(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010182 Args, ExplicitTemplateArgs,
Richard Smithb6626742012-10-18 17:56:02 +000010183 CandidateSet, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +000010184}
John McCalld681c392009-12-16 08:11:27 +000010185
Richard Smith0603bbb2013-06-12 22:56:54 +000010186/// Determine whether a declaration with the specified name could be moved into
10187/// a different namespace.
10188static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
10189 switch (Name.getCXXOverloadedOperator()) {
10190 case OO_New: case OO_Array_New:
10191 case OO_Delete: case OO_Array_Delete:
10192 return false;
10193
10194 default:
10195 return true;
10196 }
10197}
10198
Richard Smith998a5912011-06-05 22:42:48 +000010199/// Attempt to recover from an ill-formed use of a non-dependent name in a
10200/// template, where the non-dependent name was declared after the template
10201/// was defined. This is common in code written for a compilers which do not
10202/// correctly implement two-stage name lookup.
10203///
10204/// Returns true if a viable candidate was found and a diagnostic was issued.
10205static bool
10206DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
10207 const CXXScopeSpec &SS, LookupResult &R,
10208 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010209 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010210 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
10211 return false;
10212
10213 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewyckyfcd5e7a2012-03-14 20:41:00 +000010214 if (DC->isTransparentContext())
10215 continue;
10216
Richard Smith998a5912011-06-05 22:42:48 +000010217 SemaRef.LookupQualifiedName(R, DC);
10218
10219 if (!R.empty()) {
10220 R.suppressDiagnostics();
10221
10222 if (isa<CXXRecordDecl>(DC)) {
10223 // Don't diagnose names we find in classes; we get much better
10224 // diagnostics for these from DiagnoseEmptyLookup.
10225 R.clear();
10226 return false;
10227 }
10228
10229 OverloadCandidateSet Candidates(FnLoc);
10230 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
10231 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010232 ExplicitTemplateArgs, Args,
Richard Smith95ce4f62011-06-26 22:19:54 +000010233 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +000010234
10235 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +000010236 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +000010237 // No viable functions. Don't bother the user with notes for functions
10238 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +000010239 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +000010240 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +000010241 }
Richard Smith998a5912011-06-05 22:42:48 +000010242
10243 // Find the namespaces where ADL would have looked, and suggest
10244 // declaring the function there instead.
10245 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10246 Sema::AssociatedClassSet AssociatedClasses;
John McCall7d8b0412012-08-24 20:38:34 +000010247 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smith998a5912011-06-05 22:42:48 +000010248 AssociatedNamespaces,
10249 AssociatedClasses);
Chandler Carruthd50f1692011-06-05 23:36:55 +000010250 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith0603bbb2013-06-12 22:56:54 +000010251 if (canBeDeclaredInNamespace(R.getLookupName())) {
10252 DeclContext *Std = SemaRef.getStdNamespace();
10253 for (Sema::AssociatedNamespaceSet::iterator
10254 it = AssociatedNamespaces.begin(),
10255 end = AssociatedNamespaces.end(); it != end; ++it) {
10256 // Never suggest declaring a function within namespace 'std'.
10257 if (Std && Std->Encloses(*it))
10258 continue;
Richard Smith21bae432012-12-22 02:46:14 +000010259
Richard Smith0603bbb2013-06-12 22:56:54 +000010260 // Never suggest declaring a function within a namespace with a
10261 // reserved name, like __gnu_cxx.
10262 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
10263 if (NS &&
10264 NS->getQualifiedNameAsString().find("__") != std::string::npos)
10265 continue;
10266
10267 SuggestedNamespaces.insert(*it);
10268 }
Richard Smith998a5912011-06-05 22:42:48 +000010269 }
10270
10271 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
10272 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +000010273 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +000010274 SemaRef.Diag(Best->Function->getLocation(),
10275 diag::note_not_found_by_two_phase_lookup)
10276 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +000010277 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +000010278 SemaRef.Diag(Best->Function->getLocation(),
10279 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +000010280 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +000010281 } else {
10282 // FIXME: It would be useful to list the associated namespaces here,
10283 // but the diagnostics infrastructure doesn't provide a way to produce
10284 // a localized representation of a list of items.
10285 SemaRef.Diag(Best->Function->getLocation(),
10286 diag::note_not_found_by_two_phase_lookup)
10287 << R.getLookupName() << 2;
10288 }
10289
10290 // Try to recover by calling this function.
10291 return true;
10292 }
10293
10294 R.clear();
10295 }
10296
10297 return false;
10298}
10299
10300/// Attempt to recover from ill-formed use of a non-dependent operator in a
10301/// template, where the non-dependent operator was declared after the template
10302/// was defined.
10303///
10304/// Returns true if a viable candidate was found and a diagnostic was issued.
10305static bool
10306DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10307 SourceLocation OpLoc,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010308 ArrayRef<Expr *> Args) {
Richard Smith998a5912011-06-05 22:42:48 +000010309 DeclarationName OpName =
10310 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10311 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10312 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010313 /*ExplicitTemplateArgs=*/0, Args);
Richard Smith998a5912011-06-05 22:42:48 +000010314}
10315
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010316namespace {
Richard Smith88d67f32012-09-25 04:46:05 +000010317class BuildRecoveryCallExprRAII {
10318 Sema &SemaRef;
10319public:
10320 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10321 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10322 SemaRef.IsBuildingRecoveryCallExpr = true;
10323 }
10324
10325 ~BuildRecoveryCallExprRAII() {
10326 SemaRef.IsBuildingRecoveryCallExpr = false;
10327 }
10328};
10329
Kaelyn Uhrain8edb17d2012-01-25 18:37:44 +000010330}
10331
John McCalld681c392009-12-16 08:11:27 +000010332/// Attempts to recover from a call where no functions were found.
10333///
10334/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +000010335static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +000010336BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +000010337 UnresolvedLookupExpr *ULE,
10338 SourceLocation LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010339 llvm::MutableArrayRef<Expr *> Args,
Richard Smith998a5912011-06-05 22:42:48 +000010340 SourceLocation RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010341 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smith88d67f32012-09-25 04:46:05 +000010342 // Do not try to recover if it is already building a recovery call.
10343 // This stops infinite loops for template instantiations like
10344 //
10345 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10346 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10347 //
10348 if (SemaRef.IsBuildingRecoveryCallExpr)
10349 return ExprError();
10350 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCalld681c392009-12-16 08:11:27 +000010351
10352 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +000010353 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnara7945c982012-01-27 09:46:47 +000010354 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCalld681c392009-12-16 08:11:27 +000010355
John McCall57500772009-12-16 12:17:52 +000010356 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +000010357 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +000010358 if (ULE->hasExplicitTemplateArgs()) {
10359 ULE->copyTemplateArgumentsInto(TABuffer);
10360 ExplicitTemplateArgs = &TABuffer;
10361 }
10362
John McCalld681c392009-12-16 08:11:27 +000010363 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10364 Sema::LookupOrdinaryName);
Kaelyn Uhrain53e72192013-07-08 23:13:39 +000010365 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10366 ExplicitTemplateArgs != 0);
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010367 NoTypoCorrectionCCC RejectAll;
10368 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10369 (CorrectionCandidateCallback*)&Validator :
10370 (CorrectionCandidateCallback*)&RejectAll;
Richard Smith998a5912011-06-05 22:42:48 +000010371 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010372 ExplicitTemplateArgs, Args) &&
Richard Smith998a5912011-06-05 22:42:48 +000010373 (!EmptyLookup ||
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010374 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010375 ExplicitTemplateArgs, Args)))
John McCallfaf5fb42010-08-26 23:41:50 +000010376 return ExprError();
John McCalld681c392009-12-16 08:11:27 +000010377
John McCall57500772009-12-16 12:17:52 +000010378 assert(!R.empty() && "lookup results empty despite recovery");
10379
10380 // Build an implicit member call if appropriate. Just drop the
10381 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +000010382 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +000010383 if ((*R.begin())->isCXXClassMember())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010384 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10385 R, ExplicitTemplateArgs);
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010386 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnara7945c982012-01-27 09:46:47 +000010387 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +000010388 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +000010389 else
10390 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10391
10392 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +000010393 return ExprError();
John McCall57500772009-12-16 12:17:52 +000010394
10395 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +000010396 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +000010397 // end up here.
John McCallb268a282010-08-23 23:25:46 +000010398 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010399 MultiExprArg(Args.data(), Args.size()),
10400 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +000010401}
Douglas Gregor4038cf42010-06-08 17:35:15 +000010402
Sam Panzer0f384432012-08-21 00:52:01 +000010403/// \brief Constructs and populates an OverloadedCandidateSet from
10404/// the given function.
10405/// \returns true when an the ExprResult output parameter has been set.
10406bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10407 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010408 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010409 SourceLocation RParenLoc,
10410 OverloadCandidateSet *CandidateSet,
10411 ExprResult *Result) {
John McCall57500772009-12-16 12:17:52 +000010412#ifndef NDEBUG
10413 if (ULE->requiresADL()) {
10414 // To do ADL, we must have found an unqualified name.
10415 assert(!ULE->getQualifier() && "qualified name with ADL");
10416
10417 // We don't perform ADL for implicit declarations of builtins.
10418 // Verify that this was correctly set up.
10419 FunctionDecl *F;
10420 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10421 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10422 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +000010423 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010424
John McCall57500772009-12-16 12:17:52 +000010425 // We don't perform ADL in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010426 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb6626742012-10-18 17:56:02 +000010427 }
John McCall57500772009-12-16 12:17:52 +000010428#endif
10429
John McCall4124c492011-10-17 18:40:02 +000010430 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010431 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzer0f384432012-08-21 00:52:01 +000010432 *Result = ExprError();
10433 return true;
10434 }
Douglas Gregorb8a9a412009-02-04 15:01:18 +000010435
John McCall57500772009-12-16 12:17:52 +000010436 // Add the functions denoted by the callee to the set of candidate
10437 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010438 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCalld681c392009-12-16 08:11:27 +000010439
10440 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +000010441 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10442 // out if it fails.
Sam Panzer0f384432012-08-21 00:52:01 +000010443 if (CandidateSet->empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010444 // In Microsoft mode, if we are inside a template class member function then
10445 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +000010446 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010447 // classes.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010448 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +000010449 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010450 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramerc215e762012-08-24 11:54:20 +000010451 Context.DependentTy, VK_RValue,
10452 RParenLoc);
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010453 CE->setTypeDependent(true);
Sam Panzer0f384432012-08-21 00:52:01 +000010454 *Result = Owned(CE);
10455 return true;
Sebastian Redlb49c46c2011-09-24 17:48:00 +000010456 }
Sam Panzer0f384432012-08-21 00:52:01 +000010457 return false;
Francois Pichetbcf64712011-09-07 00:14:57 +000010458 }
John McCalld681c392009-12-16 08:11:27 +000010459
John McCall4124c492011-10-17 18:40:02 +000010460 UnbridgedCasts.restore();
Sam Panzer0f384432012-08-21 00:52:01 +000010461 return false;
10462}
John McCall4124c492011-10-17 18:40:02 +000010463
Sam Panzer0f384432012-08-21 00:52:01 +000010464/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10465/// the completed call expression. If overload resolution fails, emits
10466/// diagnostics and returns ExprError()
10467static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10468 UnresolvedLookupExpr *ULE,
10469 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010470 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010471 SourceLocation RParenLoc,
10472 Expr *ExecConfig,
10473 OverloadCandidateSet *CandidateSet,
10474 OverloadCandidateSet::iterator *Best,
10475 OverloadingResult OverloadResult,
10476 bool AllowTypoCorrection) {
10477 if (CandidateSet->empty())
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010478 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010479 RParenLoc, /*EmptyLookup=*/true,
10480 AllowTypoCorrection);
10481
10482 switch (OverloadResult) {
John McCall57500772009-12-16 12:17:52 +000010483 case OR_Success: {
Sam Panzer0f384432012-08-21 00:52:01 +000010484 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzer0f384432012-08-21 00:52:01 +000010485 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000010486 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10487 return ExprError();
Sam Panzer0f384432012-08-21 00:52:01 +000010488 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010489 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10490 ExecConfig);
John McCall57500772009-12-16 12:17:52 +000010491 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010492
Richard Smith998a5912011-06-05 22:42:48 +000010493 case OR_No_Viable_Function: {
10494 // Try to recover by looking for viable functions which the user might
10495 // have meant to call.
Sam Panzer0f384432012-08-21 00:52:01 +000010496 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010497 Args, RParenLoc,
Kaelyn Uhrain9afaf792012-01-25 21:11:35 +000010498 /*EmptyLookup=*/false,
10499 AllowTypoCorrection);
Richard Smith998a5912011-06-05 22:42:48 +000010500 if (!Recovery.isInvalid())
10501 return Recovery;
10502
Sam Panzer0f384432012-08-21 00:52:01 +000010503 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010504 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +000010505 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010506 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010507 break;
Richard Smith998a5912011-06-05 22:42:48 +000010508 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010509
10510 case OR_Ambiguous:
Sam Panzer0f384432012-08-21 00:52:01 +000010511 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +000010512 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010513 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010514 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000010515
Sam Panzer0f384432012-08-21 00:52:01 +000010516 case OR_Deleted: {
10517 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10518 << (*Best)->Function->isDeleted()
10519 << ULE->getName()
10520 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10521 << Fn->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010522 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +000010523
Sam Panzer0f384432012-08-21 00:52:01 +000010524 // We emitted an error for the unvailable/deleted function call but keep
10525 // the call in the AST.
10526 FunctionDecl *FDecl = (*Best)->Function;
10527 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010528 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10529 ExecConfig);
Sam Panzer0f384432012-08-21 00:52:01 +000010530 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010531 }
10532
Douglas Gregorb412e172010-07-25 18:17:45 +000010533 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +000010534 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +000010535}
10536
Sam Panzer0f384432012-08-21 00:52:01 +000010537/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10538/// (which eventually refers to the declaration Func) and the call
10539/// arguments Args/NumArgs, attempt to resolve the function call down
10540/// to a specific function. If overload resolution succeeds, returns
10541/// the call expression produced by overload resolution.
10542/// Otherwise, emits diagnostics and returns ExprError.
10543ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10544 UnresolvedLookupExpr *ULE,
10545 SourceLocation LParenLoc,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010546 MultiExprArg Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010547 SourceLocation RParenLoc,
10548 Expr *ExecConfig,
10549 bool AllowTypoCorrection) {
10550 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10551 ExprResult result;
10552
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010553 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10554 &result))
Sam Panzer0f384432012-08-21 00:52:01 +000010555 return result;
10556
10557 OverloadCandidateSet::iterator Best;
10558 OverloadingResult OverloadResult =
10559 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10560
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000010561 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzer0f384432012-08-21 00:52:01 +000010562 RParenLoc, ExecConfig, &CandidateSet,
10563 &Best, OverloadResult,
10564 AllowTypoCorrection);
10565}
10566
John McCall4c4c1df2010-01-26 03:27:55 +000010567static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +000010568 return Functions.size() > 1 ||
10569 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10570}
10571
Douglas Gregor084d8552009-03-13 23:49:33 +000010572/// \brief Create a unary operation that may resolve to an overloaded
10573/// operator.
10574///
10575/// \param OpLoc The location of the operator itself (e.g., '*').
10576///
10577/// \param OpcIn The UnaryOperator::Opcode that describes this
10578/// operator.
10579///
James Dennett18348b62012-06-22 08:52:37 +000010580/// \param Fns The set of non-member functions that will be
Douglas Gregor084d8552009-03-13 23:49:33 +000010581/// considered by overload resolution. The caller needs to build this
10582/// set based on the context using, e.g.,
10583/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10584/// set should not contain any member functions; those will be added
10585/// by CreateOverloadedUnaryOp().
10586///
James Dennett91738ff2012-06-22 10:32:46 +000010587/// \param Input The input argument.
John McCalldadc5752010-08-24 06:29:42 +000010588ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +000010589Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10590 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +000010591 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010592 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +000010593
10594 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10595 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10596 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010597 // TODO: provide better source location info.
10598 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010599
John McCall4124c492011-10-17 18:40:02 +000010600 if (checkPlaceholderForOverload(*this, Input))
10601 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010602
Douglas Gregor084d8552009-03-13 23:49:33 +000010603 Expr *Args[2] = { Input, 0 };
10604 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +000010605
Douglas Gregor084d8552009-03-13 23:49:33 +000010606 // For post-increment and post-decrement, add the implicit '0' as
10607 // the second argument, so that we know this is a post-increment or
10608 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +000010609 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010610 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +000010611 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10612 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +000010613 NumArgs = 2;
10614 }
10615
Richard Smithe54c3072013-05-05 15:51:06 +000010616 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10617
Douglas Gregor084d8552009-03-13 23:49:33 +000010618 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +000010619 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +000010620 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010621 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +000010622 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010623 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +000010624 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010625
John McCall58cc69d2010-01-27 01:50:18 +000010626 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +000010627 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000010628 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000010629 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010630 /*ADL*/ true, IsOverloaded(Fns),
10631 Fns.begin(), Fns.end());
Richard Smithe54c3072013-05-05 15:51:06 +000010632 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregor084d8552009-03-13 23:49:33 +000010633 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010634 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000010635 OpLoc, false));
Douglas Gregor084d8552009-03-13 23:49:33 +000010636 }
10637
10638 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010639 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +000010640
10641 // Add the candidates from the given function set.
Richard Smithe54c3072013-05-05 15:51:06 +000010642 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +000010643
10644 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010645 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010646
John McCall4c4c1df2010-01-26 03:27:55 +000010647 // Add candidates from ADL.
Richard Smithe54c3072013-05-05 15:51:06 +000010648 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10649 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall4c4c1df2010-01-26 03:27:55 +000010650 CandidateSet);
10651
Douglas Gregor084d8552009-03-13 23:49:33 +000010652 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010653 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +000010654
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010655 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10656
Douglas Gregor084d8552009-03-13 23:49:33 +000010657 // Perform overload resolution.
10658 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010659 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +000010660 case OR_Success: {
10661 // We found a built-in operator or an overloaded operator.
10662 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +000010663
Douglas Gregor084d8552009-03-13 23:49:33 +000010664 if (FnDecl) {
10665 // We matched an overloaded operator. Build a call to that
10666 // operator.
Mike Stump11289f42009-09-09 15:08:12 +000010667
Douglas Gregor084d8552009-03-13 23:49:33 +000010668 // Convert the arguments.
10669 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +000010670 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010671
John Wiegley01296292011-04-08 18:41:53 +000010672 ExprResult InputRes =
10673 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10674 Best->FoundDecl, Method);
10675 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010676 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010677 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010678 } else {
10679 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000010680 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +000010681 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010682 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +000010683 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010684 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +000010685 Input);
Douglas Gregore6600372009-12-23 17:40:29 +000010686 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +000010687 return ExprError();
John McCallb268a282010-08-23 23:25:46 +000010688 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010689 }
10690
Douglas Gregor084d8552009-03-13 23:49:33 +000010691 // Build the actual expression node.
Nick Lewycky134af912013-02-07 05:08:22 +000010692 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000010693 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010694 if (FnExpr.isInvalid())
10695 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +000010696
Richard Smithc1564702013-11-15 02:58:23 +000010697 // Determine the result type.
10698 QualType ResultTy = FnDecl->getResultType();
10699 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10700 ResultTy = ResultTy.getNonLValueExprType(Context);
10701
Eli Friedman030eee42009-11-18 03:58:17 +000010702 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +000010703 CallExpr *TheCall =
Richard Smithe54c3072013-05-05 15:51:06 +000010704 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hames5de91cc2012-10-02 04:45:10 +000010705 ResultTy, VK, OpLoc, false);
John McCall4fa0d5f2010-05-06 18:15:07 +000010706
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010707 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +000010708 FnDecl))
10709 return ExprError();
10710
John McCallb268a282010-08-23 23:25:46 +000010711 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +000010712 } else {
10713 // We matched a built-in operator. Convert the arguments, then
10714 // break out so that we will build the appropriate built-in
10715 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010716 ExprResult InputRes =
10717 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10718 Best->Conversions[0], AA_Passing);
10719 if (InputRes.isInvalid())
10720 return ExprError();
10721 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +000010722 break;
Douglas Gregor084d8552009-03-13 23:49:33 +000010723 }
John Wiegley01296292011-04-08 18:41:53 +000010724 }
10725
10726 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +000010727 // This is an erroneous use of an operator which can be overloaded by
10728 // a non-member function. Check for non-member operators which were
10729 // defined too late to be candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010730 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smith998a5912011-06-05 22:42:48 +000010731 // FIXME: Recover by calling the found function.
10732 return ExprError();
10733
John Wiegley01296292011-04-08 18:41:53 +000010734 // No viable function; fall through to handling this as a
10735 // built-in operator, which will produce an error message for us.
10736 break;
10737
10738 case OR_Ambiguous:
10739 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10740 << UnaryOperator::getOpcodeStr(Opc)
10741 << Input->getType()
10742 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010743 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley01296292011-04-08 18:41:53 +000010744 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10745 return ExprError();
10746
10747 case OR_Deleted:
10748 Diag(OpLoc, diag::err_ovl_deleted_oper)
10749 << Best->Function->isDeleted()
10750 << UnaryOperator::getOpcodeStr(Opc)
10751 << getDeletedOrUnavailableSuffix(Best->Function)
10752 << Input->getSourceRange();
Richard Smithe54c3072013-05-05 15:51:06 +000010753 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000010754 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010755 return ExprError();
10756 }
Douglas Gregor084d8552009-03-13 23:49:33 +000010757
10758 // Either we found no viable overloaded operator or we matched a
10759 // built-in operator. In either case, fall through to trying to
10760 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +000010761 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +000010762}
10763
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010764/// \brief Create a binary operation that may resolve to an overloaded
10765/// operator.
10766///
10767/// \param OpLoc The location of the operator itself (e.g., '+').
10768///
10769/// \param OpcIn The BinaryOperator::Opcode that describes this
10770/// operator.
10771///
James Dennett18348b62012-06-22 08:52:37 +000010772/// \param Fns The set of non-member functions that will be
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010773/// considered by overload resolution. The caller needs to build this
10774/// set based on the context using, e.g.,
10775/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10776/// set should not contain any member functions; those will be added
10777/// by CreateOverloadedBinOp().
10778///
10779/// \param LHS Left-hand argument.
10780/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +000010781ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010782Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +000010783 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +000010784 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010785 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010786 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +000010787 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010788
10789 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10790 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10791 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10792
10793 // If either side is type-dependent, create an appropriate dependent
10794 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +000010795 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +000010796 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010797 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +000010798 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +000010799 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +000010800 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +000010801 Context.DependentTy,
10802 VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +000010803 OpLoc,
10804 FPFeatures.fp_contract));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010805
Douglas Gregor5287f092009-11-05 00:51:44 +000010806 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10807 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000010808 VK_LValue,
10809 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +000010810 Context.DependentTy,
10811 Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +000010812 OpLoc,
10813 FPFeatures.fp_contract));
Douglas Gregor5287f092009-11-05 00:51:44 +000010814 }
John McCall4c4c1df2010-01-26 03:27:55 +000010815
10816 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +000010817 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000010818 // TODO: provide better source location info in DNLoc component.
10819 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +000010820 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +000010821 = UnresolvedLookupExpr::Create(Context, NamingClass,
10822 NestedNameSpecifierLoc(), OpNameInfo,
10823 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000010824 Fns.begin(), Fns.end());
Lang Hames5de91cc2012-10-02 04:45:10 +000010825 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10826 Context.DependentTy, VK_RValue,
10827 OpLoc, FPFeatures.fp_contract));
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010828 }
10829
John McCall4124c492011-10-17 18:40:02 +000010830 // Always do placeholder-like conversions on the RHS.
10831 if (checkPlaceholderForOverload(*this, Args[1]))
10832 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010833
John McCall526ab472011-10-25 17:37:35 +000010834 // Do placeholder-like conversion on the LHS; note that we should
10835 // not get here with a PseudoObject LHS.
10836 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +000010837 if (checkPlaceholderForOverload(*this, Args[0]))
10838 return ExprError();
10839
Sebastian Redl6a96bf72009-11-18 23:10:33 +000010840 // If this is the assignment operator, we only perform overload resolution
10841 // if the left-hand side is a class or enumeration type. This is actually
10842 // a hack. The standard requires that we do overload resolution between the
10843 // various built-in candidates, but as DR507 points out, this can lead to
10844 // problems. So we do it this way, which pretty much follows what GCC does.
10845 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +000010846 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +000010847 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010848
John McCalle26a8722010-12-04 08:14:53 +000010849 // If this is the .* operator, which is not overloadable, just
10850 // create a built-in binary operator.
10851 if (Opc == BO_PtrMemD)
10852 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10853
Douglas Gregor084d8552009-03-13 23:49:33 +000010854 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000010855 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010856
10857 // Add the candidates from the given function set.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010858 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010859
10860 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000010861 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010862
John McCall4c4c1df2010-01-26 03:27:55 +000010863 // Add candidates from ADL.
10864 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000010865 OpLoc, Args,
John McCall4c4c1df2010-01-26 03:27:55 +000010866 /*ExplicitTemplateArgs*/ 0,
10867 CandidateSet);
10868
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010869 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000010870 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010871
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010872 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10873
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010874 // Perform overload resolution.
10875 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010876 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +000010877 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010878 // We found a built-in operator or an overloaded operator.
10879 FunctionDecl *FnDecl = Best->Function;
10880
10881 if (FnDecl) {
10882 // We matched an overloaded operator. Build a call to that
10883 // operator.
10884
10885 // Convert the arguments.
10886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +000010887 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +000010888 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +000010889
Chandler Carruth8e543b32010-12-12 08:17:55 +000010890 ExprResult Arg1 =
10891 PerformCopyInitialization(
10892 InitializedEntity::InitializeParameter(Context,
10893 FnDecl->getParamDecl(0)),
10894 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010895 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010896 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010897
John Wiegley01296292011-04-08 18:41:53 +000010898 ExprResult Arg0 =
10899 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10900 Best->FoundDecl, Method);
10901 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010902 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010903 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010904 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010905 } else {
10906 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +000010907 ExprResult Arg0 = PerformCopyInitialization(
10908 InitializedEntity::InitializeParameter(Context,
10909 FnDecl->getParamDecl(0)),
10910 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010911 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010912 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010913
Chandler Carruth8e543b32010-12-12 08:17:55 +000010914 ExprResult Arg1 =
10915 PerformCopyInitialization(
10916 InitializedEntity::InitializeParameter(Context,
10917 FnDecl->getParamDecl(1)),
10918 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000010919 if (Arg1.isInvalid())
10920 return ExprError();
10921 Args[0] = LHS = Arg0.takeAs<Expr>();
10922 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010923 }
10924
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010925 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010926 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000010927 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010928 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000010929 if (FnExpr.isInvalid())
10930 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010931
Richard Smithc1564702013-11-15 02:58:23 +000010932 // Determine the result type.
10933 QualType ResultTy = FnDecl->getResultType();
10934 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10935 ResultTy = ResultTy.getNonLValueExprType(Context);
10936
John McCallb268a282010-08-23 23:25:46 +000010937 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010938 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000010939 Args, ResultTy, VK, OpLoc,
10940 FPFeatures.fp_contract);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010941
10942 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010943 FnDecl))
10944 return ExprError();
10945
Nick Lewyckyd24d5f22013-01-24 02:03:08 +000010946 ArrayRef<const Expr *> ArgsArray(Args, 2);
10947 // Cut off the implicit 'this'.
10948 if (isa<CXXMethodDecl>(FnDecl))
10949 ArgsArray = ArgsArray.slice(1);
10950 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10951 TheCall->getSourceRange(), VariadicDoesNotApply);
10952
John McCallb268a282010-08-23 23:25:46 +000010953 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010954 } else {
10955 // We matched a built-in operator. Convert the arguments, then
10956 // break out so that we will build the appropriate built-in
10957 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000010958 ExprResult ArgsRes0 =
10959 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10960 Best->Conversions[0], AA_Passing);
10961 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010962 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010963 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010964
John Wiegley01296292011-04-08 18:41:53 +000010965 ExprResult ArgsRes1 =
10966 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10967 Best->Conversions[1], AA_Passing);
10968 if (ArgsRes1.isInvalid())
10969 return ExprError();
10970 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +000010971 break;
10972 }
10973 }
10974
Douglas Gregor66950a32009-09-30 21:46:01 +000010975 case OR_No_Viable_Function: {
10976 // C++ [over.match.oper]p9:
10977 // If the operator is the operator , [...] and there are no
10978 // viable functions, then the operator is assumed to be the
10979 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +000010980 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +000010981 break;
10982
Chandler Carruth8e543b32010-12-12 08:17:55 +000010983 // For class as left operand for assignment or compound assigment
10984 // operator do not fall through to handling in built-in, but report that
10985 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +000010986 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010987 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +000010988 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +000010989 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10990 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +000010991 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedmana31efa02013-08-28 20:35:35 +000010992 if (Args[0]->getType()->isIncompleteType()) {
10993 Diag(OpLoc, diag::note_assign_lhs_incomplete)
10994 << Args[0]->getType()
10995 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10996 }
Douglas Gregor66950a32009-09-30 21:46:01 +000010997 } else {
Richard Smith998a5912011-06-05 22:42:48 +000010998 // This is an erroneous use of an operator which can be overloaded by
10999 // a non-member function. Check for non-member operators which were
11000 // defined too late to be candidates.
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011001 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smith998a5912011-06-05 22:42:48 +000011002 // FIXME: Recover by calling the found function.
11003 return ExprError();
11004
Douglas Gregor66950a32009-09-30 21:46:01 +000011005 // No viable function; try to create a built-in operation, which will
11006 // produce an error. Then, show the non-viable candidates.
11007 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +000011008 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011009 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +000011010 "C++ binary operator overloading is missing candidates!");
11011 if (Result.isInvalid())
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011012 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011013 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011014 return Result;
Douglas Gregor66950a32009-09-30 21:46:01 +000011015 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011016
11017 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011018 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011019 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +000011020 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +000011021 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011022 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011023 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011024 return ExprError();
11025
11026 case OR_Deleted:
Douglas Gregor74f7d502012-02-15 19:33:52 +000011027 if (isImplicitlyDeleted(Best->Function)) {
11028 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
11029 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smithde1a4872012-12-28 12:23:24 +000011030 << Context.getRecordType(Method->getParent())
11031 << getSpecialMember(Method);
Richard Smith6f1e2c62012-04-02 20:59:25 +000011032
Richard Smithde1a4872012-12-28 12:23:24 +000011033 // The user probably meant to call this special member. Just
11034 // explain why it's deleted.
11035 NoteDeletedFunction(Method);
11036 return ExprError();
Douglas Gregor74f7d502012-02-15 19:33:52 +000011037 } else {
11038 Diag(OpLoc, diag::err_ovl_deleted_oper)
11039 << Best->Function->isDeleted()
11040 << BinaryOperator::getOpcodeStr(Opc)
11041 << getDeletedOrUnavailableSuffix(Best->Function)
11042 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11043 }
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011044 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman79b2d3a2011-08-26 19:46:22 +000011045 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011046 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +000011047 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011048
Douglas Gregor66950a32009-09-30 21:46:01 +000011049 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +000011050 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +000011051}
11052
John McCalldadc5752010-08-24 06:29:42 +000011053ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +000011054Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
11055 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +000011056 Expr *Base, Expr *Idx) {
11057 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +000011058 DeclarationName OpName =
11059 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
11060
11061 // If either side is type-dependent, create an appropriate dependent
11062 // expression.
11063 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
11064
John McCall58cc69d2010-01-27 01:50:18 +000011065 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +000011066 // CHECKME: no 'operator' keyword?
11067 DeclarationNameInfo OpNameInfo(OpName, LLoc);
11068 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +000011069 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +000011070 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +000011071 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +000011072 /*ADL*/ true, /*Overloaded*/ false,
11073 UnresolvedSetIterator(),
11074 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +000011075 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +000011076
Sebastian Redladba46e2009-10-29 20:17:01 +000011077 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011078 Args,
Sebastian Redladba46e2009-10-29 20:17:01 +000011079 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +000011080 VK_RValue,
Lang Hames5de91cc2012-10-02 04:45:10 +000011081 RLoc, false));
Sebastian Redladba46e2009-10-29 20:17:01 +000011082 }
11083
John McCall4124c492011-10-17 18:40:02 +000011084 // Handle placeholders on both operands.
11085 if (checkPlaceholderForOverload(*this, Args[0]))
11086 return ExprError();
11087 if (checkPlaceholderForOverload(*this, Args[1]))
11088 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011089
Sebastian Redladba46e2009-10-29 20:17:01 +000011090 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +000011091 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011092
11093 // Subscript can only be overloaded as a member function.
11094
11095 // Add operator candidates that are member functions.
Richard Smithe54c3072013-05-05 15:51:06 +000011096 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011097
11098 // Add builtin operator candidates.
Richard Smithe54c3072013-05-05 15:51:06 +000011099 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redladba46e2009-10-29 20:17:01 +000011100
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011101 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11102
Sebastian Redladba46e2009-10-29 20:17:01 +000011103 // Perform overload resolution.
11104 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011105 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +000011106 case OR_Success: {
11107 // We found a built-in operator or an overloaded operator.
11108 FunctionDecl *FnDecl = Best->Function;
11109
11110 if (FnDecl) {
11111 // We matched an overloaded operator. Build a call to that
11112 // operator.
11113
John McCalla0296f72010-03-19 07:35:19 +000011114 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall58cc69d2010-01-27 01:50:18 +000011115
Sebastian Redladba46e2009-10-29 20:17:01 +000011116 // Convert the arguments.
11117 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +000011118 ExprResult Arg0 =
11119 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
11120 Best->FoundDecl, Method);
11121 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011122 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011123 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011124
Anders Carlssona68e51e2010-01-29 18:37:50 +000011125 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +000011126 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +000011127 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011128 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +000011129 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011130 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +000011131 Owned(Args[1]));
11132 if (InputInit.isInvalid())
11133 return ExprError();
11134
11135 Args[1] = InputInit.takeAs<Expr>();
11136
Sebastian Redladba46e2009-10-29 20:17:01 +000011137 // Build the actual expression node.
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011138 DeclarationNameInfo OpLocInfo(OpName, LLoc);
11139 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011140 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewycky134af912013-02-07 05:08:22 +000011141 Best->FoundDecl,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011142 HadMultipleCandidates,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011143 OpLocInfo.getLoc(),
11144 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011145 if (FnExpr.isInvalid())
11146 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011147
Richard Smithc1564702013-11-15 02:58:23 +000011148 // Determine the result type
11149 QualType ResultTy = FnDecl->getResultType();
11150 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11151 ResultTy = ResultTy.getNonLValueExprType(Context);
11152
John McCallb268a282010-08-23 23:25:46 +000011153 CXXOperatorCallExpr *TheCall =
11154 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramerc215e762012-08-24 11:54:20 +000011155 FnExpr.take(), Args,
Lang Hames5de91cc2012-10-02 04:45:10 +000011156 ResultTy, VK, RLoc,
11157 false);
Sebastian Redladba46e2009-10-29 20:17:01 +000011158
John McCallb268a282010-08-23 23:25:46 +000011159 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +000011160 FnDecl))
11161 return ExprError();
11162
John McCallb268a282010-08-23 23:25:46 +000011163 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +000011164 } else {
11165 // We matched a built-in operator. Convert the arguments, then
11166 // break out so that we will build the appropriate built-in
11167 // operator node.
John Wiegley01296292011-04-08 18:41:53 +000011168 ExprResult ArgsRes0 =
11169 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
11170 Best->Conversions[0], AA_Passing);
11171 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +000011172 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011173 Args[0] = ArgsRes0.take();
11174
11175 ExprResult ArgsRes1 =
11176 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
11177 Best->Conversions[1], AA_Passing);
11178 if (ArgsRes1.isInvalid())
11179 return ExprError();
11180 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +000011181
11182 break;
11183 }
11184 }
11185
11186 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +000011187 if (CandidateSet.empty())
11188 Diag(LLoc, diag::err_ovl_no_oper)
11189 << Args[0]->getType() << /*subscript*/ 0
11190 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
11191 else
11192 Diag(LLoc, diag::err_ovl_no_viable_subscript)
11193 << Args[0]->getType()
11194 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011195 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011196 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +000011197 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +000011198 }
11199
11200 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011201 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011202 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +000011203 << Args[0]->getType() << Args[1]->getType()
11204 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011205 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011206 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011207 return ExprError();
11208
11209 case OR_Deleted:
11210 Diag(LLoc, diag::err_ovl_deleted_oper)
11211 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011212 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +000011213 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011214 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall5c32be02010-08-24 20:38:10 +000011215 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011216 return ExprError();
11217 }
11218
11219 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +000011220 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +000011221}
11222
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011223/// BuildCallToMemberFunction - Build a call to a member
11224/// function. MemExpr is the expression that refers to the member
11225/// function (and includes the object parameter), Args/NumArgs are the
11226/// arguments to the function call (not including the object
11227/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +000011228/// expression refers to a non-static member function or an overloaded
11229/// member function.
John McCalldadc5752010-08-24 06:29:42 +000011230ExprResult
Mike Stump11289f42009-09-09 15:08:12 +000011231Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011232 SourceLocation LParenLoc,
11233 MultiExprArg Args,
11234 SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +000011235 assert(MemExprE->getType() == Context.BoundMemberTy ||
11236 MemExprE->getType() == Context.OverloadTy);
11237
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011238 // Dig out the member expression. This holds both the object
11239 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +000011240 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011241
John McCall0009fcc2011-04-26 20:42:42 +000011242 // Determine whether this is a call to a pointer-to-member function.
11243 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
11244 assert(op->getType() == Context.BoundMemberTy);
11245 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
11246
11247 QualType fnType =
11248 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
11249
11250 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
11251 QualType resultType = proto->getCallResultType(Context);
11252 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
11253
11254 // Check that the object type isn't more qualified than the
11255 // member function we're calling.
11256 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
11257
11258 QualType objectType = op->getLHS()->getType();
11259 if (op->getOpcode() == BO_PtrMemI)
11260 objectType = objectType->castAs<PointerType>()->getPointeeType();
11261 Qualifiers objectQuals = objectType.getQualifiers();
11262
11263 Qualifiers difference = objectQuals - funcQuals;
11264 difference.removeObjCGCAttr();
11265 difference.removeAddressSpace();
11266 if (difference) {
11267 std::string qualsString = difference.getAsString();
11268 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
11269 << fnType.getUnqualifiedType()
11270 << qualsString
11271 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
11272 }
Nick Lewycky35a6ef42014-01-11 02:50:57 +000011273
John McCall0009fcc2011-04-26 20:42:42 +000011274 CXXMemberCallExpr *call
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011275 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall0009fcc2011-04-26 20:42:42 +000011276 resultType, valueKind, RParenLoc);
11277
11278 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011279 op->getRHS()->getLocStart(),
John McCall0009fcc2011-04-26 20:42:42 +000011280 call, 0))
11281 return ExprError();
11282
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011283 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall0009fcc2011-04-26 20:42:42 +000011284 return ExprError();
11285
Richard Trieu9be9c682013-06-22 02:30:38 +000011286 if (CheckOtherCall(call, proto))
11287 return ExprError();
11288
John McCall0009fcc2011-04-26 20:42:42 +000011289 return MaybeBindToTemporary(call);
11290 }
11291
John McCall4124c492011-10-17 18:40:02 +000011292 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011293 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011294 return ExprError();
11295
John McCall10eae182009-11-30 22:42:35 +000011296 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011297 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +000011298 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011299 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +000011300 if (isa<MemberExpr>(NakedMemExpr)) {
11301 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +000011302 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +000011303 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011304 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +000011305 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +000011306 } else {
11307 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +000011308 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011309
John McCall6e9f8f62009-12-03 04:06:58 +000011310 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +000011311 Expr::Classification ObjectClassification
11312 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11313 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +000011314
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011315 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +000011316 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +000011317
John McCall2d74de92009-12-01 22:10:20 +000011318 // FIXME: avoid copy.
11319 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11320 if (UnresExpr->hasExplicitTemplateArgs()) {
11321 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11322 TemplateArgs = &TemplateArgsBuffer;
11323 }
11324
John McCall10eae182009-11-30 22:42:35 +000011325 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11326 E = UnresExpr->decls_end(); I != E; ++I) {
11327
John McCall6e9f8f62009-12-03 04:06:58 +000011328 NamedDecl *Func = *I;
11329 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11330 if (isa<UsingShadowDecl>(Func))
11331 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11332
Douglas Gregor02824322011-01-26 19:30:28 +000011333
Francois Pichet64225792011-01-18 05:04:39 +000011334 // Microsoft supports direct constructor calls.
David Blaikiebbafb8a2012-03-11 07:00:24 +000011335 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011336 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011337 Args, CandidateSet);
Francois Pichet64225792011-01-18 05:04:39 +000011338 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +000011339 // If explicit template arguments were provided, we can't call a
11340 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +000011341 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +000011342 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011343
John McCalla0296f72010-03-19 07:35:19 +000011344 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011345 ObjectClassification, Args, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +000011346 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011347 } else {
John McCall10eae182009-11-30 22:42:35 +000011348 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +000011349 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011350 ObjectType, ObjectClassification,
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011351 Args, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011352 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +000011353 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +000011354 }
Mike Stump11289f42009-09-09 15:08:12 +000011355
John McCall10eae182009-11-30 22:42:35 +000011356 DeclarationName DeclName = UnresExpr->getMemberName();
11357
John McCall4124c492011-10-17 18:40:02 +000011358 UnbridgedCasts.restore();
11359
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011360 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011361 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +000011362 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011363 case OR_Success:
11364 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +000011365 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +000011366 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011367 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11368 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011369 // If FoundDecl is different from Method (such as if one is a template
11370 // and the other a specialization), make sure DiagnoseUseOfDecl is
11371 // called on both.
11372 // FIXME: This would be more comprehensively addressed by modifying
11373 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11374 // being used.
11375 if (Method != FoundDecl.getDecl() &&
11376 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11377 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011378 break;
11379
11380 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +000011381 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011382 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011383 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011384 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011385 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011386 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011387
11388 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +000011389 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +000011390 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011391 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011392 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011393 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011394
11395 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +000011396 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +000011397 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011398 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011399 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011400 << MemExprE->getSourceRange();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011401 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011402 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +000011403 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011404 }
11405
John McCall16df1e52010-03-30 21:47:33 +000011406 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +000011407
John McCall2d74de92009-12-01 22:10:20 +000011408 // If overload resolution picked a static member, build a
11409 // non-member call based on that function.
11410 if (Method->isStatic()) {
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011411 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11412 RParenLoc);
John McCall2d74de92009-12-01 22:10:20 +000011413 }
11414
John McCall10eae182009-11-30 22:42:35 +000011415 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011416 }
11417
John McCall7decc9e2010-11-18 06:31:45 +000011418 QualType ResultType = Method->getResultType();
11419 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11420 ResultType = ResultType.getNonLValueExprType(Context);
11421
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011422 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011423 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011424 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall7decc9e2010-11-18 06:31:45 +000011425 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011426
Anders Carlssonc4859ba2009-10-10 00:06:20 +000011427 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011428 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +000011429 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +000011430 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011431
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011432 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +000011433 // We only need to do this if there was actually an overload; otherwise
11434 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +000011435 if (!Method->isStatic()) {
11436 ExprResult ObjectArg =
11437 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11438 FoundDecl, Method);
11439 if (ObjectArg.isInvalid())
11440 return ExprError();
11441 MemExpr->setBase(ObjectArg.take());
11442 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011443
11444 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +000011445 const FunctionProtoType *Proto =
11446 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011447 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011448 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +000011449 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011450
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011451 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011452
Richard Smith55ce3522012-06-25 20:30:08 +000011453 if (CheckFunctionCall(Method, TheCall, Proto))
John McCall2d74de92009-12-01 22:10:20 +000011454 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +000011455
Anders Carlsson47061ee2011-05-06 14:25:31 +000011456 if ((isa<CXXConstructorDecl>(CurContext) ||
11457 isa<CXXDestructorDecl>(CurContext)) &&
11458 TheCall->getMethodDecl()->isPure()) {
11459 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11460
Chandler Carruth59259262011-06-27 08:31:58 +000011461 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +000011462 Diag(MemExpr->getLocStart(),
11463 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11464 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11465 << MD->getParent()->getDeclName();
11466
11467 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +000011468 }
Anders Carlsson47061ee2011-05-06 14:25:31 +000011469 }
John McCallb268a282010-08-23 23:25:46 +000011470 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +000011471}
11472
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011473/// BuildCallToObjectOfClassType - Build a call to an object of class
11474/// type (C++ [over.call.object]), which can end up invoking an
11475/// overloaded function call operator (@c operator()) or performing a
11476/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +000011477ExprResult
John Wiegley01296292011-04-08 18:41:53 +000011478Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +000011479 SourceLocation LParenLoc,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011480 MultiExprArg Args,
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011481 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +000011482 if (checkPlaceholderForOverload(*this, Obj))
11483 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011484 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +000011485
11486 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011487 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall4124c492011-10-17 18:40:02 +000011488 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011489
John Wiegley01296292011-04-08 18:41:53 +000011490 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11491 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +000011492
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011493 // C++ [over.call.object]p1:
11494 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +000011495 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011496 // candidate functions includes at least the function call
11497 // operators of T. The function call operators of T are obtained by
11498 // ordinary lookup of the name operator() in the context of
11499 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +000011500 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +000011501 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011502
John Wiegley01296292011-04-08 18:41:53 +000011503 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011504 diag::err_incomplete_object_call, Object.get()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011505 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011506
John McCall27b18f82009-11-17 02:14:36 +000011507 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11508 LookupQualifiedName(R, Record->getDecl());
11509 R.suppressDiagnostics();
11510
Douglas Gregorc473cbb2009-11-15 07:48:03 +000011511 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +000011512 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +000011513 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011514 Object.get()->Classify(Context),
11515 Args, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +000011516 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +000011517 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011518
Douglas Gregorab7897a2008-11-19 22:57:39 +000011519 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011520 // In addition, for each (non-explicit in C++0x) conversion function
11521 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +000011522 //
11523 // operator conversion-type-id () cv-qualifier;
11524 //
11525 // where cv-qualifier is the same cv-qualification as, or a
11526 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +000011527 // denotes the type "pointer to function of (P1,...,Pn) returning
11528 // R", or the type "reference to pointer to function of
11529 // (P1,...,Pn) returning R", or the type "reference to function
11530 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +000011531 // is also considered as a candidate function. Similarly,
11532 // surrogate call functions are added to the set of candidate
11533 // functions for each conversion function declared in an
11534 // accessible base class provided the function is not hidden
11535 // within T by another intervening declaration.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011536 std::pair<CXXRecordDecl::conversion_iterator,
11537 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor21591822010-01-11 19:36:35 +000011538 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +000011539 for (CXXRecordDecl::conversion_iterator
11540 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +000011541 NamedDecl *D = *I;
11542 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11543 if (isa<UsingShadowDecl>(D))
11544 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011545
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011546 // Skip over templated conversion functions; they aren't
11547 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +000011548 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +000011549 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +000011550
John McCall6e9f8f62009-12-03 04:06:58 +000011551 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011552 if (!Conv->isExplicit()) {
11553 // Strip the reference type (if any) and then the pointer type (if
11554 // any) to get down to what might be a function type.
11555 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11556 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11557 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +000011558
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011559 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11560 {
11561 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011562 Object.get(), Args, CandidateSet);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +000011563 }
11564 }
Douglas Gregorab7897a2008-11-19 22:57:39 +000011565 }
Mike Stump11289f42009-09-09 15:08:12 +000011566
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011567 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11568
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011569 // Perform overload resolution.
11570 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +000011571 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +000011572 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011573 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +000011574 // Overload resolution succeeded; we'll build the appropriate call
11575 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011576 break;
11577
11578 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +000011579 if (CandidateSet.empty())
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011580 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley01296292011-04-08 18:41:53 +000011581 << Object.get()->getType() << /*call*/ 1
11582 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +000011583 else
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011584 Diag(Object.get()->getLocStart(),
John McCall02374852010-01-07 02:04:15 +000011585 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011586 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011587 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011588 break;
11589
11590 case OR_Ambiguous:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011591 Diag(Object.get()->getLocStart(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011592 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +000011593 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011594 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011595 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +000011596
11597 case OR_Deleted:
Daniel Dunbar62ee6412012-03-09 18:35:03 +000011598 Diag(Object.get()->getLocStart(),
Douglas Gregor171c45a2009-02-18 21:56:37 +000011599 diag::err_ovl_deleted_object_call)
11600 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +000011601 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011602 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +000011603 << Object.get()->getSourceRange();
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011604 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor171c45a2009-02-18 21:56:37 +000011605 break;
Mike Stump11289f42009-09-09 15:08:12 +000011606 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011607
Douglas Gregorb412e172010-07-25 18:17:45 +000011608 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011609 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011610
John McCall4124c492011-10-17 18:40:02 +000011611 UnbridgedCasts.restore();
11612
Douglas Gregorab7897a2008-11-19 22:57:39 +000011613 if (Best->Function == 0) {
11614 // Since there is no function declaration, this is one of the
11615 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +000011616 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +000011617 = cast<CXXConversionDecl>(
11618 Best->Conversions[0].UserDefined.ConversionFunction);
11619
John Wiegley01296292011-04-08 18:41:53 +000011620 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith22262ab2013-05-04 06:44:46 +000011621 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11622 return ExprError();
Faisal Valid6676412013-06-15 11:54:37 +000011623 assert(Conv == Best->FoundDecl.getDecl() &&
11624 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregorab7897a2008-11-19 22:57:39 +000011625 // We selected one of the surrogate functions that converts the
11626 // object parameter to a function pointer. Perform the conversion
11627 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011628
Fariborz Jahanian774cf792009-09-28 18:35:46 +000011629 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +000011630 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011631 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11632 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +000011633 if (Call.isInvalid())
11634 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +000011635 // Record usage of conversion in an implicit cast.
11636 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11637 CK_UserDefinedConversion,
11638 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011639
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011640 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000011641 }
11642
John Wiegley01296292011-04-08 18:41:53 +000011643 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall49ec2e62010-01-28 01:54:34 +000011644
Douglas Gregorab7897a2008-11-19 22:57:39 +000011645 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11646 // that calls this method, using Object for the implicit object
11647 // parameter and passing along the remaining arguments.
11648 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Weber1fefe412012-11-09 06:06:14 +000011649
11650 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber9512d3f2012-11-09 08:38:04 +000011651 if (Method->isInvalidDecl())
Nico Weber1fefe412012-11-09 06:06:14 +000011652 return ExprError();
11653
Chandler Carruth8e543b32010-12-12 08:17:55 +000011654 const FunctionProtoType *Proto =
11655 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011656
11657 unsigned NumArgsInProto = Proto->getNumArgs();
Mike Stump11289f42009-09-09 15:08:12 +000011658
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011659 DeclarationNameInfo OpLocInfo(
11660 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11661 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewycky134af912013-02-07 05:08:22 +000011662 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011663 HadMultipleCandidates,
11664 OpLocInfo.getLoc(),
11665 OpLocInfo.getInfo());
John Wiegley01296292011-04-08 18:41:53 +000011666 if (NewFn.isInvalid())
11667 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011668
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011669 // Build the full argument list for the method call (the implicit object
11670 // parameter is placed at the beginning of the list).
11671 llvm::OwningArrayPtr<Expr *> MethodArgs(new Expr*[Args.size() + 1]);
11672 MethodArgs[0] = Object.get();
11673 std::copy(Args.begin(), Args.end(), &MethodArgs[1]);
11674
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011675 // Once we've built TheCall, all of the expressions are properly
11676 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000011677 QualType ResultTy = Method->getResultType();
11678 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11679 ResultTy = ResultTy.getNonLValueExprType(Context);
11680
Benjamin Kramer8b1a6bd2013-09-25 13:10:11 +000011681 CXXOperatorCallExpr *TheCall = new (Context)
11682 CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
11683 llvm::makeArrayRef(MethodArgs.get(), Args.size() + 1),
11684 ResultTy, VK, RParenLoc, false);
11685 MethodArgs.reset();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011686
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011687 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000011688 Method))
11689 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011690
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011691 // We may have default arguments. If so, we need to allocate more
11692 // slots in the call for them.
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011693 if (Args.size() < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000011694 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011695
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011696 bool IsError = false;
11697
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011698 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000011699 ExprResult ObjRes =
11700 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11701 Best->FoundDecl, Method);
11702 if (ObjRes.isInvalid())
11703 IsError = true;
11704 else
Benjamin Kramer62b95d82012-08-23 21:35:17 +000011705 Object = ObjRes;
John Wiegley01296292011-04-08 18:41:53 +000011706 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011707
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011708 // Check the argument types.
Benjamin Kramer3c529ca2013-10-05 10:03:01 +000011709 for (unsigned i = 0; i != NumArgsInProto; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011710 Expr *Arg;
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011711 if (i < Args.size()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011712 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000011713
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011714 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011715
John McCalldadc5752010-08-24 06:29:42 +000011716 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011717 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000011718 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011719 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000011720 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011721
Anders Carlsson7c5fe482010-01-29 18:43:53 +000011722 IsError |= InputInit.isInvalid();
11723 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011724 } else {
John McCalldadc5752010-08-24 06:29:42 +000011725 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011726 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11727 if (DefArg.isInvalid()) {
11728 IsError = true;
11729 break;
11730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011731
Douglas Gregor1bc688d2009-11-09 19:27:57 +000011732 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000011733 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011734
11735 TheCall->setArg(i + 1, Arg);
11736 }
11737
11738 // If this is a variadic call, handle args passed through "...".
11739 if (Proto->isVariadic()) {
11740 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011741 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley01296292011-04-08 18:41:53 +000011742 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11743 IsError |= Arg.isInvalid();
11744 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011745 }
11746 }
11747
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000011748 if (IsError) return true;
11749
Dmitri Gribenkod3b75562013-05-09 23:32:58 +000011750 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmanff4b4072012-02-18 04:48:30 +000011751
Richard Smith55ce3522012-06-25 20:30:08 +000011752 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000011753 return true;
11754
John McCalle172be52010-08-24 06:09:16 +000011755 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000011756}
11757
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011758/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000011759/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011760/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000011761ExprResult
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011762Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11763 bool *NoArrowOperatorFound) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000011764 assert(Base->getType()->isRecordType() &&
11765 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000011766
John McCall4124c492011-10-17 18:40:02 +000011767 if (checkPlaceholderForOverload(*this, Base))
11768 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000011769
John McCallbc077cf2010-02-08 23:07:23 +000011770 SourceLocation Loc = Base->getExprLoc();
11771
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011772 // C++ [over.ref]p1:
11773 //
11774 // [...] An expression x->m is interpreted as (x.operator->())->m
11775 // for a class object x of type T if T::operator->() exists and if
11776 // the operator is selected as the best match function by the
11777 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000011778 DeclarationName OpName =
11779 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000011780 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000011781 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000011782
John McCallbc077cf2010-02-08 23:07:23 +000011783 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +000011784 diag::err_typecheck_incomplete_tag, Base))
Eli Friedman132e70b2009-11-18 01:28:03 +000011785 return ExprError();
11786
John McCall27b18f82009-11-17 02:14:36 +000011787 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11788 LookupQualifiedName(R, BaseRecord->getDecl());
11789 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000011790
11791 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000011792 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000011793 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +000011794 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000011795 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011796
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000011797 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11798
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011799 // Perform overload resolution.
11800 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000011801 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011802 case OR_Success:
11803 // Overload resolution succeeded; we'll build the call below.
11804 break;
11805
11806 case OR_No_Viable_Function:
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011807 if (CandidateSet.empty()) {
11808 QualType BaseType = Base->getType();
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +000011809 if (NoArrowOperatorFound) {
11810 // Report this specific error to the caller instead of emitting a
11811 // diagnostic, as requested.
11812 *NoArrowOperatorFound = true;
11813 return ExprError();
11814 }
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011815 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11816 << BaseType << Base->getSourceRange();
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011817 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhrainbad7fb02013-07-15 19:54:54 +000011818 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011819 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain1bb5dbf2013-07-11 22:38:30 +000011820 }
11821 } else
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011822 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000011823 << "operator->" << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011824 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011825 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011826
11827 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000011828 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11829 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011830 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011831 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000011832
11833 case OR_Deleted:
11834 Diag(OpLoc, diag::err_ovl_deleted_oper)
11835 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011836 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000011837 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000011838 << Base->getSourceRange();
Ahmed Charlesb24b9aa2012-02-25 11:00:22 +000011839 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregord8061562009-08-06 03:17:00 +000011840 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011841 }
11842
John McCalla0296f72010-03-19 07:35:19 +000011843 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11844
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011845 // Convert the object parameter.
11846 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000011847 ExprResult BaseResult =
11848 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11849 Best->FoundDecl, Method);
11850 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000011851 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000011852 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000011853
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011854 // Build the operator call.
Nick Lewycky134af912013-02-07 05:08:22 +000011855 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidisa2a299e2012-02-08 01:21:13 +000011856 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +000011857 if (FnExpr.isInvalid())
11858 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011859
John McCall7decc9e2010-11-18 06:31:45 +000011860 QualType ResultTy = Method->getResultType();
11861 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11862 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000011863 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000011864 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hames5de91cc2012-10-02 04:45:10 +000011865 Base, ResultTy, VK, OpLoc, false);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011866
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000011867 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000011868 Method))
11869 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000011870
11871 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000011872}
11873
Richard Smithbcc22fc2012-03-09 08:00:36 +000011874/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11875/// a literal operator described by the provided lookup results.
11876ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11877 DeclarationNameInfo &SuffixInfo,
11878 ArrayRef<Expr*> Args,
11879 SourceLocation LitEndLoc,
11880 TemplateArgumentListInfo *TemplateArgs) {
11881 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smithc67fdd42012-03-07 08:35:16 +000011882
Richard Smithbcc22fc2012-03-09 08:00:36 +000011883 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11884 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11885 TemplateArgs);
Richard Smithc67fdd42012-03-07 08:35:16 +000011886
Richard Smithbcc22fc2012-03-09 08:00:36 +000011887 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11888
Richard Smithbcc22fc2012-03-09 08:00:36 +000011889 // Perform overload resolution. This will usually be trivial, but might need
11890 // to perform substitutions for a literal operator template.
11891 OverloadCandidateSet::iterator Best;
11892 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11893 case OR_Success:
11894 case OR_Deleted:
11895 break;
11896
11897 case OR_No_Viable_Function:
11898 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11899 << R.getLookupName();
11900 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11901 return ExprError();
11902
11903 case OR_Ambiguous:
11904 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11905 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11906 return ExprError();
Richard Smithc67fdd42012-03-07 08:35:16 +000011907 }
11908
Richard Smithbcc22fc2012-03-09 08:00:36 +000011909 FunctionDecl *FD = Best->Function;
Nick Lewycky134af912013-02-07 05:08:22 +000011910 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11911 HadMultipleCandidates,
Richard Smithbcc22fc2012-03-09 08:00:36 +000011912 SuffixInfo.getLoc(),
11913 SuffixInfo.getInfo());
11914 if (Fn.isInvalid())
11915 return true;
Richard Smithc67fdd42012-03-07 08:35:16 +000011916
11917 // Check the argument types. This should almost always be a no-op, except
11918 // that array-to-pointer decay is applied to string literals.
Richard Smithc67fdd42012-03-07 08:35:16 +000011919 Expr *ConvArgs[2];
Richard Smithe54c3072013-05-05 15:51:06 +000011920 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smithc67fdd42012-03-07 08:35:16 +000011921 ExprResult InputInit = PerformCopyInitialization(
11922 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11923 SourceLocation(), Args[ArgIdx]);
11924 if (InputInit.isInvalid())
11925 return true;
11926 ConvArgs[ArgIdx] = InputInit.take();
11927 }
11928
Richard Smithc67fdd42012-03-07 08:35:16 +000011929 QualType ResultTy = FD->getResultType();
11930 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11931 ResultTy = ResultTy.getNonLValueExprType(Context);
11932
Richard Smithc67fdd42012-03-07 08:35:16 +000011933 UserDefinedLiteral *UDL =
Benjamin Kramerc215e762012-08-24 11:54:20 +000011934 new (Context) UserDefinedLiteral(Context, Fn.take(),
11935 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smithc67fdd42012-03-07 08:35:16 +000011936 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11937
11938 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11939 return ExprError();
11940
Richard Smith55ce3522012-06-25 20:30:08 +000011941 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smithc67fdd42012-03-07 08:35:16 +000011942 return ExprError();
11943
11944 return MaybeBindToTemporary(UDL);
11945}
11946
Sam Panzer0f384432012-08-21 00:52:01 +000011947/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11948/// given LookupResult is non-empty, it is assumed to describe a member which
11949/// will be invoked. Otherwise, the function will be found via argument
11950/// dependent lookup.
11951/// CallExpr is set to a valid expression and FRS_Success returned on success,
11952/// otherwise CallExpr is set to ExprError() and some non-success value
11953/// is returned.
11954Sema::ForRangeStatus
11955Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11956 SourceLocation RangeLoc, VarDecl *Decl,
11957 BeginEndFunction BEF,
11958 const DeclarationNameInfo &NameInfo,
11959 LookupResult &MemberLookup,
11960 OverloadCandidateSet *CandidateSet,
11961 Expr *Range, ExprResult *CallExpr) {
11962 CandidateSet->clear();
11963 if (!MemberLookup.empty()) {
11964 ExprResult MemberRef =
11965 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11966 /*IsPtr=*/false, CXXScopeSpec(),
11967 /*TemplateKWLoc=*/SourceLocation(),
11968 /*FirstQualifierInScope=*/0,
11969 MemberLookup,
11970 /*TemplateArgs=*/0);
11971 if (MemberRef.isInvalid()) {
11972 *CallExpr = ExprError();
11973 Diag(Range->getLocStart(), diag::note_in_for_range)
11974 << RangeLoc << BEF << Range->getType();
11975 return FRS_DiagnosticIssued;
11976 }
Dmitri Gribenko78852e92013-05-05 20:40:26 +000011977 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzer0f384432012-08-21 00:52:01 +000011978 if (CallExpr->isInvalid()) {
11979 *CallExpr = ExprError();
11980 Diag(Range->getLocStart(), diag::note_in_for_range)
11981 << RangeLoc << BEF << Range->getType();
11982 return FRS_DiagnosticIssued;
11983 }
11984 } else {
11985 UnresolvedSet<0> FoundNames;
Sam Panzer0f384432012-08-21 00:52:01 +000011986 UnresolvedLookupExpr *Fn =
11987 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11988 NestedNameSpecifierLoc(), NameInfo,
11989 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb6626742012-10-18 17:56:02 +000011990 FoundNames.begin(), FoundNames.end());
Sam Panzer0f384432012-08-21 00:52:01 +000011991
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000011992 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzer0f384432012-08-21 00:52:01 +000011993 CandidateSet, CallExpr);
11994 if (CandidateSet->empty() || CandidateSetError) {
11995 *CallExpr = ExprError();
11996 return FRS_NoViableFunction;
11997 }
11998 OverloadCandidateSet::iterator Best;
11999 OverloadingResult OverloadResult =
12000 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
12001
12002 if (OverloadResult == OR_No_Viable_Function) {
12003 *CallExpr = ExprError();
12004 return FRS_NoViableFunction;
12005 }
Dmitri Gribenko9c785c22013-05-09 21:02:07 +000012006 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzer0f384432012-08-21 00:52:01 +000012007 Loc, 0, CandidateSet, &Best,
12008 OverloadResult,
12009 /*AllowTypoCorrection=*/false);
12010 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
12011 *CallExpr = ExprError();
12012 Diag(Range->getLocStart(), diag::note_in_for_range)
12013 << RangeLoc << BEF << Range->getType();
12014 return FRS_DiagnosticIssued;
12015 }
12016 }
12017 return FRS_Success;
12018}
12019
12020
Douglas Gregorcd695e52008-11-10 20:40:00 +000012021/// FixOverloadedFunctionReference - E is an expression that refers to
12022/// a C++ overloaded function (possibly with some parentheses and
12023/// perhaps a '&' around it). We have resolved the overloaded function
12024/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000012025/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000012026Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000012027 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000012028 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012029 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
12030 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012031 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012032 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012033
Douglas Gregor51c538b2009-11-20 19:42:02 +000012034 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012035 }
12036
Douglas Gregor51c538b2009-11-20 19:42:02 +000012037 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000012038 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
12039 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012040 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000012041 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000012042 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000012043 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000012044 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012045 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012046
12047 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000012048 ICE->getCastKind(),
12049 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000012050 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012051 }
12052
Douglas Gregor51c538b2009-11-20 19:42:02 +000012053 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000012054 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000012055 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012056 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
12057 if (Method->isStatic()) {
12058 // Do nothing: static member functions aren't any different
12059 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000012060 } else {
Alp Toker028ed912013-12-06 17:56:43 +000012061 // Fix the subexpression, which really has to be an
John McCalle66edc12009-11-24 19:00:30 +000012062 // UnresolvedLookupExpr holding an overloaded member function
12063 // or template.
John McCall16df1e52010-03-30 21:47:33 +000012064 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12065 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000012066 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012067 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012068
John McCalld14a8642009-11-21 08:51:07 +000012069 assert(isa<DeclRefExpr>(SubExpr)
12070 && "fixed to something other than a decl ref");
12071 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
12072 && "fixed to a member ref with no nested name qualifier");
12073
12074 // We have taken the address of a pointer to member
12075 // function. Perform the computation here so that we get the
12076 // appropriate pointer to member type.
12077 QualType ClassType
12078 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
12079 QualType MemPtrType
12080 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
12081
John McCall7decc9e2010-11-18 06:31:45 +000012082 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
12083 VK_RValue, OK_Ordinary,
12084 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000012085 }
12086 }
John McCall16df1e52010-03-30 21:47:33 +000012087 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
12088 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000012089 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000012090 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012091
John McCalle3027922010-08-25 11:45:40 +000012092 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012093 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000012094 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000012095 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012096 }
John McCalld14a8642009-11-21 08:51:07 +000012097
12098 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000012099 // FIXME: avoid copy.
12100 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000012101 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000012102 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
12103 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000012104 }
12105
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012106 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12107 ULE->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012108 ULE->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012109 Fn,
John McCall113bee02012-03-10 09:33:50 +000012110 /*enclosing*/ false, // FIXME?
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012111 ULE->getNameLoc(),
12112 Fn->getType(),
12113 VK_LValue,
12114 Found.getDecl(),
12115 TemplateArgs);
Richard Smithf623c962012-04-17 00:58:00 +000012116 MarkDeclRefReferenced(DRE);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012117 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
12118 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000012119 }
12120
John McCall10eae182009-11-30 22:42:35 +000012121 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000012122 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000012123 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
12124 if (MemExpr->hasExplicitTemplateArgs()) {
12125 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
12126 TemplateArgs = &TemplateArgsBuffer;
12127 }
John McCall6b51f282009-11-23 01:53:49 +000012128
John McCall2d74de92009-12-01 22:10:20 +000012129 Expr *Base;
12130
John McCall7decc9e2010-11-18 06:31:45 +000012131 // If we're filling in a static method where we used to have an
12132 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000012133 if (MemExpr->isImplicitAccess()) {
12134 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012135 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
12136 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012137 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012138 Fn,
John McCall113bee02012-03-10 09:33:50 +000012139 /*enclosing*/ false,
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012140 MemExpr->getMemberLoc(),
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(MemExpr->getNumDecls() > 1);
12147 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000012148 } else {
12149 SourceLocation Loc = MemExpr->getMemberLoc();
12150 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000012151 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman73a04092012-01-07 04:59:52 +000012152 CheckCXXThisCapture(Loc);
Douglas Gregorb15af892010-01-07 23:12:05 +000012153 Base = new (Context) CXXThisExpr(Loc,
12154 MemExpr->getBaseType(),
12155 /*isImplicit=*/true);
12156 }
John McCall2d74de92009-12-01 22:10:20 +000012157 } else
John McCallc3007a22010-10-26 07:05:15 +000012158 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000012159
John McCall4adb38c2011-04-27 00:36:17 +000012160 ExprValueKind valueKind;
12161 QualType type;
12162 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
12163 valueKind = VK_LValue;
12164 type = Fn->getType();
12165 } else {
12166 valueKind = VK_RValue;
12167 type = Context.BoundMemberTy;
12168 }
12169
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012170 MemberExpr *ME = MemberExpr::Create(Context, Base,
12171 MemExpr->isArrow(),
12172 MemExpr->getQualifierLoc(),
Abramo Bagnara7945c982012-01-27 09:46:47 +000012173 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012174 Fn,
12175 Found,
12176 MemExpr->getMemberNameInfo(),
12177 TemplateArgs,
12178 type, valueKind, OK_Ordinary);
12179 ME->setHadMultipleCandidates(true);
Richard Smith4f6a2c42012-11-14 07:06:31 +000012180 MarkMemberReferenced(ME);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000012181 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000012182 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012183
John McCallc3007a22010-10-26 07:05:15 +000012184 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregorcd695e52008-11-10 20:40:00 +000012185}
12186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000012187ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000012188 DeclAccessPair Found,
12189 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000012190 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000012191}
12192
Douglas Gregor5251f1b2008-10-21 16:13:35 +000012193} // end namespace clang