blob: c7620e49f7c73048ae697dd5e19c595aa924565c [file] [log] [blame]
Nick Lewycky5d9484d2013-01-24 01:12:16 +00001//===--- SemaOverload.cpp - C++ Overloading -------------------------------===//
Douglas Gregor8e9bebd2008-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 Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000038
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000039/// A convenience routine for creating a decayed reference to a function.
John Wiegley429bb272011-04-08 18:41:53 +000040static ExprResult
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000041CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, NamedDecl *FoundDecl,
42 bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Richard Smith82f145d2013-05-04 06:44:46 +000045 if (S.DiagnoseUseOfDecl(FoundDecl, Loc))
Faisal Valid570a922013-06-15 11:54:37 +000046 return ExprError();
47 // If FoundDecl is different from Fn (such as if one is a template
48 // and the other a specialization), make sure DiagnoseUseOfDecl is
49 // called on both.
50 // FIXME: This would be more comprehensively addressed by modifying
51 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
52 // being used.
53 if (FoundDecl != Fn && S.DiagnoseUseOfDecl(Fn, Loc))
Richard Smith82f145d2013-05-04 06:44:46 +000054 return ExprError();
John McCallf4b88a42012-03-10 09:33:50 +000055 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000056 VK_LValue, Loc, LocInfo);
57 if (HadMultipleCandidates)
58 DRE->setHadMultipleCandidates(true);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000059
60 S.MarkDeclRefReferenced(DRE);
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000061
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000062 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000063 E = S.DefaultFunctionArrayConversion(E.take());
64 if (E.isInvalid())
65 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000066 return E;
John McCallf89e55a2010-11-18 06:31:45 +000067}
68
John McCall120d63c2010-08-24 20:38:10 +000069static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
70 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000071 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000072 bool CStyle,
73 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000074
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000075static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
76 QualType &ToType,
77 bool InOverloadResolution,
78 StandardConversionSequence &SCS,
79 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000080static OverloadingResult
81IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
82 UserDefinedConversionSequence& User,
83 OverloadCandidateSet& Conversions,
84 bool AllowExplicit);
85
86
87static ImplicitConversionSequence::CompareKind
88CompareStandardConversionSequences(Sema &S,
89 const StandardConversionSequence& SCS1,
90 const StandardConversionSequence& SCS2);
91
92static ImplicitConversionSequence::CompareKind
93CompareQualificationConversions(Sema &S,
94 const StandardConversionSequence& SCS1,
95 const StandardConversionSequence& SCS2);
96
97static ImplicitConversionSequence::CompareKind
98CompareDerivedToBaseConversions(Sema &S,
99 const StandardConversionSequence& SCS1,
100 const StandardConversionSequence& SCS2);
101
102
103
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104/// GetConversionCategory - Retrieve the implicit conversion
105/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +0000106ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000107GetConversionCategory(ImplicitConversionKind Kind) {
108 static const ImplicitConversionCategory
109 Category[(int)ICK_Num_Conversion_Kinds] = {
110 ICC_Identity,
111 ICC_Lvalue_Transformation,
112 ICC_Lvalue_Transformation,
113 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000114 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000115 ICC_Qualification_Adjustment,
116 ICC_Promotion,
117 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000118 ICC_Promotion,
119 ICC_Conversion,
120 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000121 ICC_Conversion,
122 ICC_Conversion,
123 ICC_Conversion,
124 ICC_Conversion,
125 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000126 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000127 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000128 ICC_Conversion,
129 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000130 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000131 ICC_Conversion
132 };
133 return Category[(int)Kind];
134}
135
136/// GetConversionRank - Retrieve the implicit conversion rank
137/// corresponding to the given implicit conversion kind.
138ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
139 static const ImplicitConversionRank
140 Rank[(int)ICK_Num_Conversion_Kinds] = {
141 ICR_Exact_Match,
142 ICR_Exact_Match,
143 ICR_Exact_Match,
144 ICR_Exact_Match,
145 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000146 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 ICR_Promotion,
148 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000149 ICR_Promotion,
150 ICR_Conversion,
151 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 ICR_Conversion,
153 ICR_Conversion,
154 ICR_Conversion,
155 ICR_Conversion,
156 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000157 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000158 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000159 ICR_Conversion,
160 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000161 ICR_Complex_Real_Conversion,
162 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000163 ICR_Conversion,
164 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165 };
166 return Rank[(int)Kind];
167}
168
169/// GetImplicitConversionName - Return the name of this kind of
170/// implicit conversion.
171const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000172 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000173 "No conversion",
174 "Lvalue-to-rvalue",
175 "Array-to-pointer",
176 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000177 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000178 "Qualification",
179 "Integral promotion",
180 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000181 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 "Integral conversion",
183 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000184 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 "Floating-integral conversion",
186 "Pointer conversion",
187 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000188 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000189 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000190 "Derived-to-base conversion",
191 "Vector conversion",
192 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000193 "Complex-real conversion",
194 "Block Pointer conversion",
195 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000196 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 };
198 return Name[Kind];
199}
200
Douglas Gregor60d62c22008-10-31 16:23:19 +0000201/// StandardConversionSequence - Set the standard conversion
202/// sequence to the identity conversion.
203void StandardConversionSequence::setAsIdentityConversion() {
204 First = ICK_Identity;
205 Second = ICK_Identity;
206 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000207 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000208 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000209 ReferenceBinding = false;
210 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000211 IsLvalueReference = true;
212 BindsToFunctionLvalue = false;
213 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000214 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000215 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000216 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000217}
218
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219/// getRank - Retrieve the rank of this standard conversion sequence
220/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
221/// implicit conversions.
222ImplicitConversionRank StandardConversionSequence::getRank() const {
223 ImplicitConversionRank Rank = ICR_Exact_Match;
224 if (GetConversionRank(First) > Rank)
225 Rank = GetConversionRank(First);
226 if (GetConversionRank(Second) > Rank)
227 Rank = GetConversionRank(Second);
228 if (GetConversionRank(Third) > Rank)
229 Rank = GetConversionRank(Third);
230 return Rank;
231}
232
233/// isPointerConversionToBool - Determines whether this conversion is
234/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000235/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000237bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 // Note that FromType has not necessarily been transformed by the
239 // array-to-pointer or function-to-pointer implicit conversions, so
240 // check for their presence as well as checking whether FromType is
241 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000242 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000243 (getFromType()->isPointerType() ||
244 getFromType()->isObjCObjectPointerType() ||
245 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000246 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
248 return true;
249
250 return false;
251}
252
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000253/// isPointerConversionToVoidPointer - Determines whether this
254/// conversion is a conversion of a pointer to a void pointer. This is
255/// used as part of the ranking of standard conversion sequences (C++
256/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000257bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000258StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000259isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000260 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000261 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000262
263 // Note that FromType has not necessarily been transformed by the
264 // array-to-pointer implicit conversion, so check for its presence
265 // and redo the conversion to get a pointer.
266 if (First == ICK_Array_To_Pointer)
267 FromType = Context.getArrayDecayedType(FromType);
268
Douglas Gregorf9af5242011-04-15 20:45:44 +0000269 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000270 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000271 return ToPtrType->getPointeeType()->isVoidType();
272
273 return false;
274}
275
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000276/// Skip any implicit casts which could be either part of a narrowing conversion
277/// or after one in an implicit conversion.
278static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
279 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
280 switch (ICE->getCastKind()) {
281 case CK_NoOp:
282 case CK_IntegralCast:
283 case CK_IntegralToBoolean:
284 case CK_IntegralToFloating:
285 case CK_FloatingToIntegral:
286 case CK_FloatingToBoolean:
287 case CK_FloatingCast:
288 Converted = ICE->getSubExpr();
289 continue;
290
291 default:
292 return Converted;
293 }
294 }
295
296 return Converted;
297}
298
299/// Check if this standard conversion sequence represents a narrowing
300/// conversion, according to C++11 [dcl.init.list]p7.
301///
302/// \param Ctx The AST context.
303/// \param Converted The result of applying this standard conversion sequence.
304/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
305/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000306/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
307/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000308NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000309StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
310 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000311 APValue &ConstantValue,
312 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000313 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000314
315 // C++11 [dcl.init.list]p7:
316 // A narrowing conversion is an implicit conversion ...
317 QualType FromType = getToType(0);
318 QualType ToType = getToType(1);
319 switch (Second) {
320 // -- from a floating-point type to an integer type, or
321 //
322 // -- from an integer type or unscoped enumeration type to a floating-point
323 // type, except where the source is a constant expression and the actual
324 // value after conversion will fit into the target type and will produce
325 // the original value when converted back to the original type, or
326 case ICK_Floating_Integral:
327 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
328 return NK_Type_Narrowing;
329 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
330 llvm::APSInt IntConstantValue;
331 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
332 if (Initializer &&
333 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
334 // Convert the integer to the floating type.
335 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
336 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
337 llvm::APFloat::rmNearestTiesToEven);
338 // And back.
339 llvm::APSInt ConvertedValue = IntConstantValue;
340 bool ignored;
341 Result.convertToInteger(ConvertedValue,
342 llvm::APFloat::rmTowardZero, &ignored);
343 // If the resulting value is different, this was a narrowing conversion.
344 if (IntConstantValue != ConvertedValue) {
345 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000346 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000347 return NK_Constant_Narrowing;
348 }
349 } else {
350 // Variables are always narrowings.
351 return NK_Variable_Narrowing;
352 }
353 }
354 return NK_Not_Narrowing;
355
356 // -- from long double to double or float, or from double to float, except
357 // where the source is a constant expression and the actual value after
358 // conversion is within the range of values that can be represented (even
359 // if it cannot be represented exactly), or
360 case ICK_Floating_Conversion:
361 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
362 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
363 // FromType is larger than ToType.
364 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
365 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
366 // Constant!
367 assert(ConstantValue.isFloat());
368 llvm::APFloat FloatVal = ConstantValue.getFloat();
369 // Convert the source value into the target type.
370 bool ignored;
371 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
372 Ctx.getFloatTypeSemantics(ToType),
373 llvm::APFloat::rmNearestTiesToEven, &ignored);
374 // If there was no overflow, the source value is within the range of
375 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000376 if (ConvertStatus & llvm::APFloat::opOverflow) {
377 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000378 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000379 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000380 } else {
381 return NK_Variable_Narrowing;
382 }
383 }
384 return NK_Not_Narrowing;
385
386 // -- from an integer type or unscoped enumeration type to an integer type
387 // that cannot represent all the values of the original type, except where
388 // the source is a constant expression and the actual value after
389 // conversion will fit into the target type and will produce the original
390 // value when converted back to the original type.
391 case ICK_Boolean_Conversion: // Bools are integers too.
392 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
393 // Boolean conversions can be from pointers and pointers to members
394 // [conv.bool], and those aren't considered narrowing conversions.
395 return NK_Not_Narrowing;
396 } // Otherwise, fall through to the integral case.
397 case ICK_Integral_Conversion: {
398 assert(FromType->isIntegralOrUnscopedEnumerationType());
399 assert(ToType->isIntegralOrUnscopedEnumerationType());
400 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
401 const unsigned FromWidth = Ctx.getIntWidth(FromType);
402 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
403 const unsigned ToWidth = Ctx.getIntWidth(ToType);
404
405 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000406 (FromWidth == ToWidth && FromSigned != ToSigned) ||
407 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000408 // Not all values of FromType can be represented in ToType.
409 llvm::APSInt InitializerValue;
410 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000411 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
412 // Such conversions on variables are always narrowing.
413 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000414 }
415 bool Narrowing = false;
416 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000417 // Negative -> unsigned is narrowing. Otherwise, more bits is never
418 // narrowing.
419 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000420 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000421 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000422 // Add a bit to the InitializerValue so we don't have to worry about
423 // signed vs. unsigned comparisons.
424 InitializerValue = InitializerValue.extend(
425 InitializerValue.getBitWidth() + 1);
426 // Convert the initializer to and from the target width and signed-ness.
427 llvm::APSInt ConvertedValue = InitializerValue;
428 ConvertedValue = ConvertedValue.trunc(ToWidth);
429 ConvertedValue.setIsSigned(ToSigned);
430 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
431 ConvertedValue.setIsSigned(InitializerValue.isSigned());
432 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000433 if (ConvertedValue != InitializerValue)
434 Narrowing = true;
435 }
436 if (Narrowing) {
437 ConstantType = Initializer->getType();
438 ConstantValue = APValue(InitializerValue);
439 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000440 }
441 }
442 return NK_Not_Narrowing;
443 }
444
445 default:
446 // Other kinds of conversions are not narrowings.
447 return NK_Not_Narrowing;
448 }
449}
450
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451/// DebugPrint - Print this standard conversion sequence to standard
452/// error. Useful for debugging overloading issues.
453void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000454 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455 bool PrintedSomething = false;
456 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (Second != ICK_Identity) {
462 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000463 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000464 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000465 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000466
467 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000468 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000469 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000470 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000471 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000473 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 PrintedSomething = true;
475 }
476
477 if (Third != ICK_Identity) {
478 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000481 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482 PrintedSomething = true;
483 }
484
485 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000486 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000487 }
488}
489
490/// DebugPrint - Print this user-defined conversion sequence to standard
491/// error. Useful for debugging overloading issues.
492void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000493 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000494 if (Before.First || Before.Second || Before.Third) {
495 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000496 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000497 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000498 if (ConversionFunction)
499 OS << '\'' << *ConversionFunction << '\'';
500 else
501 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000503 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000504 After.DebugPrint();
505 }
506}
507
508/// DebugPrint - Print this implicit conversion sequence to standard
509/// error. Useful for debugging overloading issues.
510void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000511 raw_ostream &OS = llvm::errs();
Richard Smith798186a2013-09-06 22:30:28 +0000512 if (isStdInitializerListElement())
513 OS << "Worst std::initializer_list element conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 switch (ConversionKind) {
515 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000516 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000517 Standard.DebugPrint();
518 break;
519 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000520 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 UserDefined.DebugPrint();
522 break;
523 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000524 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000525 break;
John McCall1d318332010-01-12 00:44:57 +0000526 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000527 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000528 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000530 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000531 break;
532 }
533
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000534 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000535}
536
John McCall1d318332010-01-12 00:44:57 +0000537void AmbiguousConversionSequence::construct() {
538 new (&conversions()) ConversionSet();
539}
540
541void AmbiguousConversionSequence::destruct() {
542 conversions().~ConversionSet();
543}
544
545void
546AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
547 FromTypePtr = O.FromTypePtr;
548 ToTypePtr = O.ToTypePtr;
549 new (&conversions()) ConversionSet(O.conversions());
550}
551
Douglas Gregora9333192010-05-08 17:41:32 +0000552namespace {
Larisse Voufo43847122013-07-19 23:00:19 +0000553 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000554 // template argument information.
555 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000556 TemplateArgument FirstArg;
557 TemplateArgument SecondArg;
558 };
Larisse Voufo43847122013-07-19 23:00:19 +0000559 // Structure used by DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000560 // template parameter and template argument information.
561 struct DFIParamWithArguments : DFIArguments {
562 TemplateParameter Param;
563 };
Douglas Gregora9333192010-05-08 17:41:32 +0000564}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000565
Douglas Gregora9333192010-05-08 17:41:32 +0000566/// \brief Convert from Sema's representation of template deduction information
567/// to the form used in overload-candidate information.
Larisse Voufo43847122013-07-19 23:00:19 +0000568DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context,
569 Sema::TemplateDeductionResult TDK,
570 TemplateDeductionInfo &Info) {
571 DeductionFailureInfo Result;
Douglas Gregora9333192010-05-08 17:41:32 +0000572 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000573 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000574 Result.Data = 0;
575 switch (TDK) {
576 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000577 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000578 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000579 case Sema::TDK_TooManyArguments:
580 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000581 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000582
Douglas Gregora9333192010-05-08 17:41:32 +0000583 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000584 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000585 Result.Data = Info.Param.getOpaqueValue();
586 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000587
Richard Smith29805ca2013-01-31 05:19:49 +0000588 case Sema::TDK_NonDeducedMismatch: {
589 // FIXME: Should allocate from normal heap so that we can free this later.
590 DFIArguments *Saved = new (Context) DFIArguments;
591 Saved->FirstArg = Info.FirstArg;
592 Saved->SecondArg = Info.SecondArg;
593 Result.Data = Saved;
594 break;
595 }
596
Douglas Gregora9333192010-05-08 17:41:32 +0000597 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000598 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000599 // FIXME: Should allocate from normal heap so that we can free this later.
600 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000601 Saved->Param = Info.Param;
602 Saved->FirstArg = Info.FirstArg;
603 Saved->SecondArg = Info.SecondArg;
604 Result.Data = Saved;
605 break;
606 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
Douglas Gregora9333192010-05-08 17:41:32 +0000608 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000609 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000610 if (Info.hasSFINAEDiagnostic()) {
611 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
612 SourceLocation(), PartialDiagnostic::NullDiagnostic());
613 Info.takeSFINAEDiagnostic(*Diag);
614 Result.HasDiagnostic = true;
615 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000616 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora9333192010-05-08 17:41:32 +0000618 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000619 Result.Data = Info.Expression;
620 break;
621
Richard Smith29805ca2013-01-31 05:19:49 +0000622 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000623 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000624 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000625
Douglas Gregora9333192010-05-08 17:41:32 +0000626 return Result;
627}
John McCall1d318332010-01-12 00:44:57 +0000628
Larisse Voufo43847122013-07-19 23:00:19 +0000629void DeductionFailureInfo::Destroy() {
Douglas Gregora9333192010-05-08 17:41:32 +0000630 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
631 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000632 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000633 case Sema::TDK_InstantiationDepth:
634 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000635 case Sema::TDK_TooManyArguments:
636 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000637 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000638 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000639 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000640
Douglas Gregora9333192010-05-08 17:41:32 +0000641 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000642 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000643 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000644 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000645 Data = 0;
646 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000647
648 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000649 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000650 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000651 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
652 Diag->~PartialDiagnosticAt();
653 HasDiagnostic = false;
654 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000655 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000656
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000657 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000658 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000659 break;
660 }
661}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000662
Larisse Voufo43847122013-07-19 23:00:19 +0000663PartialDiagnosticAt *DeductionFailureInfo::getSFINAEDiagnostic() {
Richard Smithb8590f32012-05-07 09:03:25 +0000664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
666 return 0;
667}
668
Larisse Voufo43847122013-07-19 23:00:19 +0000669TemplateParameter DeductionFailureInfo::getTemplateParameter() {
Douglas Gregora9333192010-05-08 17:41:32 +0000670 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
671 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000672 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000673 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000674 case Sema::TDK_TooManyArguments:
675 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000676 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000677 case Sema::TDK_NonDeducedMismatch:
678 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000679 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000680
Douglas Gregora9333192010-05-08 17:41:32 +0000681 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000682 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000683 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000684
685 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000686 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000687 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000688
Douglas Gregora9333192010-05-08 17:41:32 +0000689 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000690 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000691 break;
692 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000693
Douglas Gregora9333192010-05-08 17:41:32 +0000694 return TemplateParameter();
695}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000696
Larisse Voufo43847122013-07-19 23:00:19 +0000697TemplateArgumentList *DeductionFailureInfo::getTemplateArgumentList() {
Douglas Gregorec20f462010-05-08 20:07:26 +0000698 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000699 case Sema::TDK_Success:
700 case Sema::TDK_Invalid:
701 case Sema::TDK_InstantiationDepth:
702 case Sema::TDK_TooManyArguments:
703 case Sema::TDK_TooFewArguments:
704 case Sema::TDK_Incomplete:
705 case Sema::TDK_InvalidExplicitArguments:
706 case Sema::TDK_Inconsistent:
707 case Sema::TDK_Underqualified:
708 case Sema::TDK_NonDeducedMismatch:
709 case Sema::TDK_FailedOverloadResolution:
710 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000711
Richard Smith29805ca2013-01-31 05:19:49 +0000712 case Sema::TDK_SubstitutionFailure:
713 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000714
Richard Smith29805ca2013-01-31 05:19:49 +0000715 // Unhandled
716 case Sema::TDK_MiscellaneousDeductionFailure:
717 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000718 }
719
720 return 0;
721}
722
Larisse Voufo43847122013-07-19 23:00:19 +0000723const TemplateArgument *DeductionFailureInfo::getFirstArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000724 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
725 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000726 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000727 case Sema::TDK_InstantiationDepth:
728 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000729 case Sema::TDK_TooManyArguments:
730 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000731 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000732 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000733 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000734 return 0;
735
Douglas Gregora9333192010-05-08 17:41:32 +0000736 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000737 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000738 case Sema::TDK_NonDeducedMismatch:
739 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000740
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000741 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000742 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000743 break;
744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000745
Douglas Gregora9333192010-05-08 17:41:32 +0000746 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747}
Douglas Gregora9333192010-05-08 17:41:32 +0000748
Larisse Voufo43847122013-07-19 23:00:19 +0000749const TemplateArgument *DeductionFailureInfo::getSecondArg() {
Douglas Gregora9333192010-05-08 17:41:32 +0000750 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
751 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000752 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000753 case Sema::TDK_InstantiationDepth:
754 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000755 case Sema::TDK_TooManyArguments:
756 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000757 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000758 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000759 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000760 return 0;
761
Douglas Gregora9333192010-05-08 17:41:32 +0000762 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000763 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000764 case Sema::TDK_NonDeducedMismatch:
765 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000766
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000767 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000768 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000769 break;
770 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000771
Douglas Gregora9333192010-05-08 17:41:32 +0000772 return 0;
773}
774
Larisse Voufo43847122013-07-19 23:00:19 +0000775Expr *DeductionFailureInfo::getExpr() {
Richard Smith0efa62f2013-01-31 04:03:12 +0000776 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
777 Sema::TDK_FailedOverloadResolution)
778 return static_cast<Expr*>(Data);
779
780 return 0;
781}
782
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000783void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000784 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000785 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
786 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000787 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
788 i->DeductionFailure.Destroy();
789 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000790}
791
792void OverloadCandidateSet::clear() {
793 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000794 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000795 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000796 Functions.clear();
797}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000798
John McCall5acb0c92011-10-17 18:40:02 +0000799namespace {
800 class UnbridgedCastsSet {
801 struct Entry {
802 Expr **Addr;
803 Expr *Saved;
804 };
805 SmallVector<Entry, 2> Entries;
806
807 public:
808 void save(Sema &S, Expr *&E) {
809 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
810 Entry entry = { &E, E };
811 Entries.push_back(entry);
812 E = S.stripARCUnbridgedCast(E);
813 }
814
815 void restore() {
816 for (SmallVectorImpl<Entry>::iterator
817 i = Entries.begin(), e = Entries.end(); i != e; ++i)
818 *i->Addr = i->Saved;
819 }
820 };
821}
822
823/// checkPlaceholderForOverload - Do any interesting placeholder-like
824/// preprocessing on the given expression.
825///
826/// \param unbridgedCasts a collection to which to add unbridged casts;
827/// without this, they will be immediately diagnosed as errors
828///
829/// Return true on unrecoverable error.
830static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
831 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000832 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
833 // We can't handle overloaded expressions here because overload
834 // resolution might reasonably tweak them.
835 if (placeholder->getKind() == BuiltinType::Overload) return false;
836
837 // If the context potentially accepts unbridged ARC casts, strip
838 // the unbridged cast and add it to the collection for later restoration.
839 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
840 unbridgedCasts) {
841 unbridgedCasts->save(S, E);
842 return false;
843 }
844
845 // Go ahead and check everything else.
846 ExprResult result = S.CheckPlaceholderExpr(E);
847 if (result.isInvalid())
848 return true;
849
850 E = result.take();
851 return false;
852 }
853
854 // Nothing to do.
855 return false;
856}
857
858/// checkArgPlaceholdersForOverload - Check a set of call operands for
859/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000860static bool checkArgPlaceholdersForOverload(Sema &S,
861 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000862 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000863 for (unsigned i = 0, e = Args.size(); i != e; ++i)
864 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000865 return true;
866
867 return false;
868}
869
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000870// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000871// overload of the declarations in Old. This routine returns false if
872// New and Old cannot be overloaded, e.g., if New has the same
873// signature as some function in Old (C++ 1.3.10) or if the Old
874// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000875// it does return false, MatchedDecl will point to the decl that New
876// cannot be overloaded with. This decl may be a UsingShadowDecl on
877// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000878//
879// Example: Given the following input:
880//
881// void f(int, float); // #1
882// void f(int, int); // #2
883// int f(int, int); // #3
884//
885// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000886// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000887//
John McCall51fa86f2009-12-02 08:47:38 +0000888// When we process #2, Old contains only the FunctionDecl for #1. By
889// comparing the parameter types, we see that #1 and #2 are overloaded
890// (since they have different signatures), so this routine returns
891// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000892//
John McCall51fa86f2009-12-02 08:47:38 +0000893// When we process #3, Old is an overload set containing #1 and #2. We
894// compare the signatures of #3 to #1 (they're overloaded, so we do
895// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
896// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000897// signature), IsOverload returns false and MatchedDecl will be set to
898// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000899//
900// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
901// into a class by a using declaration. The rules for whether to hide
902// shadow declarations ignore some properties which otherwise figure
903// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000904Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000905Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
906 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000907 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000908 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000909 NamedDecl *OldD = *I;
910
911 bool OldIsUsingDecl = false;
912 if (isa<UsingShadowDecl>(OldD)) {
913 OldIsUsingDecl = true;
914
915 // We can always introduce two using declarations into the same
916 // context, even if they have identical signatures.
917 if (NewIsUsingDecl) continue;
918
919 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
920 }
921
922 // If either declaration was introduced by a using declaration,
923 // we'll need to use slightly different rules for matching.
924 // Essentially, these rules are the normal rules, except that
925 // function templates hide function templates with different
926 // return types or template parameter lists.
927 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000928 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
929 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000930
John McCall51fa86f2009-12-02 08:47:38 +0000931 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000932 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
933 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
934 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
935 continue;
936 }
937
John McCall871b2e72009-12-09 03:35:25 +0000938 Match = *I;
939 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000940 }
John McCall51fa86f2009-12-02 08:47:38 +0000941 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000942 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
943 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
944 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
945 continue;
946 }
947
Rafael Espindola90cc3902013-04-15 12:49:13 +0000948 if (!shouldLinkPossiblyHiddenDecl(*I, New))
949 continue;
950
John McCall871b2e72009-12-09 03:35:25 +0000951 Match = *I;
952 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000953 }
John McCalld7945c62010-11-10 03:01:53 +0000954 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000955 // We can overload with these, which can show up when doing
956 // redeclaration checks for UsingDecls.
957 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000958 } else if (isa<TagDecl>(OldD)) {
959 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000960 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
961 // Optimistically assume that an unresolved using decl will
962 // overload; if it doesn't, we'll have to diagnose during
963 // template instantiation.
964 } else {
John McCall68263142009-11-18 22:49:29 +0000965 // (C++ 13p1):
966 // Only function declarations can be overloaded; object and type
967 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000968 Match = *I;
969 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000970 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000971 }
John McCall68263142009-11-18 22:49:29 +0000972
John McCall871b2e72009-12-09 03:35:25 +0000973 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000974}
975
Richard Smithaa4bc182013-06-30 09:48:50 +0000976bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
977 bool UseUsingDeclRules) {
978 // C++ [basic.start.main]p2: This function shall not be overloaded.
979 if (New->isMain())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000980 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000981
John McCall68263142009-11-18 22:49:29 +0000982 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
983 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
984
985 // C++ [temp.fct]p2:
986 // A function template can be overloaded with other function templates
987 // and with normal (non-template) functions.
988 if ((OldTemplate == 0) != (NewTemplate == 0))
989 return true;
990
991 // Is the function New an overload of the function Old?
Richard Smithaa4bc182013-06-30 09:48:50 +0000992 QualType OldQType = Context.getCanonicalType(Old->getType());
993 QualType NewQType = Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +0000994
995 // Compare the signatures (C++ 1.3.10) of the two functions to
996 // determine whether they are overloads. If we find any mismatch
997 // in the signature, they are overloads.
998
999 // If either of these functions is a K&R-style function (no
1000 // prototype), then we consider them to have matching signatures.
1001 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1002 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1003 return false;
1004
John McCallf4c73712011-01-19 06:33:43 +00001005 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1006 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001007
1008 // The signature of a function includes the types of its
1009 // parameters (C++ 1.3.10), which includes the presence or absence
1010 // of the ellipsis; see C++ DR 357).
1011 if (OldQType != NewQType &&
1012 (OldType->getNumArgs() != NewType->getNumArgs() ||
1013 OldType->isVariadic() != NewType->isVariadic() ||
Richard Smithaa4bc182013-06-30 09:48:50 +00001014 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001015 return true;
1016
1017 // C++ [temp.over.link]p4:
1018 // The signature of a function template consists of its function
1019 // signature, its return type and its template parameter list. The names
1020 // of the template parameters are significant only for establishing the
1021 // relationship between the template parameters and the rest of the
1022 // signature.
1023 //
1024 // We check the return type and template parameter lists for function
1025 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001026 //
1027 // However, we don't consider either of these when deciding whether
1028 // a member introduced by a shadow declaration is hidden.
1029 if (!UseUsingDeclRules && NewTemplate &&
Richard Smithaa4bc182013-06-30 09:48:50 +00001030 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1031 OldTemplate->getTemplateParameters(),
1032 false, TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001033 OldType->getResultType() != NewType->getResultType()))
1034 return true;
1035
1036 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001037 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001038 //
1039 // As part of this, also check whether one of the member functions
1040 // is static, in which case they are not overloads (C++
1041 // 13.1p2). While not part of the definition of the signature,
1042 // this check is important to determine whether these functions
1043 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001044 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1045 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001046 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001047 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1048 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1049 if (!UseUsingDeclRules &&
1050 (OldMethod->getRefQualifier() == RQ_None ||
1051 NewMethod->getRefQualifier() == RQ_None)) {
1052 // C++0x [over.load]p2:
1053 // - Member function declarations with the same name and the same
1054 // parameter-type-list as well as member function template
1055 // declarations with the same name, the same parameter-type-list, and
1056 // the same template parameter lists cannot be overloaded if any of
1057 // them, but not all, have a ref-qualifier (8.3.5).
Richard Smithaa4bc182013-06-30 09:48:50 +00001058 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001059 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Richard Smithaa4bc182013-06-30 09:48:50 +00001060 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001061 }
1062 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001063 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001064
Richard Smith21c8fa82013-01-14 05:37:29 +00001065 // We may not have applied the implicit const for a constexpr member
1066 // function yet (because we haven't yet resolved whether this is a static
1067 // or non-static member function). Add it now, on the assumption that this
1068 // is a redeclaration of OldMethod.
1069 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithaa4bc182013-06-30 09:48:50 +00001070 if (!getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
Richard Smithdb2fe732013-06-25 18:46:26 +00001071 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001072 NewQuals |= Qualifiers::Const;
1073 if (OldMethod->getTypeQualifiers() != NewQuals)
1074 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001075 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076
John McCall68263142009-11-18 22:49:29 +00001077 // The signatures match; this is not an overload.
1078 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001079}
1080
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001081/// \brief Checks availability of the function depending on the current
1082/// function context. Inside an unavailable function, unavailability is ignored.
1083///
1084/// \returns true if \arg FD is unavailable and current context is inside
1085/// an available function, false otherwise.
1086bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1087 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1088}
1089
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001090/// \brief Tries a user-defined conversion from From to ToType.
1091///
1092/// Produces an implicit conversion sequence for when a standard conversion
1093/// is not an option. See TryImplicitConversion for more information.
1094static ImplicitConversionSequence
1095TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1096 bool SuppressUserConversions,
1097 bool AllowExplicit,
1098 bool InOverloadResolution,
1099 bool CStyle,
1100 bool AllowObjCWritebackConversion) {
1101 ImplicitConversionSequence ICS;
1102
1103 if (SuppressUserConversions) {
1104 // We're not in the case above, so there is no conversion that
1105 // we can perform.
1106 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1107 return ICS;
1108 }
1109
1110 // Attempt user-defined conversion.
1111 OverloadCandidateSet Conversions(From->getExprLoc());
1112 OverloadingResult UserDefResult
1113 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1114 AllowExplicit);
1115
1116 if (UserDefResult == OR_Success) {
1117 ICS.setUserDefined();
1118 // C++ [over.ics.user]p4:
1119 // A conversion of an expression of class type to the same class
1120 // type is given Exact Match rank, and a conversion of an
1121 // expression of class type to a base class of that type is
1122 // given Conversion rank, in spite of the fact that a copy
1123 // constructor (i.e., a user-defined conversion function) is
1124 // called for those cases.
1125 if (CXXConstructorDecl *Constructor
1126 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1127 QualType FromCanon
1128 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1129 QualType ToCanon
1130 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1131 if (Constructor->isCopyConstructor() &&
1132 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1133 // Turn this into a "standard" conversion sequence, so that it
1134 // gets ranked with standard conversion sequences.
1135 ICS.setStandard();
1136 ICS.Standard.setAsIdentityConversion();
1137 ICS.Standard.setFromType(From->getType());
1138 ICS.Standard.setAllToTypes(ToType);
1139 ICS.Standard.CopyConstructor = Constructor;
1140 if (ToCanon != FromCanon)
1141 ICS.Standard.Second = ICK_Derived_To_Base;
1142 }
1143 }
1144
1145 // C++ [over.best.ics]p4:
1146 // However, when considering the argument of a user-defined
1147 // conversion function that is a candidate by 13.3.1.3 when
1148 // invoked for the copying of the temporary in the second step
1149 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1150 // 13.3.1.6 in all cases, only standard conversion sequences and
1151 // ellipsis conversion sequences are allowed.
1152 if (SuppressUserConversions && ICS.isUserDefined()) {
1153 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1154 }
1155 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1156 ICS.setAmbiguous();
1157 ICS.Ambiguous.setFromType(From->getType());
1158 ICS.Ambiguous.setToType(ToType);
1159 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1160 Cand != Conversions.end(); ++Cand)
1161 if (Cand->Viable)
1162 ICS.Ambiguous.addConversion(Cand->Function);
1163 } else {
1164 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1165 }
1166
1167 return ICS;
1168}
1169
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001170/// TryImplicitConversion - Attempt to perform an implicit conversion
1171/// from the given expression (Expr) to the given type (ToType). This
1172/// function returns an implicit conversion sequence that can be used
1173/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001174///
1175/// void f(float f);
1176/// void g(int i) { f(i); }
1177///
1178/// this routine would produce an implicit conversion sequence to
1179/// describe the initialization of f from i, which will be a standard
1180/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1181/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1182//
1183/// Note that this routine only determines how the conversion can be
1184/// performed; it does not actually perform the conversion. As such,
1185/// it will not produce any diagnostics if no conversion is available,
1186/// but will instead return an implicit conversion sequence of kind
1187/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001188///
1189/// If @p SuppressUserConversions, then user-defined conversions are
1190/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001191/// If @p AllowExplicit, then explicit user-defined conversions are
1192/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001193///
1194/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1195/// writeback conversion, which allows __autoreleasing id* parameters to
1196/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001197static ImplicitConversionSequence
1198TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1199 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001200 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001201 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001202 bool CStyle,
1203 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001204 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001205 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001206 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001207 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001208 return ICS;
1209 }
1210
David Blaikie4e4d0842012-03-11 07:00:24 +00001211 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001212 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001213 return ICS;
1214 }
1215
Douglas Gregor604eb652010-08-11 02:15:33 +00001216 // C++ [over.ics.user]p4:
1217 // A conversion of an expression of class type to the same class
1218 // type is given Exact Match rank, and a conversion of an
1219 // expression of class type to a base class of that type is
1220 // given Conversion rank, in spite of the fact that a copy/move
1221 // constructor (i.e., a user-defined conversion function) is
1222 // called for those cases.
1223 QualType FromType = From->getType();
1224 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001225 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1226 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001227 ICS.setStandard();
1228 ICS.Standard.setAsIdentityConversion();
1229 ICS.Standard.setFromType(FromType);
1230 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001231
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001232 // We don't actually check at this point whether there is a valid
1233 // copy/move constructor, since overloading just assumes that it
1234 // exists. When we actually perform initialization, we'll find the
1235 // appropriate constructor to copy the returned object, if needed.
1236 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001237
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001238 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001239 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001240 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001241
Douglas Gregor604eb652010-08-11 02:15:33 +00001242 return ICS;
1243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001245 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1246 AllowExplicit, InOverloadResolution, CStyle,
1247 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001248}
1249
John McCallf85e1932011-06-15 23:02:42 +00001250ImplicitConversionSequence
1251Sema::TryImplicitConversion(Expr *From, QualType ToType,
1252 bool SuppressUserConversions,
1253 bool AllowExplicit,
1254 bool InOverloadResolution,
1255 bool CStyle,
1256 bool AllowObjCWritebackConversion) {
1257 return clang::TryImplicitConversion(*this, From, ToType,
1258 SuppressUserConversions, AllowExplicit,
1259 InOverloadResolution, CStyle,
1260 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001261}
1262
Douglas Gregor575c63a2010-04-16 22:27:05 +00001263/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001264/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001265/// converted expression. Flavor is the kind of conversion we're
1266/// performing, used in the error message. If @p AllowExplicit,
1267/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001268ExprResult
1269Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001270 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001271 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001272 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001273}
1274
John Wiegley429bb272011-04-08 18:41:53 +00001275ExprResult
1276Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001277 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001278 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001279 if (checkPlaceholderForOverload(*this, From))
1280 return ExprError();
1281
John McCallf85e1932011-06-15 23:02:42 +00001282 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1283 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001284 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001285 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001286
John McCall120d63c2010-08-24 20:38:10 +00001287 ICS = clang::TryImplicitConversion(*this, From, ToType,
1288 /*SuppressUserConversions=*/false,
1289 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001290 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001291 /*CStyle=*/false,
1292 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001293 return PerformImplicitConversion(From, ToType, ICS, Action);
1294}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001295
1296/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001297/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001298bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1299 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001300 if (Context.hasSameUnqualifiedType(FromType, ToType))
1301 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001302
John McCall00ccbef2010-12-21 00:44:39 +00001303 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1304 // where F adds one of the following at most once:
1305 // - a pointer
1306 // - a member pointer
1307 // - a block pointer
1308 CanQualType CanTo = Context.getCanonicalType(ToType);
1309 CanQualType CanFrom = Context.getCanonicalType(FromType);
1310 Type::TypeClass TyClass = CanTo->getTypeClass();
1311 if (TyClass != CanFrom->getTypeClass()) return false;
1312 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1313 if (TyClass == Type::Pointer) {
1314 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1315 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1316 } else if (TyClass == Type::BlockPointer) {
1317 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1318 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1319 } else if (TyClass == Type::MemberPointer) {
1320 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1321 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1322 } else {
1323 return false;
1324 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001325
John McCall00ccbef2010-12-21 00:44:39 +00001326 TyClass = CanTo->getTypeClass();
1327 if (TyClass != CanFrom->getTypeClass()) return false;
1328 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1329 return false;
1330 }
1331
1332 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1333 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1334 if (!EInfo.getNoReturn()) return false;
1335
1336 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1337 assert(QualType(FromFn, 0).isCanonical());
1338 if (QualType(FromFn, 0) != CanTo) return false;
1339
1340 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001341 return true;
1342}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001344/// \brief Determine whether the conversion from FromType to ToType is a valid
1345/// vector conversion.
1346///
1347/// \param ICK Will be set to the vector conversion kind, if this is a vector
1348/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001349static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1350 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001351 // We need at least one of these types to be a vector type to have a vector
1352 // conversion.
1353 if (!ToType->isVectorType() && !FromType->isVectorType())
1354 return false;
1355
1356 // Identical types require no conversions.
1357 if (Context.hasSameUnqualifiedType(FromType, ToType))
1358 return false;
1359
1360 // There are no conversions between extended vector types, only identity.
1361 if (ToType->isExtVectorType()) {
1362 // There are no conversions between extended vector types other than the
1363 // identity conversion.
1364 if (FromType->isExtVectorType())
1365 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001366
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001367 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001368 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001369 ICK = ICK_Vector_Splat;
1370 return true;
1371 }
1372 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001373
1374 // We can perform the conversion between vector types in the following cases:
1375 // 1)vector types are equivalent AltiVec and GCC vector types
1376 // 2)lax vector conversions are permitted and the vector types are of the
1377 // same size
1378 if (ToType->isVectorType() && FromType->isVectorType()) {
1379 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001380 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001381 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001382 ICK = ICK_Vector_Conversion;
1383 return true;
1384 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001385 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001386
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001387 return false;
1388}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389
Douglas Gregor7d000652012-04-12 20:48:09 +00001390static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1391 bool InOverloadResolution,
1392 StandardConversionSequence &SCS,
1393 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001394
Douglas Gregor60d62c22008-10-31 16:23:19 +00001395/// IsStandardConversion - Determines whether there is a standard
1396/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1397/// expression From to the type ToType. Standard conversion sequences
1398/// only consider non-class types; for conversions that involve class
1399/// types, use TryImplicitConversion. If a conversion exists, SCS will
1400/// contain the standard conversion sequence required to perform this
1401/// conversion and this routine will return true. Otherwise, this
1402/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001403static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1404 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001405 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001406 bool CStyle,
1407 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001408 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409
Douglas Gregor60d62c22008-10-31 16:23:19 +00001410 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001411 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001412 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001413 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001414 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001415 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001416
Douglas Gregorf9201e02009-02-11 23:02:49 +00001417 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001418 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001419 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001420 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001421 return false;
1422
Mike Stump1eb44332009-09-09 15:08:12 +00001423 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001424 }
1425
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001426 // The first conversion can be an lvalue-to-rvalue conversion,
1427 // array-to-pointer conversion, or function-to-pointer conversion
1428 // (C++ 4p1).
1429
John McCall120d63c2010-08-24 20:38:10 +00001430 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001431 DeclAccessPair AccessPair;
1432 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001433 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001434 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001435 // We were able to resolve the address of the overloaded function,
1436 // so we can convert to the type of that function.
1437 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001438
1439 // we can sometimes resolve &foo<int> regardless of ToType, so check
1440 // if the type matches (identity) or we are converting to bool
1441 if (!S.Context.hasSameUnqualifiedType(
1442 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1443 QualType resultTy;
1444 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001445 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001446 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1447 // otherwise, only a boolean conversion is standard
1448 if (!ToType->isBooleanType())
1449 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451
Chandler Carruth90434232011-03-29 08:08:18 +00001452 // Check if the "from" expression is taking the address of an overloaded
1453 // function and recompute the FromType accordingly. Take advantage of the
1454 // fact that non-static member functions *must* have such an address-of
1455 // expression.
1456 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1457 if (Method && !Method->isStatic()) {
1458 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1459 "Non-unary operator on non-static member address");
1460 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1461 == UO_AddrOf &&
1462 "Non-address-of operator on non-static member address");
1463 const Type *ClassType
1464 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1465 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001466 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1467 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1468 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001469 "Non-address-of operator for overloaded function expression");
1470 FromType = S.Context.getPointerType(FromType);
1471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001472
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001473 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001474 assert(S.Context.hasSameType(
1475 FromType,
1476 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001477 } else {
1478 return false;
1479 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001480 }
John McCall21480112011-08-30 00:57:29 +00001481 // Lvalue-to-rvalue conversion (C++11 4.1):
1482 // A glvalue (3.10) of a non-function, non-array type T can
1483 // be converted to a prvalue.
1484 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001485 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001486 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001487 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001488 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001489
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001490 // C11 6.3.2.1p2:
1491 // ... if the lvalue has atomic type, the value has the non-atomic version
1492 // of the type of the lvalue ...
1493 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1494 FromType = Atomic->getValueType();
1495
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001496 // If T is a non-class type, the type of the rvalue is the
1497 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001498 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1499 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001501 } else if (FromType->isArrayType()) {
1502 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001503 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001504
1505 // An lvalue or rvalue of type "array of N T" or "array of unknown
1506 // bound of T" can be converted to an rvalue of type "pointer to
1507 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001508 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001509
John McCall120d63c2010-08-24 20:38:10 +00001510 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001511 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001512 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001513
1514 // For the purpose of ranking in overload resolution
1515 // (13.3.3.1.1), this conversion is considered an
1516 // array-to-pointer conversion followed by a qualification
1517 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001518 SCS.Second = ICK_Identity;
1519 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001520 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001521 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001523 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001524 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001525 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001526 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527
1528 // An lvalue of function type T can be converted to an rvalue of
1529 // type "pointer to T." The result is a pointer to the
1530 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001531 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001532 } else {
1533 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001534 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001535 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001536 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001537
1538 // The second conversion can be an integral promotion, floating
1539 // point promotion, integral conversion, floating point conversion,
1540 // floating-integral conversion, pointer conversion,
1541 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001542 // For overloading in C, this can also be a "compatible-type"
1543 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001544 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001545 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001546 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001547 // The unqualified versions of the types are the same: there's no
1548 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001549 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001550 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001551 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001552 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001554 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001555 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001556 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001557 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001558 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001559 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001560 SCS.Second = ICK_Complex_Promotion;
1561 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001562 } else if (ToType->isBooleanType() &&
1563 (FromType->isArithmeticType() ||
1564 FromType->isAnyPointerType() ||
1565 FromType->isBlockPointerType() ||
1566 FromType->isMemberPointerType() ||
1567 FromType->isNullPtrType())) {
1568 // Boolean conversions (C++ 4.12).
1569 SCS.Second = ICK_Boolean_Conversion;
1570 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001571 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001572 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001573 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001574 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001576 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001577 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001578 SCS.Second = ICK_Complex_Conversion;
1579 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001580 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1581 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001582 // Complex-real conversions (C99 6.3.1.7)
1583 SCS.Second = ICK_Complex_Real;
1584 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001585 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001586 // Floating point conversions (C++ 4.8).
1587 SCS.Second = ICK_Floating_Conversion;
1588 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001589 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001590 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001591 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001592 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001593 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001594 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001595 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001596 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001597 SCS.Second = ICK_Block_Pointer_Conversion;
1598 } else if (AllowObjCWritebackConversion &&
1599 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1600 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001601 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1602 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001603 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001604 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001605 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001606 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001607 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001608 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001609 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001610 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001611 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001612 SCS.Second = SecondICK;
1613 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001614 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001615 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001616 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001617 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001618 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001619 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001620 // Treat a conversion that strips "noreturn" as an identity conversion.
1621 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001622 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1623 InOverloadResolution,
1624 SCS, CStyle)) {
1625 SCS.Second = ICK_TransparentUnionConversion;
1626 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001627 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1628 CStyle)) {
1629 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001630 // appropriately.
1631 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001632 } else if (ToType->isEventT() &&
1633 From->isIntegerConstantExpr(S.getASTContext()) &&
1634 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1635 SCS.Second = ICK_Zero_Event_Conversion;
1636 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001637 } else {
1638 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001639 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001640 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001641 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001642
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001643 QualType CanonFrom;
1644 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001645 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001646 bool ObjCLifetimeConversion;
1647 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1648 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001649 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001650 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001651 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001652 CanonFrom = S.Context.getCanonicalType(FromType);
1653 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001654 } else {
1655 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001656 SCS.Third = ICK_Identity;
1657
Mike Stump1eb44332009-09-09 15:08:12 +00001658 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001659 // [...] Any difference in top-level cv-qualification is
1660 // subsumed by the initialization itself and does not constitute
1661 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001662 CanonFrom = S.Context.getCanonicalType(FromType);
1663 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001664 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001665 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001666 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001667 FromType = ToType;
1668 CanonFrom = CanonTo;
1669 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001671 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001672
1673 // If we have not converted the argument type to the parameter type,
1674 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001675 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001676 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001677
Douglas Gregor60d62c22008-10-31 16:23:19 +00001678 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001679}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001680
1681static bool
1682IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1683 QualType &ToType,
1684 bool InOverloadResolution,
1685 StandardConversionSequence &SCS,
1686 bool CStyle) {
1687
1688 const RecordType *UT = ToType->getAsUnionType();
1689 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1690 return false;
1691 // The field to initialize within the transparent union.
1692 RecordDecl *UD = UT->getDecl();
1693 // It's compatible if the expression matches any of the fields.
1694 for (RecordDecl::field_iterator it = UD->field_begin(),
1695 itend = UD->field_end();
1696 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001697 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1698 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001699 ToType = it->getType();
1700 return true;
1701 }
1702 }
1703 return false;
1704}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001705
1706/// IsIntegralPromotion - Determines whether the conversion from the
1707/// expression From (whose potentially-adjusted type is FromType) to
1708/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1709/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001710bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001711 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001712 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001713 if (!To) {
1714 return false;
1715 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001716
1717 // An rvalue of type char, signed char, unsigned char, short int, or
1718 // unsigned short int can be converted to an rvalue of type int if
1719 // int can represent all the values of the source type; otherwise,
1720 // the source rvalue can be converted to an rvalue of type unsigned
1721 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001722 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1723 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001724 if (// We can promote any signed, promotable integer type to an int
1725 (FromType->isSignedIntegerType() ||
1726 // We can promote any unsigned integer type whose size is
1727 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001728 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001729 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001730 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001731 }
1732
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001733 return To->getKind() == BuiltinType::UInt;
1734 }
1735
Richard Smithe7ff9192012-09-13 21:18:54 +00001736 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001737 // A prvalue of an unscoped enumeration type whose underlying type is not
1738 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1739 // following types that can represent all the values of the enumeration
1740 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1741 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001742 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001743 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001744 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001745 // with lowest integer conversion rank (4.13) greater than the rank of long
1746 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001747 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001748 // C++11 [conv.prom]p4:
1749 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1750 // can be converted to a prvalue of its underlying type. Moreover, if
1751 // integral promotion can be applied to its underlying type, a prvalue of an
1752 // unscoped enumeration type whose underlying type is fixed can also be
1753 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001754 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1755 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1756 // provided for a scoped enumeration.
1757 if (FromEnumType->getDecl()->isScoped())
1758 return false;
1759
Richard Smithe7ff9192012-09-13 21:18:54 +00001760 // We can perform an integral promotion to the underlying type of the enum,
1761 // even if that's not the promoted type.
1762 if (FromEnumType->getDecl()->isFixed()) {
1763 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1764 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1765 IsIntegralPromotion(From, Underlying, ToType);
1766 }
1767
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001768 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001769 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001770 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001771 return Context.hasSameUnqualifiedType(ToType,
1772 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001773 }
John McCall842aef82009-12-09 09:09:27 +00001774
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001775 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001776 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1777 // to an rvalue a prvalue of the first of the following types that can
1778 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001779 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001780 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001781 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001782 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001783 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001784 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001785 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001786 // Determine whether the type we're converting from is signed or
1787 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001788 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001789 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001790
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001791 // The types we'll try to promote to, in the appropriate
1792 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001793 QualType PromoteTypes[6] = {
1794 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001795 Context.LongTy, Context.UnsignedLongTy ,
1796 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001797 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001798 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001799 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1800 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001801 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001802 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1803 // We found the type that we can promote to. If this is the
1804 // type we wanted, we have a promotion. Otherwise, no
1805 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001806 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001807 }
1808 }
1809 }
1810
1811 // An rvalue for an integral bit-field (9.6) can be converted to an
1812 // rvalue of type int if int can represent all the values of the
1813 // bit-field; otherwise, it can be converted to unsigned int if
1814 // unsigned int can represent all the values of the bit-field. If
1815 // the bit-field is larger yet, no integral promotion applies to
1816 // it. If the bit-field has an enumerated type, it is treated as any
1817 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001818 // FIXME: We should delay checking of bit-fields until we actually perform the
1819 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001820 using llvm::APSInt;
1821 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001822 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001823 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001824 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001825 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1826 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1827 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001828
Douglas Gregor86f19402008-12-20 23:49:58 +00001829 // Are we promoting to an int from a bitfield that fits in an int?
1830 if (BitWidth < ToSize ||
1831 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1832 return To->getKind() == BuiltinType::Int;
1833 }
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Douglas Gregor86f19402008-12-20 23:49:58 +00001835 // Are we promoting to an unsigned int from an unsigned bitfield
1836 // that fits into an unsigned int?
1837 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1838 return To->getKind() == BuiltinType::UInt;
1839 }
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Douglas Gregor86f19402008-12-20 23:49:58 +00001841 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001842 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001843 }
Mike Stump1eb44332009-09-09 15:08:12 +00001844
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001845 // An rvalue of type bool can be converted to an rvalue of type int,
1846 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001847 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001848 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001849 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001850
1851 return false;
1852}
1853
1854/// IsFloatingPointPromotion - Determines whether the conversion from
1855/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1856/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001857bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001858 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1859 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001860 /// An rvalue of type float can be converted to an rvalue of type
1861 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001862 if (FromBuiltin->getKind() == BuiltinType::Float &&
1863 ToBuiltin->getKind() == BuiltinType::Double)
1864 return true;
1865
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001866 // C99 6.3.1.5p1:
1867 // When a float is promoted to double or long double, or a
1868 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001869 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001870 (FromBuiltin->getKind() == BuiltinType::Float ||
1871 FromBuiltin->getKind() == BuiltinType::Double) &&
1872 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1873 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001874
1875 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001876 if (!getLangOpts().NativeHalfType &&
1877 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001878 ToBuiltin->getKind() == BuiltinType::Float)
1879 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001880 }
1881
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001882 return false;
1883}
1884
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001885/// \brief Determine if a conversion is a complex promotion.
1886///
1887/// A complex promotion is defined as a complex -> complex conversion
1888/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001889/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001890bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001891 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001892 if (!FromComplex)
1893 return false;
1894
John McCall183700f2009-09-21 23:43:11 +00001895 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001896 if (!ToComplex)
1897 return false;
1898
1899 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001900 ToComplex->getElementType()) ||
1901 IsIntegralPromotion(0, FromComplex->getElementType(),
1902 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001903}
1904
Douglas Gregorcb7de522008-11-26 23:31:11 +00001905/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1906/// the pointer type FromPtr to a pointer to type ToPointee, with the
1907/// same type qualifiers as FromPtr has on its pointee type. ToType,
1908/// if non-empty, will be a pointer to ToType that may or may not have
1909/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001910///
Mike Stump1eb44332009-09-09 15:08:12 +00001911static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001912BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001913 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001914 ASTContext &Context,
1915 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001916 assert((FromPtr->getTypeClass() == Type::Pointer ||
1917 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1918 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001919
John McCallf85e1932011-06-15 23:02:42 +00001920 /// Conversions to 'id' subsume cv-qualifier conversions.
1921 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001922 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001923
1924 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001925 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001926 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001927 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001928
John McCallf85e1932011-06-15 23:02:42 +00001929 if (StripObjCLifetime)
1930 Quals.removeObjCLifetime();
1931
Mike Stump1eb44332009-09-09 15:08:12 +00001932 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001933 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001934 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001935 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001936 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001937
1938 // Build a pointer to ToPointee. It has the right qualifiers
1939 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001940 if (isa<ObjCObjectPointerType>(ToType))
1941 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001942 return Context.getPointerType(ToPointee);
1943 }
1944
1945 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001946 QualType QualifiedCanonToPointee
1947 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001948
Douglas Gregorda80f742010-12-01 21:43:58 +00001949 if (isa<ObjCObjectPointerType>(ToType))
1950 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1951 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001952}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001953
Mike Stump1eb44332009-09-09 15:08:12 +00001954static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001955 bool InOverloadResolution,
1956 ASTContext &Context) {
1957 // Handle value-dependent integral null pointer constants correctly.
1958 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1959 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001960 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001961 return !InOverloadResolution;
1962
Douglas Gregorce940492009-09-25 04:25:58 +00001963 return Expr->isNullPointerConstant(Context,
1964 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1965 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001966}
Mike Stump1eb44332009-09-09 15:08:12 +00001967
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001968/// IsPointerConversion - Determines whether the conversion of the
1969/// expression From, which has the (possibly adjusted) type FromType,
1970/// can be converted to the type ToType via a pointer conversion (C++
1971/// 4.10). If so, returns true and places the converted type (that
1972/// might differ from ToType in its cv-qualifiers at some level) into
1973/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001974///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001975/// This routine also supports conversions to and from block pointers
1976/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1977/// pointers to interfaces. FIXME: Once we've determined the
1978/// appropriate overloading rules for Objective-C, we may want to
1979/// split the Objective-C checks into a different routine; however,
1980/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001981/// conversions, so for now they live here. IncompatibleObjC will be
1982/// set if the conversion is an allowed Objective-C conversion that
1983/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001984bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001985 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001986 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001987 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001988 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001989 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1990 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001991 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001992
Mike Stump1eb44332009-09-09 15:08:12 +00001993 // Conversion from a null pointer constant to any Objective-C pointer type.
1994 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001995 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001996 ConvertedType = ToType;
1997 return true;
1998 }
1999
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002000 // Blocks: Block pointers can be converted to void*.
2001 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002002 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002003 ConvertedType = ToType;
2004 return true;
2005 }
2006 // Blocks: A null pointer constant can be converted to a block
2007 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002008 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002009 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002010 ConvertedType = ToType;
2011 return true;
2012 }
2013
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002014 // If the left-hand-side is nullptr_t, the right side can be a null
2015 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002016 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002017 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002018 ConvertedType = ToType;
2019 return true;
2020 }
2021
Ted Kremenek6217b802009-07-29 21:53:49 +00002022 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002023 if (!ToTypePtr)
2024 return false;
2025
2026 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002027 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002028 ConvertedType = ToType;
2029 return true;
2030 }
Sebastian Redl07779722008-10-31 14:43:28 +00002031
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002032 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002033 // , including objective-c pointers.
2034 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002035 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002036 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002037 ConvertedType = BuildSimilarlyQualifiedPointerType(
2038 FromType->getAs<ObjCObjectPointerType>(),
2039 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002040 ToType, Context);
2041 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002042 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002043 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002044 if (!FromTypePtr)
2045 return false;
2046
2047 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002048
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002049 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002050 // pointer conversion, so don't do all of the work below.
2051 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2052 return false;
2053
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002054 // An rvalue of type "pointer to cv T," where T is an object type,
2055 // can be converted to an rvalue of type "pointer to cv void" (C++
2056 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002057 if (FromPointeeType->isIncompleteOrObjectType() &&
2058 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002059 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002060 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002061 ToType, Context,
2062 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002063 return true;
2064 }
2065
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002066 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002067 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002068 ToPointeeType->isVoidType()) {
2069 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2070 ToPointeeType,
2071 ToType, Context);
2072 return true;
2073 }
2074
Douglas Gregorf9201e02009-02-11 23:02:49 +00002075 // When we're overloading in C, we allow a special kind of pointer
2076 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002077 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002078 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002079 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002080 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002081 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002082 return true;
2083 }
2084
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002085 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002086 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002087 // An rvalue of type "pointer to cv D," where D is a class type,
2088 // can be converted to an rvalue of type "pointer to cv B," where
2089 // B is a base class (clause 10) of D. If B is an inaccessible
2090 // (clause 11) or ambiguous (10.2) base class of D, a program that
2091 // necessitates this conversion is ill-formed. The result of the
2092 // conversion is a pointer to the base class sub-object of the
2093 // derived class object. The null pointer value is converted to
2094 // the null pointer value of the destination type.
2095 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002096 // Note that we do not check for ambiguity or inaccessibility
2097 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002098 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002099 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002100 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002101 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002102 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002103 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002104 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002105 ToType, Context);
2106 return true;
2107 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002108
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002109 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2110 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2111 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2112 ToPointeeType,
2113 ToType, Context);
2114 return true;
2115 }
2116
Douglas Gregorc7887512008-12-19 19:13:09 +00002117 return false;
2118}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002119
2120/// \brief Adopt the given qualifiers for the given type.
2121static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2122 Qualifiers TQs = T.getQualifiers();
2123
2124 // Check whether qualifiers already match.
2125 if (TQs == Qs)
2126 return T;
2127
2128 if (Qs.compatiblyIncludes(TQs))
2129 return Context.getQualifiedType(T, Qs);
2130
2131 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2132}
Douglas Gregorc7887512008-12-19 19:13:09 +00002133
2134/// isObjCPointerConversion - Determines whether this is an
2135/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2136/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002137bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002138 QualType& ConvertedType,
2139 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002140 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002141 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002142
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002143 // The set of qualifiers on the type we're converting from.
2144 Qualifiers FromQualifiers = FromType.getQualifiers();
2145
Steve Naroff14108da2009-07-10 23:34:53 +00002146 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002147 const ObjCObjectPointerType* ToObjCPtr =
2148 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002149 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002150 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002151
Steve Naroff14108da2009-07-10 23:34:53 +00002152 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002153 // If the pointee types are the same (ignoring qualifications),
2154 // then this is not a pointer conversion.
2155 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2156 FromObjCPtr->getPointeeType()))
2157 return false;
2158
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002159 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002160 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002161 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002162 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002163 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002164 return true;
2165 }
2166 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002167 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002168 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002169 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002170 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002171 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002172 return true;
2173 }
2174 // Objective C++: We're able to convert from a pointer to an
2175 // interface to a pointer to a different interface.
2176 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002177 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2178 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002179 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002180 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2181 FromObjCPtr->getPointeeType()))
2182 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002183 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002184 ToObjCPtr->getPointeeType(),
2185 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002186 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002187 return true;
2188 }
2189
2190 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2191 // Okay: this is some kind of implicit downcast of Objective-C
2192 // interfaces, which is permitted. However, we're going to
2193 // complain about it.
2194 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002195 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002196 ToObjCPtr->getPointeeType(),
2197 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002198 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002199 return true;
2200 }
Mike Stump1eb44332009-09-09 15:08:12 +00002201 }
Steve Naroff14108da2009-07-10 23:34:53 +00002202 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002203 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002204 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002205 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002206 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002207 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002208 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002209 // to a block pointer type.
2210 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002211 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002212 return true;
2213 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002214 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002215 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002216 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002217 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002218 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002219 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002220 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002221 return true;
2222 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002223 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002224 return false;
2225
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002226 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002227 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002228 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002229 else if (const BlockPointerType *FromBlockPtr =
2230 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002231 FromPointeeType = FromBlockPtr->getPointeeType();
2232 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002233 return false;
2234
Douglas Gregorc7887512008-12-19 19:13:09 +00002235 // If we have pointers to pointers, recursively check whether this
2236 // is an Objective-C conversion.
2237 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2238 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2239 IncompatibleObjC)) {
2240 // We always complain about this conversion.
2241 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002242 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002243 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002244 return true;
2245 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002246 // Allow conversion of pointee being objective-c pointer to another one;
2247 // as in I* to id.
2248 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2249 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2250 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2251 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002252
Douglas Gregorda80f742010-12-01 21:43:58 +00002253 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002254 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002255 return true;
2256 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002257
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002258 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002259 // differences in the argument and result types are in Objective-C
2260 // pointer conversions. If so, we permit the conversion (but
2261 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002262 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002263 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002264 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002265 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002266 if (FromFunctionType && ToFunctionType) {
2267 // If the function types are exactly the same, this isn't an
2268 // Objective-C pointer conversion.
2269 if (Context.getCanonicalType(FromPointeeType)
2270 == Context.getCanonicalType(ToPointeeType))
2271 return false;
2272
2273 // Perform the quick checks that will tell us whether these
2274 // function types are obviously different.
2275 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2276 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2277 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2278 return false;
2279
2280 bool HasObjCConversion = false;
2281 if (Context.getCanonicalType(FromFunctionType->getResultType())
2282 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2283 // Okay, the types match exactly. Nothing to do.
2284 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2285 ToFunctionType->getResultType(),
2286 ConvertedType, IncompatibleObjC)) {
2287 // Okay, we have an Objective-C pointer conversion.
2288 HasObjCConversion = true;
2289 } else {
2290 // Function types are too different. Abort.
2291 return false;
2292 }
Mike Stump1eb44332009-09-09 15:08:12 +00002293
Douglas Gregorc7887512008-12-19 19:13:09 +00002294 // Check argument types.
2295 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2296 ArgIdx != NumArgs; ++ArgIdx) {
2297 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2298 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2299 if (Context.getCanonicalType(FromArgType)
2300 == Context.getCanonicalType(ToArgType)) {
2301 // Okay, the types match exactly. Nothing to do.
2302 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2303 ConvertedType, IncompatibleObjC)) {
2304 // Okay, we have an Objective-C pointer conversion.
2305 HasObjCConversion = true;
2306 } else {
2307 // Argument types are too different. Abort.
2308 return false;
2309 }
2310 }
2311
2312 if (HasObjCConversion) {
2313 // We had an Objective-C conversion. Allow this pointer
2314 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002315 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002316 IncompatibleObjC = true;
2317 return true;
2318 }
2319 }
2320
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002321 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002322}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002323
John McCallf85e1932011-06-15 23:02:42 +00002324/// \brief Determine whether this is an Objective-C writeback conversion,
2325/// used for parameter passing when performing automatic reference counting.
2326///
2327/// \param FromType The type we're converting form.
2328///
2329/// \param ToType The type we're converting to.
2330///
2331/// \param ConvertedType The type that will be produced after applying
2332/// this conversion.
2333bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2334 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002335 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002336 Context.hasSameUnqualifiedType(FromType, ToType))
2337 return false;
2338
2339 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2340 QualType ToPointee;
2341 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2342 ToPointee = ToPointer->getPointeeType();
2343 else
2344 return false;
2345
2346 Qualifiers ToQuals = ToPointee.getQualifiers();
2347 if (!ToPointee->isObjCLifetimeType() ||
2348 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002349 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002350 return false;
2351
2352 // Argument must be a pointer to __strong to __weak.
2353 QualType FromPointee;
2354 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2355 FromPointee = FromPointer->getPointeeType();
2356 else
2357 return false;
2358
2359 Qualifiers FromQuals = FromPointee.getQualifiers();
2360 if (!FromPointee->isObjCLifetimeType() ||
2361 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2362 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2363 return false;
2364
2365 // Make sure that we have compatible qualifiers.
2366 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2367 if (!ToQuals.compatiblyIncludes(FromQuals))
2368 return false;
2369
2370 // Remove qualifiers from the pointee type we're converting from; they
2371 // aren't used in the compatibility check belong, and we'll be adding back
2372 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2373 FromPointee = FromPointee.getUnqualifiedType();
2374
2375 // The unqualified form of the pointee types must be compatible.
2376 ToPointee = ToPointee.getUnqualifiedType();
2377 bool IncompatibleObjC;
2378 if (Context.typesAreCompatible(FromPointee, ToPointee))
2379 FromPointee = ToPointee;
2380 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2381 IncompatibleObjC))
2382 return false;
2383
2384 /// \brief Construct the type we're converting to, which is a pointer to
2385 /// __autoreleasing pointee.
2386 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2387 ConvertedType = Context.getPointerType(FromPointee);
2388 return true;
2389}
2390
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002391bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2392 QualType& ConvertedType) {
2393 QualType ToPointeeType;
2394 if (const BlockPointerType *ToBlockPtr =
2395 ToType->getAs<BlockPointerType>())
2396 ToPointeeType = ToBlockPtr->getPointeeType();
2397 else
2398 return false;
2399
2400 QualType FromPointeeType;
2401 if (const BlockPointerType *FromBlockPtr =
2402 FromType->getAs<BlockPointerType>())
2403 FromPointeeType = FromBlockPtr->getPointeeType();
2404 else
2405 return false;
2406 // We have pointer to blocks, check whether the only
2407 // differences in the argument and result types are in Objective-C
2408 // pointer conversions. If so, we permit the conversion.
2409
2410 const FunctionProtoType *FromFunctionType
2411 = FromPointeeType->getAs<FunctionProtoType>();
2412 const FunctionProtoType *ToFunctionType
2413 = ToPointeeType->getAs<FunctionProtoType>();
2414
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002415 if (!FromFunctionType || !ToFunctionType)
2416 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002417
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002418 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002419 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002420
2421 // Perform the quick checks that will tell us whether these
2422 // function types are obviously different.
2423 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2424 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2425 return false;
2426
2427 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2428 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2429 if (FromEInfo != ToEInfo)
2430 return false;
2431
2432 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002433 if (Context.hasSameType(FromFunctionType->getResultType(),
2434 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002435 // Okay, the types match exactly. Nothing to do.
2436 } else {
2437 QualType RHS = FromFunctionType->getResultType();
2438 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002439 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002440 !RHS.hasQualifiers() && LHS.hasQualifiers())
2441 LHS = LHS.getUnqualifiedType();
2442
2443 if (Context.hasSameType(RHS,LHS)) {
2444 // OK exact match.
2445 } else if (isObjCPointerConversion(RHS, LHS,
2446 ConvertedType, IncompatibleObjC)) {
2447 if (IncompatibleObjC)
2448 return false;
2449 // Okay, we have an Objective-C pointer conversion.
2450 }
2451 else
2452 return false;
2453 }
2454
2455 // Check argument types.
2456 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2457 ArgIdx != NumArgs; ++ArgIdx) {
2458 IncompatibleObjC = false;
2459 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2460 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2461 if (Context.hasSameType(FromArgType, ToArgType)) {
2462 // Okay, the types match exactly. Nothing to do.
2463 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2464 ConvertedType, IncompatibleObjC)) {
2465 if (IncompatibleObjC)
2466 return false;
2467 // Okay, we have an Objective-C pointer conversion.
2468 } else
2469 // Argument types are too different. Abort.
2470 return false;
2471 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002472 if (LangOpts.ObjCAutoRefCount &&
2473 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2474 ToFunctionType))
2475 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002476
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002477 ConvertedType = ToType;
2478 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002479}
2480
Richard Trieu6efd4c52011-11-23 22:32:32 +00002481enum {
2482 ft_default,
2483 ft_different_class,
2484 ft_parameter_arity,
2485 ft_parameter_mismatch,
2486 ft_return_type,
2487 ft_qualifer_mismatch
2488};
2489
2490/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2491/// function types. Catches different number of parameter, mismatch in
2492/// parameter types, and different return types.
2493void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2494 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002495 // If either type is not valid, include no extra info.
2496 if (FromType.isNull() || ToType.isNull()) {
2497 PDiag << ft_default;
2498 return;
2499 }
2500
Richard Trieu6efd4c52011-11-23 22:32:32 +00002501 // Get the function type from the pointers.
2502 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2503 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2504 *ToMember = ToType->getAs<MemberPointerType>();
2505 if (FromMember->getClass() != ToMember->getClass()) {
2506 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2507 << QualType(FromMember->getClass(), 0);
2508 return;
2509 }
2510 FromType = FromMember->getPointeeType();
2511 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002512 }
2513
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002514 if (FromType->isPointerType())
2515 FromType = FromType->getPointeeType();
2516 if (ToType->isPointerType())
2517 ToType = ToType->getPointeeType();
2518
2519 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002520 FromType = FromType.getNonReferenceType();
2521 ToType = ToType.getNonReferenceType();
2522
Richard Trieu6efd4c52011-11-23 22:32:32 +00002523 // Don't print extra info for non-specialized template functions.
2524 if (FromType->isInstantiationDependentType() &&
2525 !FromType->getAs<TemplateSpecializationType>()) {
2526 PDiag << ft_default;
2527 return;
2528 }
2529
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002530 // No extra info for same types.
2531 if (Context.hasSameType(FromType, ToType)) {
2532 PDiag << ft_default;
2533 return;
2534 }
2535
Richard Trieu6efd4c52011-11-23 22:32:32 +00002536 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2537 *ToFunction = ToType->getAs<FunctionProtoType>();
2538
2539 // Both types need to be function types.
2540 if (!FromFunction || !ToFunction) {
2541 PDiag << ft_default;
2542 return;
2543 }
2544
2545 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2546 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2547 << FromFunction->getNumArgs();
2548 return;
2549 }
2550
2551 // Handle different parameter types.
2552 unsigned ArgPos;
2553 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2554 PDiag << ft_parameter_mismatch << ArgPos + 1
2555 << ToFunction->getArgType(ArgPos)
2556 << FromFunction->getArgType(ArgPos);
2557 return;
2558 }
2559
2560 // Handle different return type.
2561 if (!Context.hasSameType(FromFunction->getResultType(),
2562 ToFunction->getResultType())) {
2563 PDiag << ft_return_type << ToFunction->getResultType()
2564 << FromFunction->getResultType();
2565 return;
2566 }
2567
2568 unsigned FromQuals = FromFunction->getTypeQuals(),
2569 ToQuals = ToFunction->getTypeQuals();
2570 if (FromQuals != ToQuals) {
2571 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2572 return;
2573 }
2574
2575 // Unable to find a difference, so add no extra info.
2576 PDiag << ft_default;
2577}
2578
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002579/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002580/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002581/// they have same number of arguments. If the parameters are different,
2582/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002583bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002584 const FunctionProtoType *NewType,
2585 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002586 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2587 N = NewType->arg_type_begin(),
2588 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Richard Trieu7ea491c2013-08-09 21:42:32 +00002589 if (!Context.hasSameType(O->getUnqualifiedType(),
2590 N->getUnqualifiedType())) {
Larisse Voufo3151b7c2013-08-06 03:57:41 +00002591 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2592 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002593 }
2594 }
2595 return true;
2596}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002597
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002598/// CheckPointerConversion - Check the pointer conversion from the
2599/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002600/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002601/// conversions for which IsPointerConversion has already returned
2602/// true. It returns true and produces a diagnostic if there was an
2603/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002604bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002605 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002606 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002607 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002608 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002609 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002610
John McCalldaa8e4e2010-11-15 09:13:47 +00002611 Kind = CK_BitCast;
2612
David Blaikie50800fc2012-08-08 17:33:31 +00002613 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2614 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2615 Expr::NPCK_ZeroExpression) {
2616 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2617 DiagRuntimeBehavior(From->getExprLoc(), From,
2618 PDiag(diag::warn_impcast_bool_to_null_pointer)
2619 << ToType << From->getSourceRange());
2620 else if (!isUnevaluatedContext())
2621 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2622 << ToType << From->getSourceRange();
2623 }
John McCall1d9b3b22011-09-09 05:25:32 +00002624 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2625 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002626 QualType FromPointeeType = FromPtrType->getPointeeType(),
2627 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002628
Douglas Gregor5fccd362010-03-03 23:55:11 +00002629 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2630 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002631 // We must have a derived-to-base conversion. Check an
2632 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002633 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2634 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002635 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002636 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002637 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002638
Anders Carlsson61faec12009-09-12 04:46:44 +00002639 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002640 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002641 }
2642 }
John McCall1d9b3b22011-09-09 05:25:32 +00002643 } else if (const ObjCObjectPointerType *ToPtrType =
2644 ToType->getAs<ObjCObjectPointerType>()) {
2645 if (const ObjCObjectPointerType *FromPtrType =
2646 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002647 // Objective-C++ conversions are always okay.
2648 // FIXME: We should have a different class of conversions for the
2649 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002650 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002651 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002652 } else if (FromType->isBlockPointerType()) {
2653 Kind = CK_BlockPointerToObjCPointerCast;
2654 } else {
2655 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002656 }
John McCall1d9b3b22011-09-09 05:25:32 +00002657 } else if (ToType->isBlockPointerType()) {
2658 if (!FromType->isBlockPointerType())
2659 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002660 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002661
2662 // We shouldn't fall into this case unless it's valid for other
2663 // reasons.
2664 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2665 Kind = CK_NullToPointer;
2666
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002667 return false;
2668}
2669
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002670/// IsMemberPointerConversion - Determines whether the conversion of the
2671/// expression From, which has the (possibly adjusted) type FromType, can be
2672/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2673/// If so, returns true and places the converted type (that might differ from
2674/// ToType in its cv-qualifiers at some level) into ConvertedType.
2675bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002676 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002677 bool InOverloadResolution,
2678 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002679 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002680 if (!ToTypePtr)
2681 return false;
2682
2683 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002684 if (From->isNullPointerConstant(Context,
2685 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2686 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002687 ConvertedType = ToType;
2688 return true;
2689 }
2690
2691 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002692 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002693 if (!FromTypePtr)
2694 return false;
2695
2696 // A pointer to member of B can be converted to a pointer to member of D,
2697 // where D is derived from B (C++ 4.11p2).
2698 QualType FromClass(FromTypePtr->getClass(), 0);
2699 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002700
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002701 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002702 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002703 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002704 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2705 ToClass.getTypePtr());
2706 return true;
2707 }
2708
2709 return false;
2710}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002711
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002712/// CheckMemberPointerConversion - Check the member pointer conversion from the
2713/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002714/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002715/// for which IsMemberPointerConversion has already returned true. It returns
2716/// true and produces a diagnostic if there was an error, or returns false
2717/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002718bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002719 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002720 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002721 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002722 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002723 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002724 if (!FromPtrType) {
2725 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002726 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002727 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002728 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002729 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002730 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002731 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002732
Ted Kremenek6217b802009-07-29 21:53:49 +00002733 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002734 assert(ToPtrType && "No member pointer cast has a target type "
2735 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002736
Sebastian Redl21593ac2009-01-28 18:33:18 +00002737 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2738 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002739
Sebastian Redl21593ac2009-01-28 18:33:18 +00002740 // FIXME: What about dependent types?
2741 assert(FromClass->isRecordType() && "Pointer into non-class.");
2742 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002743
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002744 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002745 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002746 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2747 assert(DerivationOkay &&
2748 "Should not have been called if derivation isn't OK.");
2749 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002750
Sebastian Redl21593ac2009-01-28 18:33:18 +00002751 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2752 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002753 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2754 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2755 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2756 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002757 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002758
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002759 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002760 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2761 << FromClass << ToClass << QualType(VBase, 0)
2762 << From->getSourceRange();
2763 return true;
2764 }
2765
John McCall6b2accb2010-02-10 09:31:12 +00002766 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002767 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2768 Paths.front(),
2769 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002770
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002771 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002772 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002773 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002774 return false;
2775}
2776
Douglas Gregor98cd5992008-10-21 23:43:52 +00002777/// IsQualificationConversion - Determines whether the conversion from
2778/// an rvalue of type FromType to ToType is a qualification conversion
2779/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002780///
2781/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2782/// when the qualification conversion involves a change in the Objective-C
2783/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002784bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002785Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002786 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002787 FromType = Context.getCanonicalType(FromType);
2788 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002789 ObjCLifetimeConversion = false;
2790
Douglas Gregor98cd5992008-10-21 23:43:52 +00002791 // If FromType and ToType are the same type, this is not a
2792 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002793 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002794 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002795
Douglas Gregor98cd5992008-10-21 23:43:52 +00002796 // (C++ 4.4p4):
2797 // A conversion can add cv-qualifiers at levels other than the first
2798 // in multi-level pointers, subject to the following rules: [...]
2799 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002800 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002801 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002802 // Within each iteration of the loop, we check the qualifiers to
2803 // determine if this still looks like a qualification
2804 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002805 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002806 // until there are no more pointers or pointers-to-members left to
2807 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002808 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002809
Douglas Gregor621c92a2011-04-25 18:40:17 +00002810 Qualifiers FromQuals = FromType.getQualifiers();
2811 Qualifiers ToQuals = ToType.getQualifiers();
2812
John McCallf85e1932011-06-15 23:02:42 +00002813 // Objective-C ARC:
2814 // Check Objective-C lifetime conversions.
2815 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2816 UnwrappedAnyPointer) {
2817 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2818 ObjCLifetimeConversion = true;
2819 FromQuals.removeObjCLifetime();
2820 ToQuals.removeObjCLifetime();
2821 } else {
2822 // Qualification conversions cannot cast between different
2823 // Objective-C lifetime qualifiers.
2824 return false;
2825 }
2826 }
2827
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002828 // Allow addition/removal of GC attributes but not changing GC attributes.
2829 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2830 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2831 FromQuals.removeObjCGCAttr();
2832 ToQuals.removeObjCGCAttr();
2833 }
2834
Douglas Gregor98cd5992008-10-21 23:43:52 +00002835 // -- for every j > 0, if const is in cv 1,j then const is in cv
2836 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002837 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002838 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002839
Douglas Gregor98cd5992008-10-21 23:43:52 +00002840 // -- if the cv 1,j and cv 2,j are different, then const is in
2841 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002842 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002843 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002844 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002845
Douglas Gregor98cd5992008-10-21 23:43:52 +00002846 // Keep track of whether all prior cv-qualifiers in the "to" type
2847 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002848 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002849 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002850 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002851
2852 // We are left with FromType and ToType being the pointee types
2853 // after unwrapping the original FromType and ToType the same number
2854 // of types. If we unwrapped any pointers, and if FromType and
2855 // ToType have the same unqualified type (since we checked
2856 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002857 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002858}
2859
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002860/// \brief - Determine whether this is a conversion from a scalar type to an
2861/// atomic type.
2862///
2863/// If successful, updates \c SCS's second and third steps in the conversion
2864/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002865static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2866 bool InOverloadResolution,
2867 StandardConversionSequence &SCS,
2868 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002869 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2870 if (!ToAtomic)
2871 return false;
2872
2873 StandardConversionSequence InnerSCS;
2874 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2875 InOverloadResolution, InnerSCS,
2876 CStyle, /*AllowObjCWritebackConversion=*/false))
2877 return false;
2878
2879 SCS.Second = InnerSCS.Second;
2880 SCS.setToType(1, InnerSCS.getToType(1));
2881 SCS.Third = InnerSCS.Third;
2882 SCS.QualificationIncludesObjCLifetime
2883 = InnerSCS.QualificationIncludesObjCLifetime;
2884 SCS.setToType(2, InnerSCS.getToType(2));
2885 return true;
2886}
2887
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002888static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2889 CXXConstructorDecl *Constructor,
2890 QualType Type) {
2891 const FunctionProtoType *CtorType =
2892 Constructor->getType()->getAs<FunctionProtoType>();
2893 if (CtorType->getNumArgs() > 0) {
2894 QualType FirstArg = CtorType->getArgType(0);
2895 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2896 return true;
2897 }
2898 return false;
2899}
2900
Sebastian Redl56a04282012-02-11 23:51:08 +00002901static OverloadingResult
2902IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2903 CXXRecordDecl *To,
2904 UserDefinedConversionSequence &User,
2905 OverloadCandidateSet &CandidateSet,
2906 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002907 DeclContext::lookup_result R = S.LookupConstructors(To);
2908 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002909 Con != ConEnd; ++Con) {
2910 NamedDecl *D = *Con;
2911 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2912
2913 // Find the constructor (which may be a template).
2914 CXXConstructorDecl *Constructor = 0;
2915 FunctionTemplateDecl *ConstructorTmpl
2916 = dyn_cast<FunctionTemplateDecl>(D);
2917 if (ConstructorTmpl)
2918 Constructor
2919 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2920 else
2921 Constructor = cast<CXXConstructorDecl>(D);
2922
2923 bool Usable = !Constructor->isInvalidDecl() &&
2924 S.isInitListConstructor(Constructor) &&
2925 (AllowExplicit || !Constructor->isExplicit());
2926 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002927 // If the first argument is (a reference to) the target type,
2928 // suppress conversions.
2929 bool SuppressUserConversions =
2930 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002931 if (ConstructorTmpl)
2932 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2933 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002934 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002935 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002936 else
2937 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002938 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002939 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002940 }
2941 }
2942
2943 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2944
2945 OverloadCandidateSet::iterator Best;
2946 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2947 case OR_Success: {
2948 // Record the standard conversion we used and the conversion function.
2949 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002950 QualType ThisType = Constructor->getThisType(S.Context);
2951 // Initializer lists don't have conversions as such.
2952 User.Before.setAsIdentityConversion();
2953 User.HadMultipleCandidates = HadMultipleCandidates;
2954 User.ConversionFunction = Constructor;
2955 User.FoundConversionFunction = Best->FoundDecl;
2956 User.After.setAsIdentityConversion();
2957 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2958 User.After.setAllToTypes(ToType);
2959 return OR_Success;
2960 }
2961
2962 case OR_No_Viable_Function:
2963 return OR_No_Viable_Function;
2964 case OR_Deleted:
2965 return OR_Deleted;
2966 case OR_Ambiguous:
2967 return OR_Ambiguous;
2968 }
2969
2970 llvm_unreachable("Invalid OverloadResult!");
2971}
2972
Douglas Gregor734d9862009-01-30 23:27:23 +00002973/// Determines whether there is a user-defined conversion sequence
2974/// (C++ [over.ics.user]) that converts expression From to the type
2975/// ToType. If such a conversion exists, User will contain the
2976/// user-defined conversion sequence that performs such a conversion
2977/// and this routine will return true. Otherwise, this routine returns
2978/// false and User is unspecified.
2979///
Douglas Gregor734d9862009-01-30 23:27:23 +00002980/// \param AllowExplicit true if the conversion should consider C++0x
2981/// "explicit" conversion functions as well as non-explicit conversion
2982/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002983static OverloadingResult
2984IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002985 UserDefinedConversionSequence &User,
2986 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002987 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002988 // Whether we will only visit constructors.
2989 bool ConstructorsOnly = false;
2990
2991 // If the type we are conversion to is a class type, enumerate its
2992 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002993 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002994 // C++ [over.match.ctor]p1:
2995 // When objects of class type are direct-initialized (8.5), or
2996 // copy-initialized from an expression of the same or a
2997 // derived class type (8.5), overload resolution selects the
2998 // constructor. [...] For copy-initialization, the candidate
2999 // functions are all the converting constructors (12.3.1) of
3000 // that class. The argument list is the expression-list within
3001 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003002 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003003 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003004 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003005 ConstructorsOnly = true;
3006
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003007 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003008 // RequireCompleteType may have returned true due to some invalid decl
3009 // during template instantiation, but ToType may be complete enough now
3010 // to try to recover.
3011 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003012 // We're not going to find any constructors.
3013 } else if (CXXRecordDecl *ToRecordDecl
3014 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003015
3016 Expr **Args = &From;
3017 unsigned NumArgs = 1;
3018 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003019 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003020 // But first, see if there is an init-list-constructor that will work.
Sebastian Redl56a04282012-02-11 23:51:08 +00003021 OverloadingResult Result = IsInitializerListConstructorConversion(
3022 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3023 if (Result != OR_No_Viable_Function)
3024 return Result;
3025 // Never mind.
3026 CandidateSet.clear();
3027
3028 // If we're list-initializing, we pass the individual elements as
3029 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003030 Args = InitList->getInits();
3031 NumArgs = InitList->getNumInits();
3032 ListInitializing = true;
3033 }
3034
David Blaikie3bc93e32012-12-19 00:45:41 +00003035 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3036 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003037 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003038 NamedDecl *D = *Con;
3039 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3040
Douglas Gregordec06662009-08-21 18:42:58 +00003041 // Find the constructor (which may be a template).
3042 CXXConstructorDecl *Constructor = 0;
3043 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003044 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003045 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003046 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003047 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3048 else
John McCall9aa472c2010-03-19 07:35:19 +00003049 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003050
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003051 bool Usable = !Constructor->isInvalidDecl();
3052 if (ListInitializing)
3053 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3054 else
3055 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3056 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003057 bool SuppressUserConversions = !ConstructorsOnly;
3058 if (SuppressUserConversions && ListInitializing) {
3059 SuppressUserConversions = false;
3060 if (NumArgs == 1) {
3061 // If the first argument is (a reference to) the target type,
3062 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003063 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3064 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003065 }
3066 }
Douglas Gregordec06662009-08-21 18:42:58 +00003067 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003068 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3069 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003070 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003071 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003072 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003073 // Allow one user-defined conversion when user specifies a
3074 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003075 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003076 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003077 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003078 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003079 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003080 }
3081 }
3082
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003083 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003084 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003085 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003086 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003087 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003088 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003089 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003090 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3091 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003092 std::pair<CXXRecordDecl::conversion_iterator,
3093 CXXRecordDecl::conversion_iterator>
3094 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3095 for (CXXRecordDecl::conversion_iterator
3096 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003097 DeclAccessPair FoundDecl = I.getPair();
3098 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3100 if (isa<UsingShadowDecl>(D))
3101 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3102
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003103 CXXConversionDecl *Conv;
3104 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003105 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3106 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003107 else
John McCall32daa422010-03-31 01:36:47 +00003108 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003109
3110 if (AllowExplicit || !Conv->isExplicit()) {
3111 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003112 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3113 ActingContext, From, ToType,
3114 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003115 else
John McCall120d63c2010-08-24 20:38:10 +00003116 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3117 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003118 }
3119 }
3120 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003121 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003122
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003123 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3124
Douglas Gregor60d62c22008-10-31 16:23:19 +00003125 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003126 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003127 case OR_Success:
3128 // Record the standard conversion we used and the conversion function.
3129 if (CXXConstructorDecl *Constructor
3130 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3131 // C++ [over.ics.user]p1:
3132 // If the user-defined conversion is specified by a
3133 // constructor (12.3.1), the initial standard conversion
3134 // sequence converts the source type to the type required by
3135 // the argument of the constructor.
3136 //
3137 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003138 if (isa<InitListExpr>(From)) {
3139 // Initializer lists don't have conversions as such.
3140 User.Before.setAsIdentityConversion();
3141 } else {
3142 if (Best->Conversions[0].isEllipsis())
3143 User.EllipsisConversion = true;
3144 else {
3145 User.Before = Best->Conversions[0].Standard;
3146 User.EllipsisConversion = false;
3147 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003148 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003149 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003150 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003151 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003152 User.After.setAsIdentityConversion();
3153 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3154 User.After.setAllToTypes(ToType);
3155 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003156 }
3157 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003158 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3159 // C++ [over.ics.user]p1:
3160 //
3161 // [...] If the user-defined conversion is specified by a
3162 // conversion function (12.3.2), the initial standard
3163 // conversion sequence converts the source type to the
3164 // implicit object parameter of the conversion function.
3165 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003166 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003167 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003168 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003169 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003170
John McCall120d63c2010-08-24 20:38:10 +00003171 // C++ [over.ics.user]p2:
3172 // The second standard conversion sequence converts the
3173 // result of the user-defined conversion to the target type
3174 // for the sequence. Since an implicit conversion sequence
3175 // is an initialization, the special rules for
3176 // initialization by user-defined conversion apply when
3177 // selecting the best user-defined conversion for a
3178 // user-defined conversion sequence (see 13.3.3 and
3179 // 13.3.3.1).
3180 User.After = Best->FinalConversion;
3181 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003182 }
David Blaikie7530c032012-01-17 06:56:22 +00003183 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003184
John McCall120d63c2010-08-24 20:38:10 +00003185 case OR_No_Viable_Function:
3186 return OR_No_Viable_Function;
3187 case OR_Deleted:
3188 // No conversion here! We're done.
3189 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003190
John McCall120d63c2010-08-24 20:38:10 +00003191 case OR_Ambiguous:
3192 return OR_Ambiguous;
3193 }
3194
David Blaikie7530c032012-01-17 06:56:22 +00003195 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003196}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003197
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003198bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003199Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003200 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003201 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003202 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003203 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003204 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003205 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003206 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003207 diag::err_typecheck_ambiguous_condition)
3208 << From->getType() << ToType << From->getSourceRange();
Larisse Voufo7419d012013-06-27 01:50:25 +00003209 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty()) {
Larisse Voufo288f76a2013-06-27 03:36:30 +00003210 if (!RequireCompleteType(From->getLocStart(), ToType,
Larisse Voufo7419d012013-06-27 01:50:25 +00003211 diag::err_typecheck_nonviable_condition_incomplete,
3212 From->getType(), From->getSourceRange()))
3213 Diag(From->getLocStart(),
3214 diag::err_typecheck_nonviable_condition)
3215 << From->getType() << From->getSourceRange() << ToType;
3216 }
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003217 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003218 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003219 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003220 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003221}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003222
Douglas Gregorb734e242012-02-22 17:32:19 +00003223/// \brief Compare the user-defined conversion functions or constructors
3224/// of two user-defined conversion sequences to determine whether any ordering
3225/// is possible.
3226static ImplicitConversionSequence::CompareKind
3227compareConversionFunctions(Sema &S,
3228 FunctionDecl *Function1,
3229 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003230 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003231 return ImplicitConversionSequence::Indistinguishable;
3232
3233 // Objective-C++:
3234 // If both conversion functions are implicitly-declared conversions from
3235 // a lambda closure type to a function pointer and a block pointer,
3236 // respectively, always prefer the conversion to a function pointer,
3237 // because the function pointer is more lightweight and is more likely
3238 // to keep code working.
3239 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3240 if (!Conv1)
3241 return ImplicitConversionSequence::Indistinguishable;
3242
3243 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3244 if (!Conv2)
3245 return ImplicitConversionSequence::Indistinguishable;
3246
3247 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3248 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3249 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3250 if (Block1 != Block2)
3251 return Block1? ImplicitConversionSequence::Worse
3252 : ImplicitConversionSequence::Better;
3253 }
3254
3255 return ImplicitConversionSequence::Indistinguishable;
3256}
3257
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003258/// CompareImplicitConversionSequences - Compare two implicit
3259/// conversion sequences to determine whether one is better than the
3260/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003261static ImplicitConversionSequence::CompareKind
3262CompareImplicitConversionSequences(Sema &S,
3263 const ImplicitConversionSequence& ICS1,
3264 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003265{
3266 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3267 // conversion sequences (as defined in 13.3.3.1)
3268 // -- a standard conversion sequence (13.3.3.1.1) is a better
3269 // conversion sequence than a user-defined conversion sequence or
3270 // an ellipsis conversion sequence, and
3271 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3272 // conversion sequence than an ellipsis conversion sequence
3273 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003274 //
John McCall1d318332010-01-12 00:44:57 +00003275 // C++0x [over.best.ics]p10:
3276 // For the purpose of ranking implicit conversion sequences as
3277 // described in 13.3.3.2, the ambiguous conversion sequence is
3278 // treated as a user-defined sequence that is indistinguishable
3279 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003280 if (ICS1.getKindRank() < ICS2.getKindRank())
3281 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003282 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003283 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003284
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003285 // The following checks require both conversion sequences to be of
3286 // the same kind.
3287 if (ICS1.getKind() != ICS2.getKind())
3288 return ImplicitConversionSequence::Indistinguishable;
3289
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003290 ImplicitConversionSequence::CompareKind Result =
3291 ImplicitConversionSequence::Indistinguishable;
3292
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003293 // Two implicit conversion sequences of the same form are
3294 // indistinguishable conversion sequences unless one of the
3295 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003296 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003297 Result = CompareStandardConversionSequences(S,
3298 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003299 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003300 // User-defined conversion sequence U1 is a better conversion
3301 // sequence than another user-defined conversion sequence U2 if
3302 // they contain the same user-defined conversion function or
3303 // constructor and if the second standard conversion sequence of
3304 // U1 is better than the second standard conversion sequence of
3305 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003306 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003307 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003308 Result = CompareStandardConversionSequences(S,
3309 ICS1.UserDefined.After,
3310 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003311 else
3312 Result = compareConversionFunctions(S,
3313 ICS1.UserDefined.ConversionFunction,
3314 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003315 }
3316
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003317 // List-initialization sequence L1 is a better conversion sequence than
3318 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3319 // for some X and L2 does not.
3320 if (Result == ImplicitConversionSequence::Indistinguishable &&
Richard Smith798186a2013-09-06 22:30:28 +00003321 !ICS1.isBad()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003322 if (ICS1.isStdInitializerListElement() &&
3323 !ICS2.isStdInitializerListElement())
3324 return ImplicitConversionSequence::Better;
3325 if (!ICS1.isStdInitializerListElement() &&
3326 ICS2.isStdInitializerListElement())
3327 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003328 }
3329
3330 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003331}
3332
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003333static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3334 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3335 Qualifiers Quals;
3336 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003337 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003338 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003339
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003340 return Context.hasSameUnqualifiedType(T1, T2);
3341}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003342
Douglas Gregorad323a82010-01-27 03:51:04 +00003343// Per 13.3.3.2p3, compare the given standard conversion sequences to
3344// determine if one is a proper subset of the other.
3345static ImplicitConversionSequence::CompareKind
3346compareStandardConversionSubsets(ASTContext &Context,
3347 const StandardConversionSequence& SCS1,
3348 const StandardConversionSequence& SCS2) {
3349 ImplicitConversionSequence::CompareKind Result
3350 = ImplicitConversionSequence::Indistinguishable;
3351
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003352 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003353 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003354 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3355 return ImplicitConversionSequence::Better;
3356 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3357 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358
Douglas Gregorad323a82010-01-27 03:51:04 +00003359 if (SCS1.Second != SCS2.Second) {
3360 if (SCS1.Second == ICK_Identity)
3361 Result = ImplicitConversionSequence::Better;
3362 else if (SCS2.Second == ICK_Identity)
3363 Result = ImplicitConversionSequence::Worse;
3364 else
3365 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003366 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003367 return ImplicitConversionSequence::Indistinguishable;
3368
3369 if (SCS1.Third == SCS2.Third) {
3370 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3371 : ImplicitConversionSequence::Indistinguishable;
3372 }
3373
3374 if (SCS1.Third == ICK_Identity)
3375 return Result == ImplicitConversionSequence::Worse
3376 ? ImplicitConversionSequence::Indistinguishable
3377 : ImplicitConversionSequence::Better;
3378
3379 if (SCS2.Third == ICK_Identity)
3380 return Result == ImplicitConversionSequence::Better
3381 ? ImplicitConversionSequence::Indistinguishable
3382 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003383
Douglas Gregorad323a82010-01-27 03:51:04 +00003384 return ImplicitConversionSequence::Indistinguishable;
3385}
3386
Douglas Gregor440a4832011-01-26 14:52:12 +00003387/// \brief Determine whether one of the given reference bindings is better
3388/// than the other based on what kind of bindings they are.
3389static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3390 const StandardConversionSequence &SCS2) {
3391 // C++0x [over.ics.rank]p3b4:
3392 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3393 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003394 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003395 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003397 // reference*.
3398 //
3399 // FIXME: Rvalue references. We're going rogue with the above edits,
3400 // because the semantics in the current C++0x working paper (N3225 at the
3401 // time of this writing) break the standard definition of std::forward
3402 // and std::reference_wrapper when dealing with references to functions.
3403 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003404 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3405 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3406 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003407
Douglas Gregor440a4832011-01-26 14:52:12 +00003408 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3409 SCS2.IsLvalueReference) ||
3410 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3411 !SCS2.IsLvalueReference);
3412}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003413
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003414/// CompareStandardConversionSequences - Compare two standard
3415/// conversion sequences to determine whether one is better than the
3416/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003417static ImplicitConversionSequence::CompareKind
3418CompareStandardConversionSequences(Sema &S,
3419 const StandardConversionSequence& SCS1,
3420 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003421{
3422 // Standard conversion sequence S1 is a better conversion sequence
3423 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3424
3425 // -- S1 is a proper subsequence of S2 (comparing the conversion
3426 // sequences in the canonical form defined by 13.3.3.1.1,
3427 // excluding any Lvalue Transformation; the identity conversion
3428 // sequence is considered to be a subsequence of any
3429 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003430 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003431 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003432 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003433
3434 // -- the rank of S1 is better than the rank of S2 (by the rules
3435 // defined below), or, if not that,
3436 ImplicitConversionRank Rank1 = SCS1.getRank();
3437 ImplicitConversionRank Rank2 = SCS2.getRank();
3438 if (Rank1 < Rank2)
3439 return ImplicitConversionSequence::Better;
3440 else if (Rank2 < Rank1)
3441 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003442
Douglas Gregor57373262008-10-22 14:17:15 +00003443 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3444 // are indistinguishable unless one of the following rules
3445 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003446
Douglas Gregor57373262008-10-22 14:17:15 +00003447 // A conversion that is not a conversion of a pointer, or
3448 // pointer to member, to bool is better than another conversion
3449 // that is such a conversion.
3450 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3451 return SCS2.isPointerConversionToBool()
3452 ? ImplicitConversionSequence::Better
3453 : ImplicitConversionSequence::Worse;
3454
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003455 // C++ [over.ics.rank]p4b2:
3456 //
3457 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003458 // conversion of B* to A* is better than conversion of B* to
3459 // void*, and conversion of A* to void* is better than conversion
3460 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003461 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003462 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003463 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003464 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003465 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3466 // Exactly one of the conversion sequences is a conversion to
3467 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003468 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3469 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003470 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3471 // Neither conversion sequence converts to a void pointer; compare
3472 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003473 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003474 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003475 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003476 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3477 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003478 // Both conversion sequences are conversions to void
3479 // pointers. Compare the source types to determine if there's an
3480 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003481 QualType FromType1 = SCS1.getFromType();
3482 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003483
3484 // Adjust the types we're converting from via the array-to-pointer
3485 // conversion, if we need to.
3486 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003487 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003488 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003489 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003490
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003491 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3492 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003493
John McCall120d63c2010-08-24 20:38:10 +00003494 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003495 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003496 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003497 return ImplicitConversionSequence::Worse;
3498
3499 // Objective-C++: If one interface is more specific than the
3500 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003501 const ObjCObjectPointerType* FromObjCPtr1
3502 = FromType1->getAs<ObjCObjectPointerType>();
3503 const ObjCObjectPointerType* FromObjCPtr2
3504 = FromType2->getAs<ObjCObjectPointerType>();
3505 if (FromObjCPtr1 && FromObjCPtr2) {
3506 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3507 FromObjCPtr2);
3508 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3509 FromObjCPtr1);
3510 if (AssignLeft != AssignRight) {
3511 return AssignLeft? ImplicitConversionSequence::Better
3512 : ImplicitConversionSequence::Worse;
3513 }
Douglas Gregor01919692009-12-13 21:37:05 +00003514 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003515 }
Douglas Gregor57373262008-10-22 14:17:15 +00003516
3517 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3518 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003519 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003520 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003521 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003522
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003523 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003524 // Check for a better reference binding based on the kind of bindings.
3525 if (isBetterReferenceBindingKind(SCS1, SCS2))
3526 return ImplicitConversionSequence::Better;
3527 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3528 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003529
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003530 // C++ [over.ics.rank]p3b4:
3531 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3532 // which the references refer are the same type except for
3533 // top-level cv-qualifiers, and the type to which the reference
3534 // initialized by S2 refers is more cv-qualified than the type
3535 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003536 QualType T1 = SCS1.getToType(2);
3537 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003538 T1 = S.Context.getCanonicalType(T1);
3539 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003540 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003541 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3542 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003543 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003544 // Objective-C++ ARC: If the references refer to objects with different
3545 // lifetimes, prefer bindings that don't change lifetime.
3546 if (SCS1.ObjCLifetimeConversionBinding !=
3547 SCS2.ObjCLifetimeConversionBinding) {
3548 return SCS1.ObjCLifetimeConversionBinding
3549 ? ImplicitConversionSequence::Worse
3550 : ImplicitConversionSequence::Better;
3551 }
3552
Chandler Carruth6df868e2010-12-12 08:17:55 +00003553 // If the type is an array type, promote the element qualifiers to the
3554 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003555 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003556 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003557 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003558 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003559 if (T2.isMoreQualifiedThan(T1))
3560 return ImplicitConversionSequence::Better;
3561 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003562 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003563 }
3564 }
Douglas Gregor57373262008-10-22 14:17:15 +00003565
Francois Pichet1c98d622011-09-18 21:37:37 +00003566 // In Microsoft mode, prefer an integral conversion to a
3567 // floating-to-integral conversion if the integral conversion
3568 // is between types of the same size.
3569 // For example:
3570 // void f(float);
3571 // void f(int);
3572 // int main {
3573 // long a;
3574 // f(a);
3575 // }
3576 // Here, MSVC will call f(int) instead of generating a compile error
3577 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003578 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003579 SCS1.Second == ICK_Integral_Conversion &&
3580 SCS2.Second == ICK_Floating_Integral &&
3581 S.Context.getTypeSize(SCS1.getFromType()) ==
3582 S.Context.getTypeSize(SCS1.getToType(2)))
3583 return ImplicitConversionSequence::Better;
3584
Douglas Gregor57373262008-10-22 14:17:15 +00003585 return ImplicitConversionSequence::Indistinguishable;
3586}
3587
3588/// CompareQualificationConversions - Compares two standard conversion
3589/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003590/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3591ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003592CompareQualificationConversions(Sema &S,
3593 const StandardConversionSequence& SCS1,
3594 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003595 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003596 // -- S1 and S2 differ only in their qualification conversion and
3597 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3598 // cv-qualification signature of type T1 is a proper subset of
3599 // the cv-qualification signature of type T2, and S1 is not the
3600 // deprecated string literal array-to-pointer conversion (4.2).
3601 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3602 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3603 return ImplicitConversionSequence::Indistinguishable;
3604
3605 // FIXME: the example in the standard doesn't use a qualification
3606 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003607 QualType T1 = SCS1.getToType(2);
3608 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003609 T1 = S.Context.getCanonicalType(T1);
3610 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003611 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003612 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3613 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003614
3615 // If the types are the same, we won't learn anything by unwrapped
3616 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003617 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003618 return ImplicitConversionSequence::Indistinguishable;
3619
Chandler Carruth28e318c2009-12-29 07:16:59 +00003620 // If the type is an array type, promote the element qualifiers to the type
3621 // for comparison.
3622 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003623 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003624 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003625 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003626
Mike Stump1eb44332009-09-09 15:08:12 +00003627 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003628 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003629
3630 // Objective-C++ ARC:
3631 // Prefer qualification conversions not involving a change in lifetime
3632 // to qualification conversions that do not change lifetime.
3633 if (SCS1.QualificationIncludesObjCLifetime !=
3634 SCS2.QualificationIncludesObjCLifetime) {
3635 Result = SCS1.QualificationIncludesObjCLifetime
3636 ? ImplicitConversionSequence::Worse
3637 : ImplicitConversionSequence::Better;
3638 }
3639
John McCall120d63c2010-08-24 20:38:10 +00003640 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003641 // Within each iteration of the loop, we check the qualifiers to
3642 // determine if this still looks like a qualification
3643 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003644 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003645 // until there are no more pointers or pointers-to-members left
3646 // to unwrap. This essentially mimics what
3647 // IsQualificationConversion does, but here we're checking for a
3648 // strict subset of qualifiers.
3649 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3650 // The qualifiers are the same, so this doesn't tell us anything
3651 // about how the sequences rank.
3652 ;
3653 else if (T2.isMoreQualifiedThan(T1)) {
3654 // T1 has fewer qualifiers, so it could be the better sequence.
3655 if (Result == ImplicitConversionSequence::Worse)
3656 // Neither has qualifiers that are a subset of the other's
3657 // qualifiers.
3658 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Douglas Gregor57373262008-10-22 14:17:15 +00003660 Result = ImplicitConversionSequence::Better;
3661 } else if (T1.isMoreQualifiedThan(T2)) {
3662 // T2 has fewer qualifiers, so it could be the better sequence.
3663 if (Result == ImplicitConversionSequence::Better)
3664 // Neither has qualifiers that are a subset of the other's
3665 // qualifiers.
3666 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003667
Douglas Gregor57373262008-10-22 14:17:15 +00003668 Result = ImplicitConversionSequence::Worse;
3669 } else {
3670 // Qualifiers are disjoint.
3671 return ImplicitConversionSequence::Indistinguishable;
3672 }
3673
3674 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003675 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003676 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003677 }
3678
Douglas Gregor57373262008-10-22 14:17:15 +00003679 // Check that the winning standard conversion sequence isn't using
3680 // the deprecated string literal array to pointer conversion.
3681 switch (Result) {
3682 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003683 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003684 Result = ImplicitConversionSequence::Indistinguishable;
3685 break;
3686
3687 case ImplicitConversionSequence::Indistinguishable:
3688 break;
3689
3690 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003691 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003692 Result = ImplicitConversionSequence::Indistinguishable;
3693 break;
3694 }
3695
3696 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003697}
3698
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003699/// CompareDerivedToBaseConversions - Compares two standard conversion
3700/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003701/// various kinds of derived-to-base conversions (C++
3702/// [over.ics.rank]p4b3). As part of these checks, we also look at
3703/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003704ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003705CompareDerivedToBaseConversions(Sema &S,
3706 const StandardConversionSequence& SCS1,
3707 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003708 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003709 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003710 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003711 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003712
3713 // Adjust the types we're converting from via the array-to-pointer
3714 // conversion, if we need to.
3715 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003716 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003717 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003718 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003719
3720 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003721 FromType1 = S.Context.getCanonicalType(FromType1);
3722 ToType1 = S.Context.getCanonicalType(ToType1);
3723 FromType2 = S.Context.getCanonicalType(FromType2);
3724 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003725
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003726 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003727 //
3728 // If class B is derived directly or indirectly from class A and
3729 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003730 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003731 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003732 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003733 SCS2.Second == ICK_Pointer_Conversion &&
3734 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3735 FromType1->isPointerType() && FromType2->isPointerType() &&
3736 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003737 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003738 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003739 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003740 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003741 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003742 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003743 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003744 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003745
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003746 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003747 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003748 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003749 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003750 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003751 return ImplicitConversionSequence::Worse;
3752 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003753
3754 // -- conversion of B* to A* is better than conversion of C* to A*,
3755 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003756 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003757 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003758 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003759 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003760 }
3761 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3762 SCS2.Second == ICK_Pointer_Conversion) {
3763 const ObjCObjectPointerType *FromPtr1
3764 = FromType1->getAs<ObjCObjectPointerType>();
3765 const ObjCObjectPointerType *FromPtr2
3766 = FromType2->getAs<ObjCObjectPointerType>();
3767 const ObjCObjectPointerType *ToPtr1
3768 = ToType1->getAs<ObjCObjectPointerType>();
3769 const ObjCObjectPointerType *ToPtr2
3770 = ToType2->getAs<ObjCObjectPointerType>();
3771
3772 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3773 // Apply the same conversion ranking rules for Objective-C pointer types
3774 // that we do for C++ pointers to class types. However, we employ the
3775 // Objective-C pseudo-subtyping relationship used for assignment of
3776 // Objective-C pointer types.
3777 bool FromAssignLeft
3778 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3779 bool FromAssignRight
3780 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3781 bool ToAssignLeft
3782 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3783 bool ToAssignRight
3784 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3785
3786 // A conversion to an a non-id object pointer type or qualified 'id'
3787 // type is better than a conversion to 'id'.
3788 if (ToPtr1->isObjCIdType() &&
3789 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3790 return ImplicitConversionSequence::Worse;
3791 if (ToPtr2->isObjCIdType() &&
3792 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3793 return ImplicitConversionSequence::Better;
3794
3795 // A conversion to a non-id object pointer type is better than a
3796 // conversion to a qualified 'id' type
3797 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3798 return ImplicitConversionSequence::Worse;
3799 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3800 return ImplicitConversionSequence::Better;
3801
3802 // A conversion to an a non-Class object pointer type or qualified 'Class'
3803 // type is better than a conversion to 'Class'.
3804 if (ToPtr1->isObjCClassType() &&
3805 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3806 return ImplicitConversionSequence::Worse;
3807 if (ToPtr2->isObjCClassType() &&
3808 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3809 return ImplicitConversionSequence::Better;
3810
3811 // A conversion to a non-Class object pointer type is better than a
3812 // conversion to a qualified 'Class' type.
3813 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3814 return ImplicitConversionSequence::Worse;
3815 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3816 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003817
Douglas Gregor395cc372011-01-31 18:51:41 +00003818 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3819 if (S.Context.hasSameType(FromType1, FromType2) &&
3820 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3821 (ToAssignLeft != ToAssignRight))
3822 return ToAssignLeft? ImplicitConversionSequence::Worse
3823 : ImplicitConversionSequence::Better;
3824
3825 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3826 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3827 (FromAssignLeft != FromAssignRight))
3828 return FromAssignLeft? ImplicitConversionSequence::Better
3829 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003830 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003831 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003832
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003833 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003834 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3835 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3836 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003837 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003838 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003839 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003840 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003841 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003842 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003843 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003844 ToType2->getAs<MemberPointerType>();
3845 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3846 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3847 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3848 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3849 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3850 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3851 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3852 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003853 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003854 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003855 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003856 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003857 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003858 return ImplicitConversionSequence::Better;
3859 }
3860 // conversion of B::* to C::* is better than conversion of A::* to C::*
3861 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003862 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003863 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003864 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003865 return ImplicitConversionSequence::Worse;
3866 }
3867 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003869 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003870 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003871 // -- binding of an expression of type C to a reference of type
3872 // B& is better than binding an expression of type C to a
3873 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003874 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3875 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3876 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003877 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003878 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003879 return ImplicitConversionSequence::Worse;
3880 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003881
Douglas Gregor225c41e2008-11-03 19:09:14 +00003882 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003883 // -- binding of an expression of type B to a reference of type
3884 // A& is better than binding an expression of type C to a
3885 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003886 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3887 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3888 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003889 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003890 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003891 return ImplicitConversionSequence::Worse;
3892 }
3893 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003894
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003895 return ImplicitConversionSequence::Indistinguishable;
3896}
3897
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003898/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3899/// C++ class.
3900static bool isTypeValid(QualType T) {
3901 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3902 return !Record->isInvalidDecl();
3903
3904 return true;
3905}
3906
Douglas Gregorabe183d2010-04-13 16:31:36 +00003907/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3908/// determine whether they are reference-related,
3909/// reference-compatible, reference-compatible with added
3910/// qualification, or incompatible, for use in C++ initialization by
3911/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3912/// type, and the first type (T1) is the pointee type of the reference
3913/// type being initialized.
3914Sema::ReferenceCompareResult
3915Sema::CompareReferenceRelationship(SourceLocation Loc,
3916 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003917 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003918 bool &ObjCConversion,
3919 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003920 assert(!OrigT1->isReferenceType() &&
3921 "T1 must be the pointee type of the reference type");
3922 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3923
3924 QualType T1 = Context.getCanonicalType(OrigT1);
3925 QualType T2 = Context.getCanonicalType(OrigT2);
3926 Qualifiers T1Quals, T2Quals;
3927 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3928 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3929
3930 // C++ [dcl.init.ref]p4:
3931 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3932 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3933 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003934 DerivedToBase = false;
3935 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003936 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003937 if (UnqualT1 == UnqualT2) {
3938 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003939 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003940 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3941 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003942 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003943 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3944 UnqualT2->isObjCObjectOrInterfaceType() &&
3945 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3946 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003947 else
3948 return Ref_Incompatible;
3949
3950 // At this point, we know that T1 and T2 are reference-related (at
3951 // least).
3952
3953 // If the type is an array type, promote the element qualifiers to the type
3954 // for comparison.
3955 if (isa<ArrayType>(T1) && T1Quals)
3956 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3957 if (isa<ArrayType>(T2) && T2Quals)
3958 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3959
3960 // C++ [dcl.init.ref]p4:
3961 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3962 // reference-related to T2 and cv1 is the same cv-qualification
3963 // as, or greater cv-qualification than, cv2. For purposes of
3964 // overload resolution, cases for which cv1 is greater
3965 // cv-qualification than cv2 are identified as
3966 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003967 //
3968 // Note that we also require equivalence of Objective-C GC and address-space
3969 // qualifiers when performing these computations, so that e.g., an int in
3970 // address space 1 is not reference-compatible with an int in address
3971 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003972 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3973 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3974 T1Quals.removeObjCLifetime();
3975 T2Quals.removeObjCLifetime();
3976 ObjCLifetimeConversion = true;
3977 }
3978
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003979 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003980 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003981 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003982 return Ref_Compatible_With_Added_Qualification;
3983 else
3984 return Ref_Related;
3985}
3986
Douglas Gregor604eb652010-08-11 02:15:33 +00003987/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003988/// with DeclType. Return true if something definite is found.
3989static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003990FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3991 QualType DeclType, SourceLocation DeclLoc,
3992 Expr *Init, QualType T2, bool AllowRvalues,
3993 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003994 assert(T2->isRecordType() && "Can only find conversions of record types.");
3995 CXXRecordDecl *T2RecordDecl
3996 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3997
3998 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003999 std::pair<CXXRecordDecl::conversion_iterator,
4000 CXXRecordDecl::conversion_iterator>
4001 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4002 for (CXXRecordDecl::conversion_iterator
4003 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004004 NamedDecl *D = *I;
4005 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4006 if (isa<UsingShadowDecl>(D))
4007 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4008
4009 FunctionTemplateDecl *ConvTemplate
4010 = dyn_cast<FunctionTemplateDecl>(D);
4011 CXXConversionDecl *Conv;
4012 if (ConvTemplate)
4013 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4014 else
4015 Conv = cast<CXXConversionDecl>(D);
4016
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004018 // explicit conversions, skip it.
4019 if (!AllowExplicit && Conv->isExplicit())
4020 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004021
Douglas Gregor604eb652010-08-11 02:15:33 +00004022 if (AllowRvalues) {
4023 bool DerivedToBase = false;
4024 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004025 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004026
4027 // If we are initializing an rvalue reference, don't permit conversion
4028 // functions that return lvalues.
4029 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4030 const ReferenceType *RefType
4031 = Conv->getConversionType()->getAs<LValueReferenceType>();
4032 if (RefType && !RefType->getPointeeType()->isFunctionType())
4033 continue;
4034 }
4035
Douglas Gregor604eb652010-08-11 02:15:33 +00004036 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004037 S.CompareReferenceRelationship(
4038 DeclLoc,
4039 Conv->getConversionType().getNonReferenceType()
4040 .getUnqualifiedType(),
4041 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004042 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004043 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004044 continue;
4045 } else {
4046 // If the conversion function doesn't return a reference type,
4047 // it can't be considered for this conversion. An rvalue reference
4048 // is only acceptable if its referencee is a function type.
4049
4050 const ReferenceType *RefType =
4051 Conv->getConversionType()->getAs<ReferenceType>();
4052 if (!RefType ||
4053 (!RefType->isLValueReferenceType() &&
4054 !RefType->getPointeeType()->isFunctionType()))
4055 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004056 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004057
Douglas Gregor604eb652010-08-11 02:15:33 +00004058 if (ConvTemplate)
4059 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004060 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004061 else
4062 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004063 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004064 }
4065
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004066 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4067
Sebastian Redl4680bf22010-06-30 18:13:39 +00004068 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004069 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004070 case OR_Success:
4071 // C++ [over.ics.ref]p1:
4072 //
4073 // [...] If the parameter binds directly to the result of
4074 // applying a conversion function to the argument
4075 // expression, the implicit conversion sequence is a
4076 // user-defined conversion sequence (13.3.3.1.2), with the
4077 // second standard conversion sequence either an identity
4078 // conversion or, if the conversion function returns an
4079 // entity of a type that is a derived class of the parameter
4080 // type, a derived-to-base Conversion.
4081 if (!Best->FinalConversion.DirectBinding)
4082 return false;
4083
4084 ICS.setUserDefined();
4085 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4086 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004087 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004088 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004089 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004090 ICS.UserDefined.EllipsisConversion = false;
4091 assert(ICS.UserDefined.After.ReferenceBinding &&
4092 ICS.UserDefined.After.DirectBinding &&
4093 "Expected a direct reference binding!");
4094 return true;
4095
4096 case OR_Ambiguous:
4097 ICS.setAmbiguous();
4098 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4099 Cand != CandidateSet.end(); ++Cand)
4100 if (Cand->Viable)
4101 ICS.Ambiguous.addConversion(Cand->Function);
4102 return true;
4103
4104 case OR_No_Viable_Function:
4105 case OR_Deleted:
4106 // There was no suitable conversion, or we found a deleted
4107 // conversion; continue with other checks.
4108 return false;
4109 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004110
David Blaikie7530c032012-01-17 06:56:22 +00004111 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004112}
4113
Douglas Gregorabe183d2010-04-13 16:31:36 +00004114/// \brief Compute an implicit conversion sequence for reference
4115/// initialization.
4116static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004117TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004118 SourceLocation DeclLoc,
4119 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004120 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004121 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4122
4123 // Most paths end in a failed conversion.
4124 ImplicitConversionSequence ICS;
4125 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4126
4127 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4128 QualType T2 = Init->getType();
4129
4130 // If the initializer is the address of an overloaded function, try
4131 // to resolve the overloaded function. If all goes well, T2 is the
4132 // type of the resulting function.
4133 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4134 DeclAccessPair Found;
4135 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4136 false, Found))
4137 T2 = Fn->getType();
4138 }
4139
4140 // Compute some basic properties of the types and the initializer.
4141 bool isRValRef = DeclType->isRValueReferenceType();
4142 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004143 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004144 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004145 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004146 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004147 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004148 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004149
Douglas Gregorabe183d2010-04-13 16:31:36 +00004150
Sebastian Redl4680bf22010-06-30 18:13:39 +00004151 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004152 // A reference to type "cv1 T1" is initialized by an expression
4153 // of type "cv2 T2" as follows:
4154
Sebastian Redl4680bf22010-06-30 18:13:39 +00004155 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004156 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004157 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4158 // reference-compatible with "cv2 T2," or
4159 //
4160 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4161 if (InitCategory.isLValue() &&
4162 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004163 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004164 // When a parameter of reference type binds directly (8.5.3)
4165 // to an argument expression, the implicit conversion sequence
4166 // is the identity conversion, unless the argument expression
4167 // has a type that is a derived class of the parameter type,
4168 // in which case the implicit conversion sequence is a
4169 // derived-to-base Conversion (13.3.3.1).
4170 ICS.setStandard();
4171 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004172 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4173 : ObjCConversion? ICK_Compatible_Conversion
4174 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004175 ICS.Standard.Third = ICK_Identity;
4176 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4177 ICS.Standard.setToType(0, T2);
4178 ICS.Standard.setToType(1, T1);
4179 ICS.Standard.setToType(2, T1);
4180 ICS.Standard.ReferenceBinding = true;
4181 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004182 ICS.Standard.IsLvalueReference = !isRValRef;
4183 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4184 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004185 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004186 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004187 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004188
Sebastian Redl4680bf22010-06-30 18:13:39 +00004189 // Nothing more to do: the inaccessibility/ambiguity check for
4190 // derived-to-base conversions is suppressed when we're
4191 // computing the implicit conversion sequence (C++
4192 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004193 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004194 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004195
Sebastian Redl4680bf22010-06-30 18:13:39 +00004196 // -- has a class type (i.e., T2 is a class type), where T1 is
4197 // not reference-related to T2, and can be implicitly
4198 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4199 // is reference-compatible with "cv3 T3" 92) (this
4200 // conversion is selected by enumerating the applicable
4201 // conversion functions (13.3.1.6) and choosing the best
4202 // one through overload resolution (13.3)),
4203 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004205 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004206 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4207 Init, T2, /*AllowRvalues=*/false,
4208 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004209 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004210 }
4211 }
4212
Sebastian Redl4680bf22010-06-30 18:13:39 +00004213 // -- Otherwise, the reference shall be an lvalue reference to a
4214 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004215 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004216 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004217 // We actually handle one oddity of C++ [over.ics.ref] at this
4218 // point, which is that, due to p2 (which short-circuits reference
4219 // binding by only attempting a simple conversion for non-direct
4220 // bindings) and p3's strange wording, we allow a const volatile
4221 // reference to bind to an rvalue. Hence the check for the presence
4222 // of "const" rather than checking for "const" being the only
4223 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004224 // This is also the point where rvalue references and lvalue inits no longer
4225 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004226 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004227 return ICS;
4228
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004229 // -- If the initializer expression
4230 //
4231 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004232 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004233 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4234 (InitCategory.isXValue() ||
4235 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4236 (InitCategory.isLValue() && T2->isFunctionType()))) {
4237 ICS.setStandard();
4238 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004240 : ObjCConversion? ICK_Compatible_Conversion
4241 : ICK_Identity;
4242 ICS.Standard.Third = ICK_Identity;
4243 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4244 ICS.Standard.setToType(0, T2);
4245 ICS.Standard.setToType(1, T1);
4246 ICS.Standard.setToType(2, T1);
4247 ICS.Standard.ReferenceBinding = true;
4248 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4249 // binding unless we're binding to a class prvalue.
4250 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4251 // allow the use of rvalue references in C++98/03 for the benefit of
4252 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004253 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004254 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004255 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004256 ICS.Standard.IsLvalueReference = !isRValRef;
4257 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004258 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004259 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004260 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004261 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004262 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004263 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004264
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004265 // -- has a class type (i.e., T2 is a class type), where T1 is not
4266 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004267 // an xvalue, class prvalue, or function lvalue of type
4268 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004269 // "cv3 T3",
4270 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004271 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004272 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004273 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004274 // class subobject).
4275 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004276 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004277 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4278 Init, T2, /*AllowRvalues=*/true,
4279 AllowExplicit)) {
4280 // In the second case, if the reference is an rvalue reference
4281 // and the second standard conversion sequence of the
4282 // user-defined conversion sequence includes an lvalue-to-rvalue
4283 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004284 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004285 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4286 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4287
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004288 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004289 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004290
Douglas Gregorabe183d2010-04-13 16:31:36 +00004291 // -- Otherwise, a temporary of type "cv1 T1" is created and
4292 // initialized from the initializer expression using the
4293 // rules for a non-reference copy initialization (8.5). The
4294 // reference is then bound to the temporary. If T1 is
4295 // reference-related to T2, cv1 must be the same
4296 // cv-qualification as, or greater cv-qualification than,
4297 // cv2; otherwise, the program is ill-formed.
4298 if (RefRelationship == Sema::Ref_Related) {
4299 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4300 // we would be reference-compatible or reference-compatible with
4301 // added qualification. But that wasn't the case, so the reference
4302 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004303 //
4304 // Note that we only want to check address spaces and cvr-qualifiers here.
4305 // ObjC GC and lifetime qualifiers aren't important.
4306 Qualifiers T1Quals = T1.getQualifiers();
4307 Qualifiers T2Quals = T2.getQualifiers();
4308 T1Quals.removeObjCGCAttr();
4309 T1Quals.removeObjCLifetime();
4310 T2Quals.removeObjCGCAttr();
4311 T2Quals.removeObjCLifetime();
4312 if (!T1Quals.compatiblyIncludes(T2Quals))
4313 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004314 }
4315
4316 // If at least one of the types is a class type, the types are not
4317 // related, and we aren't allowed any user conversions, the
4318 // reference binding fails. This case is important for breaking
4319 // recursion, since TryImplicitConversion below will attempt to
4320 // create a temporary through the use of a copy constructor.
4321 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4322 (T1->isRecordType() || T2->isRecordType()))
4323 return ICS;
4324
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004325 // If T1 is reference-related to T2 and the reference is an rvalue
4326 // reference, the initializer expression shall not be an lvalue.
4327 if (RefRelationship >= Sema::Ref_Related &&
4328 isRValRef && Init->Classify(S.Context).isLValue())
4329 return ICS;
4330
Douglas Gregorabe183d2010-04-13 16:31:36 +00004331 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004332 // When a parameter of reference type is not bound directly to
4333 // an argument expression, the conversion sequence is the one
4334 // required to convert the argument expression to the
4335 // underlying type of the reference according to
4336 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4337 // to copy-initializing a temporary of the underlying type with
4338 // the argument expression. Any difference in top-level
4339 // cv-qualification is subsumed by the initialization itself
4340 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004341 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4342 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004343 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004344 /*CStyle=*/false,
4345 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004346
4347 // Of course, that's still a reference binding.
4348 if (ICS.isStandard()) {
4349 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004350 ICS.Standard.IsLvalueReference = !isRValRef;
4351 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4352 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004353 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004354 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004355 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004356 // Don't allow rvalue references to bind to lvalues.
4357 if (DeclType->isRValueReferenceType()) {
4358 if (const ReferenceType *RefType
4359 = ICS.UserDefined.ConversionFunction->getResultType()
4360 ->getAs<LValueReferenceType>()) {
4361 if (!RefType->getPointeeType()->isFunctionType()) {
4362 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4363 DeclType);
4364 return ICS;
4365 }
4366 }
4367 }
4368
Douglas Gregorabe183d2010-04-13 16:31:36 +00004369 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004370 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4371 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4372 ICS.UserDefined.After.BindsToRvalue = true;
4373 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4374 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004375 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004376
Douglas Gregorabe183d2010-04-13 16:31:36 +00004377 return ICS;
4378}
4379
Sebastian Redl5405b812011-10-16 18:19:34 +00004380static ImplicitConversionSequence
4381TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4382 bool SuppressUserConversions,
4383 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004384 bool AllowObjCWritebackConversion,
4385 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004386
4387/// TryListConversion - Try to copy-initialize a value of type ToType from the
4388/// initializer list From.
4389static ImplicitConversionSequence
4390TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4391 bool SuppressUserConversions,
4392 bool InOverloadResolution,
4393 bool AllowObjCWritebackConversion) {
4394 // C++11 [over.ics.list]p1:
4395 // When an argument is an initializer list, it is not an expression and
4396 // special rules apply for converting it to a parameter type.
4397
4398 ImplicitConversionSequence Result;
4399 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
4400
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004401 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004402 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004403 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004404 return Result;
4405
Sebastian Redl5405b812011-10-16 18:19:34 +00004406 // C++11 [over.ics.list]p2:
4407 // If the parameter type is std::initializer_list<X> or "array of X" and
4408 // all the elements can be implicitly converted to X, the implicit
4409 // conversion sequence is the worst conversion necessary to convert an
4410 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004411 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004412 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004413 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004414 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004415 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004416 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004417 if (!X.isNull()) {
4418 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4419 Expr *Init = From->getInit(i);
4420 ImplicitConversionSequence ICS =
4421 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4422 InOverloadResolution,
4423 AllowObjCWritebackConversion);
4424 // If a single element isn't convertible, fail.
4425 if (ICS.isBad()) {
4426 Result = ICS;
4427 break;
4428 }
4429 // Otherwise, look for the worst conversion.
4430 if (Result.isBad() ||
4431 CompareImplicitConversionSequences(S, ICS, Result) ==
4432 ImplicitConversionSequence::Worse)
4433 Result = ICS;
4434 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004435
4436 // For an empty list, we won't have computed any conversion sequence.
4437 // Introduce the identity conversion sequence.
4438 if (From->getNumInits() == 0) {
4439 Result.setStandard();
4440 Result.Standard.setAsIdentityConversion();
4441 Result.Standard.setFromType(ToType);
4442 Result.Standard.setAllToTypes(ToType);
4443 }
4444
Sebastian Redladfb5352012-02-27 22:38:26 +00004445 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004446 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004447 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004448
4449 // C++11 [over.ics.list]p3:
4450 // Otherwise, if the parameter is a non-aggregate class X and overload
4451 // resolution chooses a single best constructor [...] the implicit
4452 // conversion sequence is a user-defined conversion sequence. If multiple
4453 // constructors are viable but none is better than the others, the
4454 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004455 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4456 // This function can deal with initializer lists.
Richard Smith798186a2013-09-06 22:30:28 +00004457 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4458 /*AllowExplicit=*/false,
4459 InOverloadResolution, /*CStyle=*/false,
4460 AllowObjCWritebackConversion);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004461 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004462
4463 // C++11 [over.ics.list]p4:
4464 // Otherwise, if the parameter has an aggregate type which can be
4465 // initialized from the initializer list [...] the implicit conversion
4466 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004467 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004468 // Type is an aggregate, argument is an init list. At this point it comes
4469 // down to checking whether the initialization works.
4470 // FIXME: Find out whether this parameter is consumed or not.
4471 InitializedEntity Entity =
4472 InitializedEntity::InitializeParameter(S.Context, ToType,
4473 /*Consumed=*/false);
4474 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4475 Result.setUserDefined();
4476 Result.UserDefined.Before.setAsIdentityConversion();
4477 // Initializer lists don't have a type.
4478 Result.UserDefined.Before.setFromType(QualType());
4479 Result.UserDefined.Before.setAllToTypes(QualType());
4480
4481 Result.UserDefined.After.setAsIdentityConversion();
4482 Result.UserDefined.After.setFromType(ToType);
4483 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004484 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004485 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004486 return Result;
4487 }
4488
4489 // C++11 [over.ics.list]p5:
4490 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004491 if (ToType->isReferenceType()) {
4492 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4493 // mention initializer lists in any way. So we go by what list-
4494 // initialization would do and try to extrapolate from that.
4495
4496 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4497
4498 // If the initializer list has a single element that is reference-related
4499 // to the parameter type, we initialize the reference from that.
4500 if (From->getNumInits() == 1) {
4501 Expr *Init = From->getInit(0);
4502
4503 QualType T2 = Init->getType();
4504
4505 // If the initializer is the address of an overloaded function, try
4506 // to resolve the overloaded function. If all goes well, T2 is the
4507 // type of the resulting function.
4508 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4509 DeclAccessPair Found;
4510 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4511 Init, ToType, false, Found))
4512 T2 = Fn->getType();
4513 }
4514
4515 // Compute some basic properties of the types and the initializer.
4516 bool dummy1 = false;
4517 bool dummy2 = false;
4518 bool dummy3 = false;
4519 Sema::ReferenceCompareResult RefRelationship
4520 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4521 dummy2, dummy3);
4522
Richard Smith3082be22013-09-06 01:22:42 +00004523 if (RefRelationship >= Sema::Ref_Related) {
Richard Smith798186a2013-09-06 22:30:28 +00004524 return TryReferenceInit(S, Init, ToType, /*FIXME*/From->getLocStart(),
4525 SuppressUserConversions,
4526 /*AllowExplicit=*/false);
Richard Smith3082be22013-09-06 01:22:42 +00004527 }
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004528 }
4529
4530 // Otherwise, we bind the reference to a temporary created from the
4531 // initializer list.
4532 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4533 InOverloadResolution,
4534 AllowObjCWritebackConversion);
4535 if (Result.isFailure())
4536 return Result;
4537 assert(!Result.isEllipsis() &&
4538 "Sub-initialization cannot result in ellipsis conversion.");
4539
4540 // Can we even bind to a temporary?
4541 if (ToType->isRValueReferenceType() ||
4542 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4543 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4544 Result.UserDefined.After;
4545 SCS.ReferenceBinding = true;
4546 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4547 SCS.BindsToRvalue = true;
4548 SCS.BindsToFunctionLvalue = false;
4549 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4550 SCS.ObjCLifetimeConversionBinding = false;
4551 } else
4552 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4553 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004554 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004555 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004556
4557 // C++11 [over.ics.list]p6:
4558 // Otherwise, if the parameter type is not a class:
4559 if (!ToType->isRecordType()) {
4560 // - if the initializer list has one element, the implicit conversion
4561 // sequence is the one required to convert the element to the
4562 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004563 unsigned NumInits = From->getNumInits();
4564 if (NumInits == 1)
4565 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4566 SuppressUserConversions,
4567 InOverloadResolution,
4568 AllowObjCWritebackConversion);
4569 // - if the initializer list has no elements, the implicit conversion
4570 // sequence is the identity conversion.
4571 else if (NumInits == 0) {
4572 Result.setStandard();
4573 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004574 Result.Standard.setFromType(ToType);
4575 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004576 }
4577 return Result;
4578 }
4579
4580 // C++11 [over.ics.list]p7:
4581 // In all cases other than those enumerated above, no conversion is possible
4582 return Result;
4583}
4584
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004585/// TryCopyInitialization - Try to copy-initialize a value of type
4586/// ToType from the expression From. Return the implicit conversion
4587/// sequence required to pass this argument, which may be a bad
4588/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004589/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004590/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004591static ImplicitConversionSequence
4592TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004593 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004594 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004595 bool AllowObjCWritebackConversion,
4596 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004597 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4598 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4599 InOverloadResolution,AllowObjCWritebackConversion);
4600
Douglas Gregorabe183d2010-04-13 16:31:36 +00004601 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004602 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004603 /*FIXME:*/From->getLocStart(),
4604 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004605 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004606
John McCall120d63c2010-08-24 20:38:10 +00004607 return TryImplicitConversion(S, From, ToType,
4608 SuppressUserConversions,
4609 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004610 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004611 /*CStyle=*/false,
4612 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004613}
4614
Anna Zaksf3546ee2011-07-28 19:46:48 +00004615static bool TryCopyInitialization(const CanQualType FromQTy,
4616 const CanQualType ToQTy,
4617 Sema &S,
4618 SourceLocation Loc,
4619 ExprValueKind FromVK) {
4620 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4621 ImplicitConversionSequence ICS =
4622 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4623
4624 return !ICS.isBad();
4625}
4626
Douglas Gregor96176b32008-11-18 23:14:02 +00004627/// TryObjectArgumentInitialization - Try to initialize the object
4628/// parameter of the given member function (@c Method) from the
4629/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004630static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004631TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004632 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004633 CXXMethodDecl *Method,
4634 CXXRecordDecl *ActingContext) {
4635 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004636 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4637 // const volatile object.
4638 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4639 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004640 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004641
4642 // Set up the conversion sequence as a "bad" conversion, to allow us
4643 // to exit early.
4644 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004645
4646 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004647 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004648 FromType = PT->getPointeeType();
4649
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004650 // When we had a pointer, it's implicitly dereferenced, so we
4651 // better have an lvalue.
4652 assert(FromClassification.isLValue());
4653 }
4654
Anders Carlssona552f7c2009-05-01 18:34:30 +00004655 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004656
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004657 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004658 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004659 // parameter is
4660 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004661 // - "lvalue reference to cv X" for functions declared without a
4662 // ref-qualifier or with the & ref-qualifier
4663 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004664 // ref-qualifier
4665 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004666 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004667 // cv-qualification on the member function declaration.
4668 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004669 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004670 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004671 // (C++ [over.match.funcs]p5). We perform a simplified version of
4672 // reference binding here, that allows class rvalues to bind to
4673 // non-constant references.
4674
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004675 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004676 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004677 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004678 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004679 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004680 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004681 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004682 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004683 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004684
4685 // Check that we have either the same type or a derived type. It
4686 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004687 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004688 ImplicitConversionKind SecondKind;
4689 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4690 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004691 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004692 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004693 else {
John McCallb1bdc622010-02-25 01:37:24 +00004694 ICS.setBad(BadConversionSequence::unrelated_class,
4695 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004696 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004697 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004698
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004699 // Check the ref-qualifier.
4700 switch (Method->getRefQualifier()) {
4701 case RQ_None:
4702 // Do nothing; we don't care about lvalueness or rvalueness.
4703 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004704
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004705 case RQ_LValue:
4706 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4707 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004708 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004709 ImplicitParamType);
4710 return ICS;
4711 }
4712 break;
4713
4714 case RQ_RValue:
4715 if (!FromClassification.isRValue()) {
4716 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004717 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004718 ImplicitParamType);
4719 return ICS;
4720 }
4721 break;
4722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004723
Douglas Gregor96176b32008-11-18 23:14:02 +00004724 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004725 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004726 ICS.Standard.setAsIdentityConversion();
4727 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004728 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004729 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004730 ICS.Standard.ReferenceBinding = true;
4731 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004732 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004733 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004734 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4735 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4736 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004737 return ICS;
4738}
4739
4740/// PerformObjectArgumentInitialization - Perform initialization of
4741/// the implicit object parameter for the given Method with the given
4742/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004743ExprResult
4744Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004746 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004747 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004748 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004749 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004750 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004751
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004752 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004753 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004754 FromRecordType = PT->getPointeeType();
4755 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004756 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004757 } else {
4758 FromRecordType = From->getType();
4759 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004760 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004761 }
4762
John McCall701c89e2009-12-03 04:06:58 +00004763 // Note that we always use the true parent context when performing
4764 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004765 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004766 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4767 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004768 if (ICS.isBad()) {
4769 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4770 Qualifiers FromQs = FromRecordType.getQualifiers();
4771 Qualifiers ToQs = DestType.getQualifiers();
4772 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4773 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004774 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004775 diag::err_member_function_call_bad_cvr)
4776 << Method->getDeclName() << FromRecordType << (CVR - 1)
4777 << From->getSourceRange();
4778 Diag(Method->getLocation(), diag::note_previous_decl)
4779 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004780 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004781 }
4782 }
4783
Daniel Dunbar96a00142012-03-09 18:35:03 +00004784 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004785 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004786 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004787 }
Mike Stump1eb44332009-09-09 15:08:12 +00004788
John Wiegley429bb272011-04-08 18:41:53 +00004789 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4790 ExprResult FromRes =
4791 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4792 if (FromRes.isInvalid())
4793 return ExprError();
4794 From = FromRes.take();
4795 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004796
Douglas Gregor5fccd362010-03-03 23:55:11 +00004797 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004798 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004799 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004800 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004801}
4802
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004803/// TryContextuallyConvertToBool - Attempt to contextually convert the
4804/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004805static ImplicitConversionSequence
4806TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004807 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004808 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004809 // FIXME: Are these flags correct?
4810 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004811 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004812 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004813 /*CStyle=*/false,
4814 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004815}
4816
4817/// PerformContextuallyConvertToBool - Perform a contextual conversion
4818/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004819ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004820 if (checkPlaceholderForOverload(*this, From))
4821 return ExprError();
4822
John McCall120d63c2010-08-24 20:38:10 +00004823 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004824 if (!ICS.isBad())
4825 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004826
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004827 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004828 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004829 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004830 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004831 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004832}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004833
Richard Smith8ef7b202012-01-18 23:55:52 +00004834/// Check that the specified conversion is permitted in a converted constant
4835/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4836/// is acceptable.
4837static bool CheckConvertedConstantConversions(Sema &S,
4838 StandardConversionSequence &SCS) {
4839 // Since we know that the target type is an integral or unscoped enumeration
4840 // type, most conversion kinds are impossible. All possible First and Third
4841 // conversions are fine.
4842 switch (SCS.Second) {
4843 case ICK_Identity:
4844 case ICK_Integral_Promotion:
4845 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004846 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004847 return true;
4848
4849 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004850 // Conversion from an integral or unscoped enumeration type to bool is
4851 // classified as ICK_Boolean_Conversion, but it's also an integral
4852 // conversion, so it's permitted in a converted constant expression.
4853 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4854 SCS.getToType(2)->isBooleanType();
4855
Richard Smith8ef7b202012-01-18 23:55:52 +00004856 case ICK_Floating_Integral:
4857 case ICK_Complex_Real:
4858 return false;
4859
4860 case ICK_Lvalue_To_Rvalue:
4861 case ICK_Array_To_Pointer:
4862 case ICK_Function_To_Pointer:
4863 case ICK_NoReturn_Adjustment:
4864 case ICK_Qualification:
4865 case ICK_Compatible_Conversion:
4866 case ICK_Vector_Conversion:
4867 case ICK_Vector_Splat:
4868 case ICK_Derived_To_Base:
4869 case ICK_Pointer_Conversion:
4870 case ICK_Pointer_Member:
4871 case ICK_Block_Pointer_Conversion:
4872 case ICK_Writeback_Conversion:
4873 case ICK_Floating_Promotion:
4874 case ICK_Complex_Promotion:
4875 case ICK_Complex_Conversion:
4876 case ICK_Floating_Conversion:
4877 case ICK_TransparentUnionConversion:
4878 llvm_unreachable("unexpected second conversion kind");
4879
4880 case ICK_Num_Conversion_Kinds:
4881 break;
4882 }
4883
4884 llvm_unreachable("unknown conversion kind");
4885}
4886
4887/// CheckConvertedConstantExpression - Check that the expression From is a
4888/// converted constant expression of type T, perform the conversion and produce
4889/// the converted expression, per C++11 [expr.const]p3.
4890ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4891 llvm::APSInt &Value,
4892 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004893 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004894 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4895
4896 if (checkPlaceholderForOverload(*this, From))
4897 return ExprError();
4898
4899 // C++11 [expr.const]p3 with proposed wording fixes:
4900 // A converted constant expression of type T is a core constant expression,
4901 // implicitly converted to a prvalue of type T, where the converted
4902 // expression is a literal constant expression and the implicit conversion
4903 // sequence contains only user-defined conversions, lvalue-to-rvalue
4904 // conversions, integral promotions, and integral conversions other than
4905 // narrowing conversions.
4906 ImplicitConversionSequence ICS =
4907 TryImplicitConversion(From, T,
4908 /*SuppressUserConversions=*/false,
4909 /*AllowExplicit=*/false,
4910 /*InOverloadResolution=*/false,
4911 /*CStyle=*/false,
4912 /*AllowObjcWritebackConversion=*/false);
4913 StandardConversionSequence *SCS = 0;
4914 switch (ICS.getKind()) {
4915 case ImplicitConversionSequence::StandardConversion:
4916 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004917 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004918 diag::err_typecheck_converted_constant_expression_disallowed)
4919 << From->getType() << From->getSourceRange() << T;
4920 SCS = &ICS.Standard;
4921 break;
4922 case ImplicitConversionSequence::UserDefinedConversion:
4923 // We are converting from class type to an integral or enumeration type, so
4924 // the Before sequence must be trivial.
4925 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004926 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004927 diag::err_typecheck_converted_constant_expression_disallowed)
4928 << From->getType() << From->getSourceRange() << T;
4929 SCS = &ICS.UserDefined.After;
4930 break;
4931 case ImplicitConversionSequence::AmbiguousConversion:
4932 case ImplicitConversionSequence::BadConversion:
4933 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004934 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004935 diag::err_typecheck_converted_constant_expression)
4936 << From->getType() << From->getSourceRange() << T;
4937 return ExprError();
4938
4939 case ImplicitConversionSequence::EllipsisConversion:
4940 llvm_unreachable("ellipsis conversion in converted constant expression");
4941 }
4942
4943 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4944 if (Result.isInvalid())
4945 return Result;
4946
4947 // Check for a narrowing implicit conversion.
4948 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004949 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004950 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4951 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004952 case NK_Variable_Narrowing:
4953 // Implicit conversion to a narrower type, and the value is not a constant
4954 // expression. We'll diagnose this in a moment.
4955 case NK_Not_Narrowing:
4956 break;
4957
4958 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004959 Diag(From->getLocStart(),
4960 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4961 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004962 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004963 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004964 break;
4965
4966 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004967 Diag(From->getLocStart(),
4968 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4969 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004970 << CCE << /*Constant*/0 << From->getType() << T;
4971 break;
4972 }
4973
4974 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004975 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00004976 Expr::EvalResult Eval;
4977 Eval.Diag = &Notes;
4978
Douglas Gregor484f6fa2013-04-08 23:24:07 +00004979 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004980 // The expression can't be folded, so we can't keep it at this position in
4981 // the AST.
4982 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004983 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004984 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004985
4986 if (Notes.empty()) {
4987 // It's a constant expression.
4988 return Result;
4989 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004990 }
4991
4992 // It's not a constant expression. Produce an appropriate diagnostic.
4993 if (Notes.size() == 1 &&
4994 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4995 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4996 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004997 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004998 << CCE << From->getSourceRange();
4999 for (unsigned I = 0; I < Notes.size(); ++I)
5000 Diag(Notes[I].first, Notes[I].second);
5001 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005002 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005003}
5004
John McCall0bcc9bc2011-09-09 06:11:02 +00005005/// dropPointerConversions - If the given standard conversion sequence
5006/// involves any pointer conversions, remove them. This may change
5007/// the result type of the conversion sequence.
5008static void dropPointerConversion(StandardConversionSequence &SCS) {
5009 if (SCS.Second == ICK_Pointer_Conversion) {
5010 SCS.Second = ICK_Identity;
5011 SCS.Third = ICK_Identity;
5012 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5013 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005014}
John McCall120d63c2010-08-24 20:38:10 +00005015
John McCall0bcc9bc2011-09-09 06:11:02 +00005016/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5017/// convert the expression From to an Objective-C pointer type.
5018static ImplicitConversionSequence
5019TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5020 // Do an implicit conversion to 'id'.
5021 QualType Ty = S.Context.getObjCIdType();
5022 ImplicitConversionSequence ICS
5023 = TryImplicitConversion(S, From, Ty,
5024 // FIXME: Are these flags correct?
5025 /*SuppressUserConversions=*/false,
5026 /*AllowExplicit=*/true,
5027 /*InOverloadResolution=*/false,
5028 /*CStyle=*/false,
5029 /*AllowObjCWritebackConversion=*/false);
5030
5031 // Strip off any final conversions to 'id'.
5032 switch (ICS.getKind()) {
5033 case ImplicitConversionSequence::BadConversion:
5034 case ImplicitConversionSequence::AmbiguousConversion:
5035 case ImplicitConversionSequence::EllipsisConversion:
5036 break;
5037
5038 case ImplicitConversionSequence::UserDefinedConversion:
5039 dropPointerConversion(ICS.UserDefined.After);
5040 break;
5041
5042 case ImplicitConversionSequence::StandardConversion:
5043 dropPointerConversion(ICS.Standard);
5044 break;
5045 }
5046
5047 return ICS;
5048}
5049
5050/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5051/// conversion of the expression From to an Objective-C pointer type.
5052ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005053 if (checkPlaceholderForOverload(*this, From))
5054 return ExprError();
5055
John McCallc12c5bb2010-05-15 11:32:37 +00005056 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005057 ImplicitConversionSequence ICS =
5058 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005059 if (!ICS.isBad())
5060 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005061 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005062}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005063
Richard Smithf39aec12012-02-04 07:07:42 +00005064/// Determine whether the provided type is an integral type, or an enumeration
5065/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005066bool Sema::ICEConvertDiagnoser::match(QualType T) {
5067 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5068 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005069}
5070
Larisse Voufo50b60b32013-06-10 06:50:24 +00005071static ExprResult
5072diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5073 Sema::ContextualImplicitConverter &Converter,
5074 QualType T, UnresolvedSetImpl &ViableConversions) {
5075
5076 if (Converter.Suppress)
5077 return ExprError();
5078
5079 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5080 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5081 CXXConversionDecl *Conv =
5082 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5083 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5084 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5085 }
5086 return SemaRef.Owned(From);
5087}
5088
5089static bool
5090diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5091 Sema::ContextualImplicitConverter &Converter,
5092 QualType T, bool HadMultipleCandidates,
5093 UnresolvedSetImpl &ExplicitConversions) {
5094 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5095 DeclAccessPair Found = ExplicitConversions[0];
5096 CXXConversionDecl *Conversion =
5097 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5098
5099 // The user probably meant to invoke the given explicit
5100 // conversion; use it.
5101 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5102 std::string TypeStr;
5103 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5104
5105 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5106 << FixItHint::CreateInsertion(From->getLocStart(),
5107 "static_cast<" + TypeStr + ">(")
5108 << FixItHint::CreateInsertion(
5109 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5110 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5111
5112 // If we aren't in a SFINAE context, build a call to the
5113 // explicit conversion function.
5114 if (SemaRef.isSFINAEContext())
5115 return true;
5116
5117 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5118 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5119 HadMultipleCandidates);
5120 if (Result.isInvalid())
5121 return true;
5122 // Record usage of conversion in an implicit cast.
5123 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5124 CK_UserDefinedConversion, Result.get(), 0,
5125 Result.get()->getValueKind());
5126 }
5127 return false;
5128}
5129
5130static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5131 Sema::ContextualImplicitConverter &Converter,
5132 QualType T, bool HadMultipleCandidates,
5133 DeclAccessPair &Found) {
5134 CXXConversionDecl *Conversion =
5135 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5136 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5137
5138 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5139 if (!Converter.SuppressConversion) {
5140 if (SemaRef.isSFINAEContext())
5141 return true;
5142
5143 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5144 << From->getSourceRange();
5145 }
5146
5147 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5148 HadMultipleCandidates);
5149 if (Result.isInvalid())
5150 return true;
5151 // Record usage of conversion in an implicit cast.
5152 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5153 CK_UserDefinedConversion, Result.get(), 0,
5154 Result.get()->getValueKind());
5155 return false;
5156}
5157
5158static ExprResult finishContextualImplicitConversion(
5159 Sema &SemaRef, SourceLocation Loc, Expr *From,
5160 Sema::ContextualImplicitConverter &Converter) {
5161 if (!Converter.match(From->getType()) && !Converter.Suppress)
5162 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5163 << From->getSourceRange();
5164
5165 return SemaRef.DefaultLvalueConversion(From);
5166}
5167
5168static void
5169collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5170 UnresolvedSetImpl &ViableConversions,
5171 OverloadCandidateSet &CandidateSet) {
5172 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5173 DeclAccessPair FoundDecl = ViableConversions[I];
5174 NamedDecl *D = FoundDecl.getDecl();
5175 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5176 if (isa<UsingShadowDecl>(D))
5177 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5178
5179 CXXConversionDecl *Conv;
5180 FunctionTemplateDecl *ConvTemplate;
5181 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5182 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5183 else
5184 Conv = cast<CXXConversionDecl>(D);
5185
5186 if (ConvTemplate)
5187 SemaRef.AddTemplateConversionCandidate(
5188 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5189 else
5190 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5191 ToType, CandidateSet);
5192 }
5193}
5194
Richard Smith097e0a22013-05-21 19:05:48 +00005195/// \brief Attempt to convert the given expression to a type which is accepted
5196/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005197///
Richard Smith097e0a22013-05-21 19:05:48 +00005198/// This routine will attempt to convert an expression of class type to a
5199/// type accepted by the specified converter. In C++11 and before, the class
5200/// must have a single non-explicit conversion function converting to a matching
5201/// type. In C++1y, there can be multiple such conversion functions, but only
5202/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005203///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005204/// \param Loc The source location of the construct that requires the
5205/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005206///
James Dennett40ae6662012-06-22 08:52:37 +00005207/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005208///
Richard Smith097e0a22013-05-21 19:05:48 +00005209/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005210///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005211/// \returns The expression, converted to an integral or enumeration type if
5212/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005213ExprResult Sema::PerformContextualImplicitConversion(
5214 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005215 // We can't perform any more checking for type-dependent expressions.
5216 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005217 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005218
Eli Friedmanceccab92012-01-26 00:26:18 +00005219 // Process placeholders immediately.
5220 if (From->hasPlaceholderType()) {
5221 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005222 if (result.isInvalid())
5223 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005224 From = result.take();
5225 }
5226
Richard Smith097e0a22013-05-21 19:05:48 +00005227 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005228 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005229 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005230 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005231
5232 // FIXME: Check for missing '()' if T is a function type?
5233
Richard Smith097e0a22013-05-21 19:05:48 +00005234 // We can only perform contextual implicit conversions on objects of class
5235 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005236 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005237 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005238 if (!Converter.Suppress)
5239 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005240 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005242
Douglas Gregorc30614b2010-06-29 23:17:37 +00005243 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005244 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005245 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005246 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005247
5248 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5249 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5250
Douglas Gregord10099e2012-05-04 16:32:21 +00005251 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005252 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005253 }
Richard Smith097e0a22013-05-21 19:05:48 +00005254 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005255
5256 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005257 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005258
Douglas Gregorc30614b2010-06-29 23:17:37 +00005259 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005260 UnresolvedSet<4>
5261 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005262 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005263 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005264 CXXRecordDecl::conversion_iterator> Conversions =
5265 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005266
Larisse Voufo50b60b32013-06-10 06:50:24 +00005267 bool HadMultipleCandidates =
5268 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005269
Larisse Voufo50b60b32013-06-10 06:50:24 +00005270 // To check that there is only one target type, in C++1y:
5271 QualType ToType;
5272 bool HasUniqueTargetType = true;
5273
5274 // Collect explicit or viable (potentially in C++1y) conversions.
5275 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5276 E = Conversions.second;
5277 I != E; ++I) {
5278 NamedDecl *D = (*I)->getUnderlyingDecl();
5279 CXXConversionDecl *Conversion;
5280 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5281 if (ConvTemplate) {
5282 if (getLangOpts().CPlusPlus1y)
5283 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5284 else
5285 continue; // C++11 does not consider conversion operator templates(?).
5286 } else
5287 Conversion = cast<CXXConversionDecl>(D);
5288
5289 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5290 "Conversion operator templates are considered potentially "
5291 "viable in C++1y");
5292
5293 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5294 if (Converter.match(CurToType) || ConvTemplate) {
5295
5296 if (Conversion->isExplicit()) {
5297 // FIXME: For C++1y, do we need this restriction?
5298 // cf. diagnoseNoViableConversion()
5299 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005300 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005301 } else {
5302 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5303 if (ToType.isNull())
5304 ToType = CurToType.getUnqualifiedType();
5305 else if (HasUniqueTargetType &&
5306 (CurToType.getUnqualifiedType() != ToType))
5307 HasUniqueTargetType = false;
5308 }
5309 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005310 }
Richard Smithf39aec12012-02-04 07:07:42 +00005311 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005313
Larisse Voufo50b60b32013-06-10 06:50:24 +00005314 if (getLangOpts().CPlusPlus1y) {
5315 // C++1y [conv]p6:
5316 // ... An expression e of class type E appearing in such a context
5317 // is said to be contextually implicitly converted to a specified
5318 // type T and is well-formed if and only if e can be implicitly
5319 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005320 // for conversion functions whose return type is cv T or reference to
5321 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005322 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005323
Larisse Voufo50b60b32013-06-10 06:50:24 +00005324 // If no unique T is found:
5325 if (ToType.isNull()) {
5326 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5327 HadMultipleCandidates,
5328 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005329 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005330 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005331 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005332
Larisse Voufo50b60b32013-06-10 06:50:24 +00005333 // If more than one unique Ts are found:
5334 if (!HasUniqueTargetType)
5335 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5336 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005337
Larisse Voufo50b60b32013-06-10 06:50:24 +00005338 // If one unique T is found:
5339 // First, build a candidate set from the previously recorded
5340 // potentially viable conversions.
5341 OverloadCandidateSet CandidateSet(Loc);
5342 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5343 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005344
Larisse Voufo50b60b32013-06-10 06:50:24 +00005345 // Then, perform overload resolution over the candidate set.
5346 OverloadCandidateSet::iterator Best;
5347 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5348 case OR_Success: {
5349 // Apply this conversion.
5350 DeclAccessPair Found =
5351 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5352 if (recordConversion(*this, Loc, From, Converter, T,
5353 HadMultipleCandidates, Found))
5354 return ExprError();
5355 break;
5356 }
5357 case OR_Ambiguous:
5358 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5359 ViableConversions);
5360 case OR_No_Viable_Function:
5361 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5362 HadMultipleCandidates,
5363 ExplicitConversions))
5364 return ExprError();
5365 // fall through 'OR_Deleted' case.
5366 case OR_Deleted:
5367 // We'll complain below about a non-integral condition type.
5368 break;
5369 }
5370 } else {
5371 switch (ViableConversions.size()) {
5372 case 0: {
5373 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5374 HadMultipleCandidates,
5375 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005376 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005377
Larisse Voufo50b60b32013-06-10 06:50:24 +00005378 // We'll complain below about a non-integral condition type.
5379 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005380 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005381 case 1: {
5382 // Apply this conversion.
5383 DeclAccessPair Found = ViableConversions[0];
5384 if (recordConversion(*this, Loc, From, Converter, T,
5385 HadMultipleCandidates, Found))
5386 return ExprError();
5387 break;
5388 }
5389 default:
5390 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5391 ViableConversions);
5392 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005393 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005394
Larisse Voufo50b60b32013-06-10 06:50:24 +00005395 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005396}
5397
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005398/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005399/// candidate functions, using the given function call arguments. If
5400/// @p SuppressUserConversions, then don't allow user-defined
5401/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005402///
James Dennett699c9042012-06-15 07:13:21 +00005403/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005404/// based on an incomplete set of function arguments. This feature is used by
5405/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005406void
5407Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005408 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005409 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005410 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005411 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005412 bool PartialOverloading,
5413 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005414 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005415 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005416 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005417 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005418 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005419
Douglas Gregor88a35142008-12-22 05:46:06 +00005420 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005421 if (!isa<CXXConstructorDecl>(Method)) {
5422 // If we get here, it's because we're calling a member function
5423 // that is named without a member access expression (e.g.,
5424 // "this->f") that was either written explicitly or created
5425 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005426 // function, e.g., X::f(). We use an empty type for the implied
5427 // object argument (C++ [over.call.func]p3), and the acting context
5428 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005429 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005430 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005431 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005432 return;
5433 }
5434 // We treat a constructor like a non-member function, since its object
5435 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005436 }
5437
Douglas Gregorfd476482009-11-13 23:59:09 +00005438 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005439 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005440
Douglas Gregor7edfb692009-11-23 12:27:39 +00005441 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005442 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005443
Douglas Gregor66724ea2009-11-14 01:20:54 +00005444 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5445 // C++ [class.copy]p3:
5446 // A member function template is never instantiated to perform the copy
5447 // of a class object to an object of its class type.
5448 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005449 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005450 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005451 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5452 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005453 return;
5454 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005455
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005456 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005457 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005458 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005459 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005460 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005461 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005462 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005463 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005464
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005465 unsigned NumArgsInProto = Proto->getNumArgs();
5466
5467 // (C++ 13.3.2p2): A candidate function having fewer than m
5468 // parameters is viable only if it has an ellipsis in its parameter
5469 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005470 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005471 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005472 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005473 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005474 return;
5475 }
5476
5477 // (C++ 13.3.2p2): A candidate function having more than m parameters
5478 // is viable only if the (m+1)st parameter has a default argument
5479 // (8.3.6). For the purposes of overload resolution, the
5480 // parameter list is truncated on the right, so that there are
5481 // exactly m parameters.
5482 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005483 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005484 // Not enough arguments.
5485 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005486 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005487 return;
5488 }
5489
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005490 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005491 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005492 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5493 if (CheckCUDATarget(Caller, Function)) {
5494 Candidate.Viable = false;
5495 Candidate.FailureKind = ovl_fail_bad_target;
5496 return;
5497 }
5498
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005499 // Determine the implicit conversion sequences for each of the
5500 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005501 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005502 if (ArgIdx < NumArgsInProto) {
5503 // (C++ 13.3.2p3): for F to be a viable function, there shall
5504 // exist for each argument an implicit conversion sequence
5505 // (13.3.3.1) that converts that argument to the corresponding
5506 // parameter of F.
5507 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005508 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005509 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005510 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005511 /*InOverloadResolution=*/true,
5512 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005513 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005514 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005515 if (Candidate.Conversions[ArgIdx].isBad()) {
5516 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005517 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005518 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005519 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005520 } else {
5521 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5522 // argument for which there is no corresponding parameter is
5523 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005524 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005525 }
5526 }
5527}
5528
Douglas Gregor063daf62009-03-13 18:40:31 +00005529/// \brief Add all of the function declarations in the given function set to
5530/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005531void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005532 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005533 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005534 bool SuppressUserConversions,
5535 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005536 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005537 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5538 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005539 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005540 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005541 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005542 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005543 Args.slice(1), CandidateSet,
5544 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005545 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005546 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005547 SuppressUserConversions);
5548 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005549 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005550 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5551 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005552 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005553 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005554 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005555 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005556 Args[0]->Classify(Context), Args.slice(1),
5557 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005558 else
John McCall9aa472c2010-03-19 07:35:19 +00005559 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005560 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005561 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005562 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005563 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005564}
5565
John McCall314be4e2009-11-17 07:50:12 +00005566/// AddMethodCandidate - Adds a named decl (which is some kind of
5567/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005568void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005569 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005570 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005571 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005572 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005573 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005574 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005575 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005576
5577 if (isa<UsingShadowDecl>(Decl))
5578 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005579
John McCall314be4e2009-11-17 07:50:12 +00005580 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5581 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5582 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005583 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5584 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005585 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005586 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005587 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005588 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005589 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005590 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005591 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005592 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005593 }
5594}
5595
Douglas Gregor96176b32008-11-18 23:14:02 +00005596/// AddMethodCandidate - Adds the given C++ member function to the set
5597/// of candidate functions, using the given function call arguments
5598/// and the object argument (@c Object). For example, in a call
5599/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5600/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5601/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005602/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005603void
John McCall9aa472c2010-03-19 07:35:19 +00005604Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005605 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005606 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005607 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005608 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005609 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005610 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005611 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005612 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005613 assert(!isa<CXXConstructorDecl>(Method) &&
5614 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005615
Douglas Gregor3f396022009-09-28 04:47:19 +00005616 if (!CandidateSet.isNewCandidate(Method))
5617 return;
5618
Douglas Gregor7edfb692009-11-23 12:27:39 +00005619 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005620 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005621
Douglas Gregor96176b32008-11-18 23:14:02 +00005622 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005623 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005624 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005625 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005626 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005627 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005628 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005629
5630 unsigned NumArgsInProto = Proto->getNumArgs();
5631
5632 // (C++ 13.3.2p2): A candidate function having fewer than m
5633 // parameters is viable only if it has an ellipsis in its parameter
5634 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005635 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005636 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005637 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005638 return;
5639 }
5640
5641 // (C++ 13.3.2p2): A candidate function having more than m parameters
5642 // is viable only if the (m+1)st parameter has a default argument
5643 // (8.3.6). For the purposes of overload resolution, the
5644 // parameter list is truncated on the right, so that there are
5645 // exactly m parameters.
5646 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005647 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005648 // Not enough arguments.
5649 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005650 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005651 return;
5652 }
5653
5654 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005655
John McCall701c89e2009-12-03 04:06:58 +00005656 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005657 // The implicit object argument is ignored.
5658 Candidate.IgnoreObjectArgument = true;
5659 else {
5660 // Determine the implicit conversion sequence for the object
5661 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005662 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005663 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5664 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005665 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005666 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005667 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005668 return;
5669 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005670 }
5671
5672 // Determine the implicit conversion sequences for each of the
5673 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005674 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005675 if (ArgIdx < NumArgsInProto) {
5676 // (C++ 13.3.2p3): for F to be a viable function, there shall
5677 // exist for each argument an implicit conversion sequence
5678 // (13.3.3.1) that converts that argument to the corresponding
5679 // parameter of F.
5680 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005681 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005682 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005683 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005684 /*InOverloadResolution=*/true,
5685 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005686 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005687 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005688 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005689 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005690 break;
5691 }
5692 } else {
5693 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5694 // argument for which there is no corresponding parameter is
5695 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005696 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005697 }
5698 }
5699}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005700
Douglas Gregor6b906862009-08-21 00:16:32 +00005701/// \brief Add a C++ member function template as a candidate to the candidate
5702/// set, using template argument deduction to produce an appropriate member
5703/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005704void
Douglas Gregor6b906862009-08-21 00:16:32 +00005705Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005706 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005707 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005708 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005709 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005710 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005711 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005712 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005713 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005714 if (!CandidateSet.isNewCandidate(MethodTmpl))
5715 return;
5716
Douglas Gregor6b906862009-08-21 00:16:32 +00005717 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005718 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005719 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005720 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005721 // candidate functions in the usual way.113) A given name can refer to one
5722 // or more function templates and also to a set of overloaded non-template
5723 // functions. In such a case, the candidate functions generated from each
5724 // function template are combined with the set of non-template candidate
5725 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005726 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005727 FunctionDecl *Specialization = 0;
5728 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005729 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5730 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005731 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005732 Candidate.FoundDecl = FoundDecl;
5733 Candidate.Function = MethodTmpl->getTemplatedDecl();
5734 Candidate.Viable = false;
5735 Candidate.FailureKind = ovl_fail_bad_deduction;
5736 Candidate.IsSurrogate = false;
5737 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005738 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005739 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005740 Info);
5741 return;
5742 }
Mike Stump1eb44332009-09-09 15:08:12 +00005743
Douglas Gregor6b906862009-08-21 00:16:32 +00005744 // Add the function template specialization produced by template argument
5745 // deduction as a candidate.
5746 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005747 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005748 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005749 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005750 ActingContext, ObjectType, ObjectClassification, Args,
5751 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005752}
5753
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005754/// \brief Add a C++ function template specialization as a candidate
5755/// in the candidate set, using template argument deduction to produce
5756/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005757void
Douglas Gregore53060f2009-06-25 22:08:12 +00005758Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005759 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005760 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005761 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005762 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005763 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005764 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5765 return;
5766
Douglas Gregore53060f2009-06-25 22:08:12 +00005767 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005768 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005769 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005770 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005771 // candidate functions in the usual way.113) A given name can refer to one
5772 // or more function templates and also to a set of overloaded non-template
5773 // functions. In such a case, the candidate functions generated from each
5774 // function template are combined with the set of non-template candidate
5775 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005776 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005777 FunctionDecl *Specialization = 0;
5778 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005779 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5780 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005781 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005782 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005783 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5784 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005785 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005786 Candidate.IsSurrogate = false;
5787 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005788 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005789 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005790 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005791 return;
5792 }
Mike Stump1eb44332009-09-09 15:08:12 +00005793
Douglas Gregore53060f2009-06-25 22:08:12 +00005794 // Add the function template specialization produced by template argument
5795 // deduction as a candidate.
5796 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005797 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005798 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005799}
Mike Stump1eb44332009-09-09 15:08:12 +00005800
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005801/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005802/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005803/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005804/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005805/// (which may or may not be the same type as the type that the
5806/// conversion function produces).
5807void
5808Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005809 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005810 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005811 Expr *From, QualType ToType,
5812 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005813 assert(!Conversion->getDescribedFunctionTemplate() &&
5814 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005815 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005816 if (!CandidateSet.isNewCandidate(Conversion))
5817 return;
5818
Richard Smith60e141e2013-05-04 07:00:32 +00005819 // If the conversion function has an undeduced return type, trigger its
5820 // deduction now.
5821 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5822 if (DeduceReturnType(Conversion, From->getExprLoc()))
5823 return;
5824 ConvType = Conversion->getConversionType().getNonReferenceType();
5825 }
5826
Douglas Gregor7edfb692009-11-23 12:27:39 +00005827 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005828 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005829
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005830 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005831 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005832 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005833 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005834 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005835 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005836 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005837 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005838 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005839 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005840 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005841
Douglas Gregorbca39322010-08-19 15:37:02 +00005842 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005843 // For conversion functions, the function is considered to be a member of
5844 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005845 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005846 //
5847 // Determine the implicit conversion sequence for the implicit
5848 // object parameter.
5849 QualType ImplicitParamType = From->getType();
5850 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5851 ImplicitParamType = FromPtrType->getPointeeType();
5852 CXXRecordDecl *ConversionContext
5853 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005854
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005855 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005856 = TryObjectArgumentInitialization(*this, From->getType(),
5857 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005858 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005859
John McCall1d318332010-01-12 00:44:57 +00005860 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005861 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005862 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005863 return;
5864 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005865
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005866 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005867 // derived to base as such conversions are given Conversion Rank. They only
5868 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5869 QualType FromCanon
5870 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5871 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5872 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5873 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005874 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005875 return;
5876 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005877
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005878 // To determine what the conversion from the result of calling the
5879 // conversion function to the type we're eventually trying to
5880 // convert to (ToType), we need to synthesize a call to the
5881 // conversion function and attempt copy initialization from it. This
5882 // makes sure that we get the right semantics with respect to
5883 // lvalues/rvalues and the type. Fortunately, we can allocate this
5884 // call on the stack and we don't need its arguments to be
5885 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005886 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005887 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005888 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5889 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005890 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005891 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005892
Richard Smith87c1f1f2011-07-13 22:53:21 +00005893 QualType ConversionType = Conversion->getConversionType();
5894 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005895 Candidate.Viable = false;
5896 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5897 return;
5898 }
5899
Richard Smith87c1f1f2011-07-13 22:53:21 +00005900 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005901
Mike Stump1eb44332009-09-09 15:08:12 +00005902 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005903 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5904 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005905 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005906 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005907 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005908 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005909 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005910 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005911 /*InOverloadResolution=*/false,
5912 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005913
John McCall1d318332010-01-12 00:44:57 +00005914 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005915 case ImplicitConversionSequence::StandardConversion:
5916 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005917
Douglas Gregorc520c842010-04-12 23:42:09 +00005918 // C++ [over.ics.user]p3:
5919 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005920 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005921 // shall have exact match rank.
5922 if (Conversion->getPrimaryTemplate() &&
5923 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5924 Candidate.Viable = false;
5925 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5926 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005927
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005928 // C++0x [dcl.init.ref]p5:
5929 // In the second case, if the reference is an rvalue reference and
5930 // the second standard conversion sequence of the user-defined
5931 // conversion sequence includes an lvalue-to-rvalue conversion, the
5932 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005933 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005934 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5935 Candidate.Viable = false;
5936 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5937 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005938 break;
5939
5940 case ImplicitConversionSequence::BadConversion:
5941 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005942 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005943 break;
5944
5945 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005946 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005947 "Can only end up with a standard conversion sequence or failure");
5948 }
5949}
5950
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005951/// \brief Adds a conversion function template specialization
5952/// candidate to the overload set, using template argument deduction
5953/// to deduce the template arguments of the conversion function
5954/// template from the type that we are converting to (C++
5955/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005956void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005957Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005958 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005959 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005960 Expr *From, QualType ToType,
5961 OverloadCandidateSet &CandidateSet) {
5962 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5963 "Only conversion function templates permitted here");
5964
Douglas Gregor3f396022009-09-28 04:47:19 +00005965 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5966 return;
5967
Craig Topper93e45992012-09-19 02:26:47 +00005968 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005969 CXXConversionDecl *Specialization = 0;
5970 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005971 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005972 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005973 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005974 Candidate.FoundDecl = FoundDecl;
5975 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5976 Candidate.Viable = false;
5977 Candidate.FailureKind = ovl_fail_bad_deduction;
5978 Candidate.IsSurrogate = false;
5979 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005980 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005981 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005982 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005983 return;
5984 }
Mike Stump1eb44332009-09-09 15:08:12 +00005985
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005986 // Add the conversion function template specialization produced by
5987 // template argument deduction as a candidate.
5988 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005989 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005990 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005991}
5992
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005993/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5994/// converts the given @c Object to a function pointer via the
5995/// conversion function @c Conversion, and then attempts to call it
5996/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5997/// the type of function that we'll eventually be calling.
5998void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005999 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006000 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006001 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006002 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006003 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006004 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006005 if (!CandidateSet.isNewCandidate(Conversion))
6006 return;
6007
Douglas Gregor7edfb692009-11-23 12:27:39 +00006008 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006009 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006010
Ahmed Charles13a140c2012-02-25 11:00:22 +00006011 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006012 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006013 Candidate.Function = 0;
6014 Candidate.Surrogate = Conversion;
6015 Candidate.Viable = true;
6016 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006017 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006018 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006019
6020 // Determine the implicit conversion sequence for the implicit
6021 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006022 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006023 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006024 Object->Classify(Context),
6025 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006026 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006027 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006028 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006029 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006030 return;
6031 }
6032
6033 // The first conversion is actually a user-defined conversion whose
6034 // first conversion is ObjectInit's standard conversion (which is
6035 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006036 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006037 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006038 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006039 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006040 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006041 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006042 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006043 = Candidate.Conversions[0].UserDefined.Before;
6044 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6045
Mike Stump1eb44332009-09-09 15:08:12 +00006046 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006047 unsigned NumArgsInProto = Proto->getNumArgs();
6048
6049 // (C++ 13.3.2p2): A candidate function having fewer than m
6050 // parameters is viable only if it has an ellipsis in its parameter
6051 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006052 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006053 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006054 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006055 return;
6056 }
6057
6058 // Function types don't have any default arguments, so just check if
6059 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006060 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006061 // Not enough arguments.
6062 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006063 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006064 return;
6065 }
6066
6067 // Determine the implicit conversion sequences for each of the
6068 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006069 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006070 if (ArgIdx < NumArgsInProto) {
6071 // (C++ 13.3.2p3): for F to be a viable function, there shall
6072 // exist for each argument an implicit conversion sequence
6073 // (13.3.3.1) that converts that argument to the corresponding
6074 // parameter of F.
6075 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006076 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006077 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006078 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006079 /*InOverloadResolution=*/false,
6080 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006081 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006082 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006083 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006084 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006085 break;
6086 }
6087 } else {
6088 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6089 // argument for which there is no corresponding parameter is
6090 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006091 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006092 }
6093 }
6094}
6095
Douglas Gregor063daf62009-03-13 18:40:31 +00006096/// \brief Add overload candidates for overloaded operators that are
6097/// member functions.
6098///
6099/// Add the overloaded operator candidates that are member functions
6100/// for the operator Op that was used in an operator expression such
6101/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6102/// CandidateSet will store the added overload candidates. (C++
6103/// [over.match.oper]).
6104void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6105 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006106 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006107 OverloadCandidateSet& CandidateSet,
6108 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006109 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6110
6111 // C++ [over.match.oper]p3:
6112 // For a unary operator @ with an operand of a type whose
6113 // cv-unqualified version is T1, and for a binary operator @ with
6114 // a left operand of a type whose cv-unqualified version is T1 and
6115 // a right operand of a type whose cv-unqualified version is T2,
6116 // three sets of candidate functions, designated member
6117 // candidates, non-member candidates and built-in candidates, are
6118 // constructed as follows:
6119 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006120
Richard Smithe410be92013-04-20 12:41:22 +00006121 // -- If T1 is a complete class type or a class currently being
6122 // defined, the set of member candidates is the result of the
6123 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6124 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006125 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006126 // Complete the type if it can be completed.
6127 RequireCompleteType(OpLoc, T1, 0);
6128 // If the type is neither complete nor being defined, bail out now.
6129 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006130 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006131
John McCalla24dc2e2009-11-17 02:14:36 +00006132 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6133 LookupQualifiedName(Operators, T1Rec->getDecl());
6134 Operators.suppressDiagnostics();
6135
Mike Stump1eb44332009-09-09 15:08:12 +00006136 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006137 OperEnd = Operators.end();
6138 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006139 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006140 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006141 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006142 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006143 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006144 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006145 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006146}
6147
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006148/// AddBuiltinCandidate - Add a candidate for a built-in
6149/// operator. ResultTy and ParamTys are the result and parameter types
6150/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006151/// arguments being passed to the candidate. IsAssignmentOperator
6152/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006153/// operator. NumContextualBoolArguments is the number of arguments
6154/// (at the beginning of the argument list) that will be contextually
6155/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006156void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006157 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006158 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006159 bool IsAssignmentOperator,
6160 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006161 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006162 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006163
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006164 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006165 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006166 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006167 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006168 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006169 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006170 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006171 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006172 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6173
6174 // Determine the implicit conversion sequences for each of the
6175 // arguments.
6176 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006177 Candidate.ExplicitCallArguments = Args.size();
6178 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006179 // C++ [over.match.oper]p4:
6180 // For the built-in assignment operators, conversions of the
6181 // left operand are restricted as follows:
6182 // -- no temporaries are introduced to hold the left operand, and
6183 // -- no user-defined conversions are applied to the left
6184 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006185 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006186 //
6187 // We block these conversions by turning off user-defined
6188 // conversions, since that is the only way that initialization of
6189 // a reference to a non-class type can occur from something that
6190 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006191 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006192 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006193 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006194 Candidate.Conversions[ArgIdx]
6195 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006196 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006197 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006198 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006199 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006200 /*InOverloadResolution=*/false,
6201 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006202 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006203 }
John McCall1d318332010-01-12 00:44:57 +00006204 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006205 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006206 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006207 break;
6208 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006209 }
6210}
6211
Craig Topperfe09f3f2013-07-01 06:29:40 +00006212namespace {
6213
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006214/// BuiltinCandidateTypeSet - A set of types that will be used for the
6215/// candidate operator functions for built-in operators (C++
6216/// [over.built]). The types are separated into pointer types and
6217/// enumeration types.
6218class BuiltinCandidateTypeSet {
6219 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006220 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006221
6222 /// PointerTypes - The set of pointer types that will be used in the
6223 /// built-in candidates.
6224 TypeSet PointerTypes;
6225
Sebastian Redl78eb8742009-04-19 21:53:20 +00006226 /// MemberPointerTypes - The set of member pointer types that will be
6227 /// used in the built-in candidates.
6228 TypeSet MemberPointerTypes;
6229
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006230 /// EnumerationTypes - The set of enumeration types that will be
6231 /// used in the built-in candidates.
6232 TypeSet EnumerationTypes;
6233
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006234 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006235 /// candidates.
6236 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006237
6238 /// \brief A flag indicating non-record types are viable candidates
6239 bool HasNonRecordTypes;
6240
6241 /// \brief A flag indicating whether either arithmetic or enumeration types
6242 /// were present in the candidate set.
6243 bool HasArithmeticOrEnumeralTypes;
6244
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006245 /// \brief A flag indicating whether the nullptr type was present in the
6246 /// candidate set.
6247 bool HasNullPtrType;
6248
Douglas Gregor5842ba92009-08-24 15:23:48 +00006249 /// Sema - The semantic analysis instance where we are building the
6250 /// candidate type set.
6251 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006252
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006253 /// Context - The AST context in which we will build the type sets.
6254 ASTContext &Context;
6255
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006256 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6257 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006258 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006259
6260public:
6261 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006262 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006263
Mike Stump1eb44332009-09-09 15:08:12 +00006264 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006265 : HasNonRecordTypes(false),
6266 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006267 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006268 SemaRef(SemaRef),
6269 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006270
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006271 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006272 SourceLocation Loc,
6273 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006274 bool AllowExplicitConversions,
6275 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006276
6277 /// pointer_begin - First pointer type found;
6278 iterator pointer_begin() { return PointerTypes.begin(); }
6279
Sebastian Redl78eb8742009-04-19 21:53:20 +00006280 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006281 iterator pointer_end() { return PointerTypes.end(); }
6282
Sebastian Redl78eb8742009-04-19 21:53:20 +00006283 /// member_pointer_begin - First member pointer type found;
6284 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6285
6286 /// member_pointer_end - Past the last member pointer type found;
6287 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6288
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006289 /// enumeration_begin - First enumeration type found;
6290 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6291
Sebastian Redl78eb8742009-04-19 21:53:20 +00006292 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006293 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006294
Douglas Gregor26bcf672010-05-19 03:21:00 +00006295 iterator vector_begin() { return VectorTypes.begin(); }
6296 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006297
6298 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6299 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006300 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006301};
6302
Craig Topperfe09f3f2013-07-01 06:29:40 +00006303} // end anonymous namespace
6304
Sebastian Redl78eb8742009-04-19 21:53:20 +00006305/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006306/// the set of pointer types along with any more-qualified variants of
6307/// that type. For example, if @p Ty is "int const *", this routine
6308/// will add "int const *", "int const volatile *", "int const
6309/// restrict *", and "int const volatile restrict *" to the set of
6310/// pointer types. Returns true if the add of @p Ty itself succeeded,
6311/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006312///
6313/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006314bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006315BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6316 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006317
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006318 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006319 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006320 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006321
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006322 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006323 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006324 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006325 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006326 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6327 PointeeTy = PTy->getPointeeType();
6328 buildObjCPtr = true;
6329 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006330 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006331 }
6332
Sebastian Redla9efada2009-11-18 20:39:26 +00006333 // Don't add qualified variants of arrays. For one, they're not allowed
6334 // (the qualifier would sink to the element type), and for another, the
6335 // only overload situation where it matters is subscript or pointer +- int,
6336 // and those shouldn't have qualifier variants anyway.
6337 if (PointeeTy->isArrayType())
6338 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006339
John McCall0953e762009-09-24 19:53:00 +00006340 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006341 bool hasVolatile = VisibleQuals.hasVolatile();
6342 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006343
John McCall0953e762009-09-24 19:53:00 +00006344 // Iterate through all strict supersets of BaseCVR.
6345 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6346 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006347 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006348 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006349
6350 // Skip over restrict if no restrict found anywhere in the types, or if
6351 // the type cannot be restrict-qualified.
6352 if ((CVR & Qualifiers::Restrict) &&
6353 (!hasRestrict ||
6354 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6355 continue;
6356
6357 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006358 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006359
6360 // Build qualified pointer type.
6361 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006362 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006363 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006364 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006365 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6366
6367 // Insert qualified pointer type.
6368 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006369 }
6370
6371 return true;
6372}
6373
Sebastian Redl78eb8742009-04-19 21:53:20 +00006374/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6375/// to the set of pointer types along with any more-qualified variants of
6376/// that type. For example, if @p Ty is "int const *", this routine
6377/// will add "int const *", "int const volatile *", "int const
6378/// restrict *", and "int const volatile restrict *" to the set of
6379/// pointer types. Returns true if the add of @p Ty itself succeeded,
6380/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006381///
6382/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006383bool
6384BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6385 QualType Ty) {
6386 // Insert this type.
6387 if (!MemberPointerTypes.insert(Ty))
6388 return false;
6389
John McCall0953e762009-09-24 19:53:00 +00006390 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6391 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006392
John McCall0953e762009-09-24 19:53:00 +00006393 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006394 // Don't add qualified variants of arrays. For one, they're not allowed
6395 // (the qualifier would sink to the element type), and for another, the
6396 // only overload situation where it matters is subscript or pointer +- int,
6397 // and those shouldn't have qualifier variants anyway.
6398 if (PointeeTy->isArrayType())
6399 return true;
John McCall0953e762009-09-24 19:53:00 +00006400 const Type *ClassTy = PointerTy->getClass();
6401
6402 // Iterate through all strict supersets of the pointee type's CVR
6403 // qualifiers.
6404 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6405 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6406 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006407
John McCall0953e762009-09-24 19:53:00 +00006408 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006409 MemberPointerTypes.insert(
6410 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006411 }
6412
6413 return true;
6414}
6415
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006416/// AddTypesConvertedFrom - Add each of the types to which the type @p
6417/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006418/// primarily interested in pointer types and enumeration types. We also
6419/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006420/// AllowUserConversions is true if we should look at the conversion
6421/// functions of a class type, and AllowExplicitConversions if we
6422/// should also include the explicit conversion functions of a class
6423/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006424void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006425BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006426 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006427 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006428 bool AllowExplicitConversions,
6429 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006430 // Only deal with canonical types.
6431 Ty = Context.getCanonicalType(Ty);
6432
6433 // Look through reference types; they aren't part of the type of an
6434 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006435 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006436 Ty = RefTy->getPointeeType();
6437
John McCall3b657512011-01-19 10:06:00 +00006438 // If we're dealing with an array type, decay to the pointer.
6439 if (Ty->isArrayType())
6440 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6441
6442 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006443 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006444
Chandler Carruth6a577462010-12-13 01:44:01 +00006445 // Flag if we ever add a non-record type.
6446 const RecordType *TyRec = Ty->getAs<RecordType>();
6447 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6448
Chandler Carruth6a577462010-12-13 01:44:01 +00006449 // Flag if we encounter an arithmetic type.
6450 HasArithmeticOrEnumeralTypes =
6451 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6452
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006453 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6454 PointerTypes.insert(Ty);
6455 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006456 // Insert our type, and its more-qualified variants, into the set
6457 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006458 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006459 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006460 } else if (Ty->isMemberPointerType()) {
6461 // Member pointers are far easier, since the pointee can't be converted.
6462 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6463 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006464 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006465 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006466 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006467 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006468 // We treat vector types as arithmetic types in many contexts as an
6469 // extension.
6470 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006471 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006472 } else if (Ty->isNullPtrType()) {
6473 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006474 } else if (AllowUserConversions && TyRec) {
6475 // No conversion functions in incomplete types.
6476 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6477 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006478
Chandler Carruth6a577462010-12-13 01:44:01 +00006479 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006480 std::pair<CXXRecordDecl::conversion_iterator,
6481 CXXRecordDecl::conversion_iterator>
6482 Conversions = ClassDecl->getVisibleConversionFunctions();
6483 for (CXXRecordDecl::conversion_iterator
6484 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006485 NamedDecl *D = I.getDecl();
6486 if (isa<UsingShadowDecl>(D))
6487 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006488
Chandler Carruth6a577462010-12-13 01:44:01 +00006489 // Skip conversion function templates; they don't tell us anything
6490 // about which builtin types we can convert to.
6491 if (isa<FunctionTemplateDecl>(D))
6492 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006493
Chandler Carruth6a577462010-12-13 01:44:01 +00006494 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6495 if (AllowExplicitConversions || !Conv->isExplicit()) {
6496 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6497 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006498 }
6499 }
6500 }
6501}
6502
Douglas Gregor19b7b152009-08-24 13:43:27 +00006503/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6504/// the volatile- and non-volatile-qualified assignment operators for the
6505/// given type to the candidate set.
6506static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6507 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006508 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006509 OverloadCandidateSet &CandidateSet) {
6510 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006511
Douglas Gregor19b7b152009-08-24 13:43:27 +00006512 // T& operator=(T&, T)
6513 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6514 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006515 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006516 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006517
Douglas Gregor19b7b152009-08-24 13:43:27 +00006518 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6519 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006520 ParamTypes[0]
6521 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006522 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006523 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006524 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006525 }
6526}
Mike Stump1eb44332009-09-09 15:08:12 +00006527
Sebastian Redl9994a342009-10-25 17:03:50 +00006528/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6529/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006530static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6531 Qualifiers VRQuals;
6532 const RecordType *TyRec;
6533 if (const MemberPointerType *RHSMPType =
6534 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006535 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006536 else
6537 TyRec = ArgExpr->getType()->getAs<RecordType>();
6538 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006539 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006540 VRQuals.addVolatile();
6541 VRQuals.addRestrict();
6542 return VRQuals;
6543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006544
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006545 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006546 if (!ClassDecl->hasDefinition())
6547 return VRQuals;
6548
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006549 std::pair<CXXRecordDecl::conversion_iterator,
6550 CXXRecordDecl::conversion_iterator>
6551 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006552
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006553 for (CXXRecordDecl::conversion_iterator
6554 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006555 NamedDecl *D = I.getDecl();
6556 if (isa<UsingShadowDecl>(D))
6557 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6558 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006559 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6560 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6561 CanTy = ResTypeRef->getPointeeType();
6562 // Need to go down the pointer/mempointer chain and add qualifiers
6563 // as see them.
6564 bool done = false;
6565 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006566 if (CanTy.isRestrictQualified())
6567 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006568 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6569 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006570 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006571 CanTy->getAs<MemberPointerType>())
6572 CanTy = ResTypeMPtr->getPointeeType();
6573 else
6574 done = true;
6575 if (CanTy.isVolatileQualified())
6576 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006577 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6578 return VRQuals;
6579 }
6580 }
6581 }
6582 return VRQuals;
6583}
John McCall00071ec2010-11-13 05:51:15 +00006584
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006585namespace {
John McCall00071ec2010-11-13 05:51:15 +00006586
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006587/// \brief Helper class to manage the addition of builtin operator overload
6588/// candidates. It provides shared state and utility methods used throughout
6589/// the process, as well as a helper method to add each group of builtin
6590/// operator overloads from the standard to a candidate set.
6591class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006592 // Common instance state available to all overload candidate addition methods.
6593 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006594 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006595 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006596 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006597 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006598 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006599
Chandler Carruth6d695582010-12-12 10:35:00 +00006600 // Define some constants used to index and iterate over the arithemetic types
6601 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006602 // The "promoted arithmetic types" are the arithmetic
6603 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006604 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006605 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006606 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006607 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006608 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006609 LastPromotedArithmeticType = 11;
6610 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006611
Chandler Carruth6d695582010-12-12 10:35:00 +00006612 /// \brief Get the canonical type for a given arithmetic type index.
6613 CanQualType getArithmeticType(unsigned index) {
6614 assert(index < NumArithmeticTypes);
6615 static CanQualType ASTContext::* const
6616 ArithmeticTypes[NumArithmeticTypes] = {
6617 // Start of promoted types.
6618 &ASTContext::FloatTy,
6619 &ASTContext::DoubleTy,
6620 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006621
Chandler Carruth6d695582010-12-12 10:35:00 +00006622 // Start of integral types.
6623 &ASTContext::IntTy,
6624 &ASTContext::LongTy,
6625 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006626 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006627 &ASTContext::UnsignedIntTy,
6628 &ASTContext::UnsignedLongTy,
6629 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006630 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006631 // End of promoted types.
6632
6633 &ASTContext::BoolTy,
6634 &ASTContext::CharTy,
6635 &ASTContext::WCharTy,
6636 &ASTContext::Char16Ty,
6637 &ASTContext::Char32Ty,
6638 &ASTContext::SignedCharTy,
6639 &ASTContext::ShortTy,
6640 &ASTContext::UnsignedCharTy,
6641 &ASTContext::UnsignedShortTy,
6642 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006643 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006644 };
6645 return S.Context.*ArithmeticTypes[index];
6646 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006647
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006648 /// \brief Gets the canonical type resulting from the usual arithemetic
6649 /// converions for the given arithmetic types.
6650 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6651 // Accelerator table for performing the usual arithmetic conversions.
6652 // The rules are basically:
6653 // - if either is floating-point, use the wider floating-point
6654 // - if same signedness, use the higher rank
6655 // - if same size, use unsigned of the higher rank
6656 // - use the larger type
6657 // These rules, together with the axiom that higher ranks are
6658 // never smaller, are sufficient to precompute all of these results
6659 // *except* when dealing with signed types of higher rank.
6660 // (we could precompute SLL x UI for all known platforms, but it's
6661 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006662 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006663 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006664 Dep=-1,
6665 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006666 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006667 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006668 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006669/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6670/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6671/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6672/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6673/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6674/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6675/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6676/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6677/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6678/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6679/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006680 };
6681
6682 assert(L < LastPromotedArithmeticType);
6683 assert(R < LastPromotedArithmeticType);
6684 int Idx = ConversionsTable[L][R];
6685
6686 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006687 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006688
6689 // Slow path: we need to compare widths.
6690 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006691 CanQualType LT = getArithmeticType(L),
6692 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006693 unsigned LW = S.Context.getIntWidth(LT),
6694 RW = S.Context.getIntWidth(RT);
6695
6696 // If they're different widths, use the signed type.
6697 if (LW > RW) return LT;
6698 else if (LW < RW) return RT;
6699
6700 // Otherwise, use the unsigned type of the signed type's rank.
6701 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6702 assert(L == SLL || R == SLL);
6703 return S.Context.UnsignedLongLongTy;
6704 }
6705
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006706 /// \brief Helper method to factor out the common pattern of adding overloads
6707 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006708 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006709 bool HasVolatile,
6710 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006711 QualType ParamTypes[2] = {
6712 S.Context.getLValueReferenceType(CandidateTy),
6713 S.Context.IntTy
6714 };
6715
6716 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006717 if (Args.size() == 1)
6718 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006719 else
Richard Smith958ba642013-05-05 15:51:06 +00006720 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006721
6722 // Use a heuristic to reduce number of builtin candidates in the set:
6723 // add volatile version only if there are conversions to a volatile type.
6724 if (HasVolatile) {
6725 ParamTypes[0] =
6726 S.Context.getLValueReferenceType(
6727 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006728 if (Args.size() == 1)
6729 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006730 else
Richard Smith958ba642013-05-05 15:51:06 +00006731 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006732 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006733
6734 // Add restrict version only if there are conversions to a restrict type
6735 // and our candidate type is a non-restrict-qualified pointer.
6736 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6737 !CandidateTy.isRestrictQualified()) {
6738 ParamTypes[0]
6739 = S.Context.getLValueReferenceType(
6740 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006741 if (Args.size() == 1)
6742 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006743 else
Richard Smith958ba642013-05-05 15:51:06 +00006744 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006745
6746 if (HasVolatile) {
6747 ParamTypes[0]
6748 = S.Context.getLValueReferenceType(
6749 S.Context.getCVRQualifiedType(CandidateTy,
6750 (Qualifiers::Volatile |
6751 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006752 if (Args.size() == 1)
6753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006754 else
Richard Smith958ba642013-05-05 15:51:06 +00006755 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006756 }
6757 }
6758
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006759 }
6760
6761public:
6762 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006763 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006764 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006765 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006766 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006767 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006768 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006769 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006770 HasArithmeticOrEnumeralCandidateType(
6771 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006772 CandidateTypes(CandidateTypes),
6773 CandidateSet(CandidateSet) {
6774 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006775 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006776 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006777 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006778 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006779 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006780 assert(getArithmeticType(FirstPromotedArithmeticType)
6781 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006782 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006783 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006784 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006785 "Invalid last promoted arithmetic type");
6786 }
6787
6788 // C++ [over.built]p3:
6789 //
6790 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6791 // is either volatile or empty, there exist candidate operator
6792 // functions of the form
6793 //
6794 // VQ T& operator++(VQ T&);
6795 // T operator++(VQ T&, int);
6796 //
6797 // C++ [over.built]p4:
6798 //
6799 // For every pair (T, VQ), where T is an arithmetic type other
6800 // than bool, and VQ is either volatile or empty, there exist
6801 // candidate operator functions of the form
6802 //
6803 // VQ T& operator--(VQ T&);
6804 // T operator--(VQ T&, int);
6805 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006806 if (!HasArithmeticOrEnumeralCandidateType)
6807 return;
6808
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006809 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6810 Arith < NumArithmeticTypes; ++Arith) {
6811 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006812 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006813 VisibleTypeConversionsQuals.hasVolatile(),
6814 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006815 }
6816 }
6817
6818 // C++ [over.built]p5:
6819 //
6820 // For every pair (T, VQ), where T is a cv-qualified or
6821 // cv-unqualified object type, and VQ is either volatile or
6822 // empty, there exist candidate operator functions of the form
6823 //
6824 // T*VQ& operator++(T*VQ&);
6825 // T*VQ& operator--(T*VQ&);
6826 // T* operator++(T*VQ&, int);
6827 // T* operator--(T*VQ&, int);
6828 void addPlusPlusMinusMinusPointerOverloads() {
6829 for (BuiltinCandidateTypeSet::iterator
6830 Ptr = CandidateTypes[0].pointer_begin(),
6831 PtrEnd = CandidateTypes[0].pointer_end();
6832 Ptr != PtrEnd; ++Ptr) {
6833 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006834 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006835 continue;
6836
6837 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006838 (!(*Ptr).isVolatileQualified() &&
6839 VisibleTypeConversionsQuals.hasVolatile()),
6840 (!(*Ptr).isRestrictQualified() &&
6841 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006842 }
6843 }
6844
6845 // C++ [over.built]p6:
6846 // For every cv-qualified or cv-unqualified object type T, there
6847 // exist candidate operator functions of the form
6848 //
6849 // T& operator*(T*);
6850 //
6851 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006852 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006853 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006854 // T& operator*(T*);
6855 void addUnaryStarPointerOverloads() {
6856 for (BuiltinCandidateTypeSet::iterator
6857 Ptr = CandidateTypes[0].pointer_begin(),
6858 PtrEnd = CandidateTypes[0].pointer_end();
6859 Ptr != PtrEnd; ++Ptr) {
6860 QualType ParamTy = *Ptr;
6861 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006862 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6863 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006864
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006865 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6866 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6867 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006868
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006869 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006870 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006871 }
6872 }
6873
6874 // C++ [over.built]p9:
6875 // For every promoted arithmetic type T, there exist candidate
6876 // operator functions of the form
6877 //
6878 // T operator+(T);
6879 // T operator-(T);
6880 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006881 if (!HasArithmeticOrEnumeralCandidateType)
6882 return;
6883
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006884 for (unsigned Arith = FirstPromotedArithmeticType;
6885 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006886 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006887 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006888 }
6889
6890 // Extension: We also add these operators for vector types.
6891 for (BuiltinCandidateTypeSet::iterator
6892 Vec = CandidateTypes[0].vector_begin(),
6893 VecEnd = CandidateTypes[0].vector_end();
6894 Vec != VecEnd; ++Vec) {
6895 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006896 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006897 }
6898 }
6899
6900 // C++ [over.built]p8:
6901 // For every type T, there exist candidate operator functions of
6902 // the form
6903 //
6904 // T* operator+(T*);
6905 void addUnaryPlusPointerOverloads() {
6906 for (BuiltinCandidateTypeSet::iterator
6907 Ptr = CandidateTypes[0].pointer_begin(),
6908 PtrEnd = CandidateTypes[0].pointer_end();
6909 Ptr != PtrEnd; ++Ptr) {
6910 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006911 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006912 }
6913 }
6914
6915 // C++ [over.built]p10:
6916 // For every promoted integral type T, there exist candidate
6917 // operator functions of the form
6918 //
6919 // T operator~(T);
6920 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006921 if (!HasArithmeticOrEnumeralCandidateType)
6922 return;
6923
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006924 for (unsigned Int = FirstPromotedIntegralType;
6925 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006926 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006927 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006928 }
6929
6930 // Extension: We also add this operator for vector types.
6931 for (BuiltinCandidateTypeSet::iterator
6932 Vec = CandidateTypes[0].vector_begin(),
6933 VecEnd = CandidateTypes[0].vector_end();
6934 Vec != VecEnd; ++Vec) {
6935 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006936 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006937 }
6938 }
6939
6940 // C++ [over.match.oper]p16:
6941 // For every pointer to member type T, there exist candidate operator
6942 // functions of the form
6943 //
6944 // bool operator==(T,T);
6945 // bool operator!=(T,T);
6946 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6947 /// Set of (canonical) types that we've already handled.
6948 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6949
Richard Smith958ba642013-05-05 15:51:06 +00006950 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006951 for (BuiltinCandidateTypeSet::iterator
6952 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6953 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6954 MemPtr != MemPtrEnd;
6955 ++MemPtr) {
6956 // Don't add the same builtin candidate twice.
6957 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6958 continue;
6959
6960 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006961 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006962 }
6963 }
6964 }
6965
6966 // C++ [over.built]p15:
6967 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006968 // For every T, where T is an enumeration type, a pointer type, or
6969 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006970 //
6971 // bool operator<(T, T);
6972 // bool operator>(T, T);
6973 // bool operator<=(T, T);
6974 // bool operator>=(T, T);
6975 // bool operator==(T, T);
6976 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006977 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006978 // C++ [over.match.oper]p3:
6979 // [...]the built-in candidates include all of the candidate operator
6980 // functions defined in 13.6 that, compared to the given operator, [...]
6981 // do not have the same parameter-type-list as any non-template non-member
6982 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006983 //
Eli Friedman97c67392012-09-18 21:52:24 +00006984 // Note that in practice, this only affects enumeration types because there
6985 // aren't any built-in candidates of record type, and a user-defined operator
6986 // must have an operand of record or enumeration type. Also, the only other
6987 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006988 // cannot be overloaded for enumeration types, so this is the only place
6989 // where we must suppress candidates like this.
6990 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6991 UserDefinedBinaryOperators;
6992
Richard Smith958ba642013-05-05 15:51:06 +00006993 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006994 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6995 CandidateTypes[ArgIdx].enumeration_end()) {
6996 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6997 CEnd = CandidateSet.end();
6998 C != CEnd; ++C) {
6999 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7000 continue;
7001
Eli Friedman97c67392012-09-18 21:52:24 +00007002 if (C->Function->isFunctionTemplateSpecialization())
7003 continue;
7004
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007005 QualType FirstParamType =
7006 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7007 QualType SecondParamType =
7008 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7009
7010 // Skip if either parameter isn't of enumeral type.
7011 if (!FirstParamType->isEnumeralType() ||
7012 !SecondParamType->isEnumeralType())
7013 continue;
7014
7015 // Add this operator to the set of known user-defined operators.
7016 UserDefinedBinaryOperators.insert(
7017 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7018 S.Context.getCanonicalType(SecondParamType)));
7019 }
7020 }
7021 }
7022
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007023 /// Set of (canonical) types that we've already handled.
7024 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7025
Richard Smith958ba642013-05-05 15:51:06 +00007026 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007027 for (BuiltinCandidateTypeSet::iterator
7028 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7029 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7030 Ptr != PtrEnd; ++Ptr) {
7031 // Don't add the same builtin candidate twice.
7032 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7033 continue;
7034
7035 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007036 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007037 }
7038 for (BuiltinCandidateTypeSet::iterator
7039 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7040 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7041 Enum != EnumEnd; ++Enum) {
7042 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7043
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007044 // Don't add the same builtin candidate twice, or if a user defined
7045 // candidate exists.
7046 if (!AddedTypes.insert(CanonType) ||
7047 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7048 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007049 continue;
7050
7051 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007052 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007053 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007054
7055 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7056 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7057 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007058 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007059 NullPtrTy))) {
7060 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007061 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007062 CandidateSet);
7063 }
7064 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007065 }
7066 }
7067
7068 // C++ [over.built]p13:
7069 //
7070 // For every cv-qualified or cv-unqualified object type T
7071 // there exist candidate operator functions of the form
7072 //
7073 // T* operator+(T*, ptrdiff_t);
7074 // T& operator[](T*, ptrdiff_t); [BELOW]
7075 // T* operator-(T*, ptrdiff_t);
7076 // T* operator+(ptrdiff_t, T*);
7077 // T& operator[](ptrdiff_t, T*); [BELOW]
7078 //
7079 // C++ [over.built]p14:
7080 //
7081 // For every T, where T is a pointer to object type, there
7082 // exist candidate operator functions of the form
7083 //
7084 // ptrdiff_t operator-(T, T);
7085 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7086 /// Set of (canonical) types that we've already handled.
7087 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7088
7089 for (int Arg = 0; Arg < 2; ++Arg) {
7090 QualType AsymetricParamTypes[2] = {
7091 S.Context.getPointerDiffType(),
7092 S.Context.getPointerDiffType(),
7093 };
7094 for (BuiltinCandidateTypeSet::iterator
7095 Ptr = CandidateTypes[Arg].pointer_begin(),
7096 PtrEnd = CandidateTypes[Arg].pointer_end();
7097 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007098 QualType PointeeTy = (*Ptr)->getPointeeType();
7099 if (!PointeeTy->isObjectType())
7100 continue;
7101
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007102 AsymetricParamTypes[Arg] = *Ptr;
7103 if (Arg == 0 || Op == OO_Plus) {
7104 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7105 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007106 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007107 }
7108 if (Op == OO_Minus) {
7109 // ptrdiff_t operator-(T, T);
7110 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7111 continue;
7112
7113 QualType ParamTypes[2] = { *Ptr, *Ptr };
7114 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007115 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007116 }
7117 }
7118 }
7119 }
7120
7121 // C++ [over.built]p12:
7122 //
7123 // For every pair of promoted arithmetic types L and R, there
7124 // exist candidate operator functions of the form
7125 //
7126 // LR operator*(L, R);
7127 // LR operator/(L, R);
7128 // LR operator+(L, R);
7129 // LR operator-(L, R);
7130 // bool operator<(L, R);
7131 // bool operator>(L, R);
7132 // bool operator<=(L, R);
7133 // bool operator>=(L, R);
7134 // bool operator==(L, R);
7135 // bool operator!=(L, R);
7136 //
7137 // where LR is the result of the usual arithmetic conversions
7138 // between types L and R.
7139 //
7140 // C++ [over.built]p24:
7141 //
7142 // For every pair of promoted arithmetic types L and R, there exist
7143 // candidate operator functions of the form
7144 //
7145 // LR operator?(bool, L, R);
7146 //
7147 // where LR is the result of the usual arithmetic conversions
7148 // between types L and R.
7149 // Our candidates ignore the first parameter.
7150 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007151 if (!HasArithmeticOrEnumeralCandidateType)
7152 return;
7153
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007154 for (unsigned Left = FirstPromotedArithmeticType;
7155 Left < LastPromotedArithmeticType; ++Left) {
7156 for (unsigned Right = FirstPromotedArithmeticType;
7157 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007158 QualType LandR[2] = { getArithmeticType(Left),
7159 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007160 QualType Result =
7161 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007162 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007163 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007164 }
7165 }
7166
7167 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7168 // conditional operator for vector types.
7169 for (BuiltinCandidateTypeSet::iterator
7170 Vec1 = CandidateTypes[0].vector_begin(),
7171 Vec1End = CandidateTypes[0].vector_end();
7172 Vec1 != Vec1End; ++Vec1) {
7173 for (BuiltinCandidateTypeSet::iterator
7174 Vec2 = CandidateTypes[1].vector_begin(),
7175 Vec2End = CandidateTypes[1].vector_end();
7176 Vec2 != Vec2End; ++Vec2) {
7177 QualType LandR[2] = { *Vec1, *Vec2 };
7178 QualType Result = S.Context.BoolTy;
7179 if (!isComparison) {
7180 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7181 Result = *Vec1;
7182 else
7183 Result = *Vec2;
7184 }
7185
Richard Smith958ba642013-05-05 15:51:06 +00007186 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007187 }
7188 }
7189 }
7190
7191 // C++ [over.built]p17:
7192 //
7193 // For every pair of promoted integral types L and R, there
7194 // exist candidate operator functions of the form
7195 //
7196 // LR operator%(L, R);
7197 // LR operator&(L, R);
7198 // LR operator^(L, R);
7199 // LR operator|(L, R);
7200 // L operator<<(L, R);
7201 // L operator>>(L, R);
7202 //
7203 // where LR is the result of the usual arithmetic conversions
7204 // between types L and R.
7205 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007206 if (!HasArithmeticOrEnumeralCandidateType)
7207 return;
7208
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007209 for (unsigned Left = FirstPromotedIntegralType;
7210 Left < LastPromotedIntegralType; ++Left) {
7211 for (unsigned Right = FirstPromotedIntegralType;
7212 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007213 QualType LandR[2] = { getArithmeticType(Left),
7214 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007215 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7216 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007217 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007218 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007219 }
7220 }
7221 }
7222
7223 // C++ [over.built]p20:
7224 //
7225 // For every pair (T, VQ), where T is an enumeration or
7226 // pointer to member type and VQ is either volatile or
7227 // empty, there exist candidate operator functions of the form
7228 //
7229 // VQ T& operator=(VQ T&, T);
7230 void addAssignmentMemberPointerOrEnumeralOverloads() {
7231 /// Set of (canonical) types that we've already handled.
7232 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7233
7234 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7235 for (BuiltinCandidateTypeSet::iterator
7236 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7237 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7238 Enum != EnumEnd; ++Enum) {
7239 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7240 continue;
7241
Richard Smith958ba642013-05-05 15:51:06 +00007242 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007243 }
7244
7245 for (BuiltinCandidateTypeSet::iterator
7246 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7247 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7248 MemPtr != MemPtrEnd; ++MemPtr) {
7249 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7250 continue;
7251
Richard Smith958ba642013-05-05 15:51:06 +00007252 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007253 }
7254 }
7255 }
7256
7257 // C++ [over.built]p19:
7258 //
7259 // For every pair (T, VQ), where T is any type and VQ is either
7260 // volatile or empty, there exist candidate operator functions
7261 // of the form
7262 //
7263 // T*VQ& operator=(T*VQ&, T*);
7264 //
7265 // C++ [over.built]p21:
7266 //
7267 // For every pair (T, VQ), where T is a cv-qualified or
7268 // cv-unqualified object type and VQ is either volatile or
7269 // empty, there exist candidate operator functions of the form
7270 //
7271 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7272 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7273 void addAssignmentPointerOverloads(bool isEqualOp) {
7274 /// Set of (canonical) types that we've already handled.
7275 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7276
7277 for (BuiltinCandidateTypeSet::iterator
7278 Ptr = CandidateTypes[0].pointer_begin(),
7279 PtrEnd = CandidateTypes[0].pointer_end();
7280 Ptr != PtrEnd; ++Ptr) {
7281 // If this is operator=, keep track of the builtin candidates we added.
7282 if (isEqualOp)
7283 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007284 else if (!(*Ptr)->getPointeeType()->isObjectType())
7285 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007286
7287 // non-volatile version
7288 QualType ParamTypes[2] = {
7289 S.Context.getLValueReferenceType(*Ptr),
7290 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7291 };
Richard Smith958ba642013-05-05 15:51:06 +00007292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007293 /*IsAssigmentOperator=*/ isEqualOp);
7294
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007295 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7296 VisibleTypeConversionsQuals.hasVolatile();
7297 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007298 // volatile version
7299 ParamTypes[0] =
7300 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007301 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007302 /*IsAssigmentOperator=*/isEqualOp);
7303 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007304
7305 if (!(*Ptr).isRestrictQualified() &&
7306 VisibleTypeConversionsQuals.hasRestrict()) {
7307 // restrict version
7308 ParamTypes[0]
7309 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007310 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007311 /*IsAssigmentOperator=*/isEqualOp);
7312
7313 if (NeedVolatile) {
7314 // volatile restrict version
7315 ParamTypes[0]
7316 = S.Context.getLValueReferenceType(
7317 S.Context.getCVRQualifiedType(*Ptr,
7318 (Qualifiers::Volatile |
7319 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007320 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007321 /*IsAssigmentOperator=*/isEqualOp);
7322 }
7323 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007324 }
7325
7326 if (isEqualOp) {
7327 for (BuiltinCandidateTypeSet::iterator
7328 Ptr = CandidateTypes[1].pointer_begin(),
7329 PtrEnd = CandidateTypes[1].pointer_end();
7330 Ptr != PtrEnd; ++Ptr) {
7331 // Make sure we don't add the same candidate twice.
7332 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7333 continue;
7334
Chandler Carruth6df868e2010-12-12 08:17:55 +00007335 QualType ParamTypes[2] = {
7336 S.Context.getLValueReferenceType(*Ptr),
7337 *Ptr,
7338 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007339
7340 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007342 /*IsAssigmentOperator=*/true);
7343
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007344 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7345 VisibleTypeConversionsQuals.hasVolatile();
7346 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007347 // volatile version
7348 ParamTypes[0] =
7349 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007350 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7351 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007352 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007353
7354 if (!(*Ptr).isRestrictQualified() &&
7355 VisibleTypeConversionsQuals.hasRestrict()) {
7356 // restrict version
7357 ParamTypes[0]
7358 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007359 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7360 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007361
7362 if (NeedVolatile) {
7363 // volatile restrict version
7364 ParamTypes[0]
7365 = S.Context.getLValueReferenceType(
7366 S.Context.getCVRQualifiedType(*Ptr,
7367 (Qualifiers::Volatile |
7368 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007369 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7370 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007371 }
7372 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007373 }
7374 }
7375 }
7376
7377 // C++ [over.built]p18:
7378 //
7379 // For every triple (L, VQ, R), where L is an arithmetic type,
7380 // VQ is either volatile or empty, and R is a promoted
7381 // arithmetic type, there exist candidate operator functions of
7382 // the form
7383 //
7384 // VQ L& operator=(VQ L&, R);
7385 // VQ L& operator*=(VQ L&, R);
7386 // VQ L& operator/=(VQ L&, R);
7387 // VQ L& operator+=(VQ L&, R);
7388 // VQ L& operator-=(VQ L&, R);
7389 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007390 if (!HasArithmeticOrEnumeralCandidateType)
7391 return;
7392
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007393 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7394 for (unsigned Right = FirstPromotedArithmeticType;
7395 Right < LastPromotedArithmeticType; ++Right) {
7396 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007397 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007398
7399 // Add this built-in operator as a candidate (VQ is empty).
7400 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007401 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007402 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007403 /*IsAssigmentOperator=*/isEqualOp);
7404
7405 // Add this built-in operator as a candidate (VQ is 'volatile').
7406 if (VisibleTypeConversionsQuals.hasVolatile()) {
7407 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007408 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007409 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007410 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007411 /*IsAssigmentOperator=*/isEqualOp);
7412 }
7413 }
7414 }
7415
7416 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7417 for (BuiltinCandidateTypeSet::iterator
7418 Vec1 = CandidateTypes[0].vector_begin(),
7419 Vec1End = CandidateTypes[0].vector_end();
7420 Vec1 != Vec1End; ++Vec1) {
7421 for (BuiltinCandidateTypeSet::iterator
7422 Vec2 = CandidateTypes[1].vector_begin(),
7423 Vec2End = CandidateTypes[1].vector_end();
7424 Vec2 != Vec2End; ++Vec2) {
7425 QualType ParamTypes[2];
7426 ParamTypes[1] = *Vec2;
7427 // Add this built-in operator as a candidate (VQ is empty).
7428 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007429 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007430 /*IsAssigmentOperator=*/isEqualOp);
7431
7432 // Add this built-in operator as a candidate (VQ is 'volatile').
7433 if (VisibleTypeConversionsQuals.hasVolatile()) {
7434 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7435 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007436 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007437 /*IsAssigmentOperator=*/isEqualOp);
7438 }
7439 }
7440 }
7441 }
7442
7443 // C++ [over.built]p22:
7444 //
7445 // For every triple (L, VQ, R), where L is an integral type, VQ
7446 // is either volatile or empty, and R is a promoted integral
7447 // type, there exist candidate operator functions of the form
7448 //
7449 // VQ L& operator%=(VQ L&, R);
7450 // VQ L& operator<<=(VQ L&, R);
7451 // VQ L& operator>>=(VQ L&, R);
7452 // VQ L& operator&=(VQ L&, R);
7453 // VQ L& operator^=(VQ L&, R);
7454 // VQ L& operator|=(VQ L&, R);
7455 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007456 if (!HasArithmeticOrEnumeralCandidateType)
7457 return;
7458
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007459 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7460 for (unsigned Right = FirstPromotedIntegralType;
7461 Right < LastPromotedIntegralType; ++Right) {
7462 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007463 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007464
7465 // Add this built-in operator as a candidate (VQ is empty).
7466 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007467 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007468 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007469 if (VisibleTypeConversionsQuals.hasVolatile()) {
7470 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007471 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007472 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7473 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007474 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007475 }
7476 }
7477 }
7478 }
7479
7480 // C++ [over.operator]p23:
7481 //
7482 // There also exist candidate operator functions of the form
7483 //
7484 // bool operator!(bool);
7485 // bool operator&&(bool, bool);
7486 // bool operator||(bool, bool);
7487 void addExclaimOverload() {
7488 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007489 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007490 /*IsAssignmentOperator=*/false,
7491 /*NumContextualBoolArguments=*/1);
7492 }
7493 void addAmpAmpOrPipePipeOverload() {
7494 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007495 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007496 /*IsAssignmentOperator=*/false,
7497 /*NumContextualBoolArguments=*/2);
7498 }
7499
7500 // C++ [over.built]p13:
7501 //
7502 // For every cv-qualified or cv-unqualified object type T there
7503 // exist candidate operator functions of the form
7504 //
7505 // T* operator+(T*, ptrdiff_t); [ABOVE]
7506 // T& operator[](T*, ptrdiff_t);
7507 // T* operator-(T*, ptrdiff_t); [ABOVE]
7508 // T* operator+(ptrdiff_t, T*); [ABOVE]
7509 // T& operator[](ptrdiff_t, T*);
7510 void addSubscriptOverloads() {
7511 for (BuiltinCandidateTypeSet::iterator
7512 Ptr = CandidateTypes[0].pointer_begin(),
7513 PtrEnd = CandidateTypes[0].pointer_end();
7514 Ptr != PtrEnd; ++Ptr) {
7515 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7516 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007517 if (!PointeeType->isObjectType())
7518 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007519
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007520 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7521
7522 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007523 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007524 }
7525
7526 for (BuiltinCandidateTypeSet::iterator
7527 Ptr = CandidateTypes[1].pointer_begin(),
7528 PtrEnd = CandidateTypes[1].pointer_end();
7529 Ptr != PtrEnd; ++Ptr) {
7530 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7531 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007532 if (!PointeeType->isObjectType())
7533 continue;
7534
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007535 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7536
7537 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007538 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007539 }
7540 }
7541
7542 // C++ [over.built]p11:
7543 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7544 // C1 is the same type as C2 or is a derived class of C2, T is an object
7545 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7546 // there exist candidate operator functions of the form
7547 //
7548 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7549 //
7550 // where CV12 is the union of CV1 and CV2.
7551 void addArrowStarOverloads() {
7552 for (BuiltinCandidateTypeSet::iterator
7553 Ptr = CandidateTypes[0].pointer_begin(),
7554 PtrEnd = CandidateTypes[0].pointer_end();
7555 Ptr != PtrEnd; ++Ptr) {
7556 QualType C1Ty = (*Ptr);
7557 QualType C1;
7558 QualifierCollector Q1;
7559 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7560 if (!isa<RecordType>(C1))
7561 continue;
7562 // heuristic to reduce number of builtin candidates in the set.
7563 // Add volatile/restrict version only if there are conversions to a
7564 // volatile/restrict type.
7565 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7566 continue;
7567 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7568 continue;
7569 for (BuiltinCandidateTypeSet::iterator
7570 MemPtr = CandidateTypes[1].member_pointer_begin(),
7571 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7572 MemPtr != MemPtrEnd; ++MemPtr) {
7573 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7574 QualType C2 = QualType(mptr->getClass(), 0);
7575 C2 = C2.getUnqualifiedType();
7576 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7577 break;
7578 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7579 // build CV12 T&
7580 QualType T = mptr->getPointeeType();
7581 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7582 T.isVolatileQualified())
7583 continue;
7584 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7585 T.isRestrictQualified())
7586 continue;
7587 T = Q1.apply(S.Context, T);
7588 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007589 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007590 }
7591 }
7592 }
7593
7594 // Note that we don't consider the first argument, since it has been
7595 // contextually converted to bool long ago. The candidates below are
7596 // therefore added as binary.
7597 //
7598 // C++ [over.built]p25:
7599 // For every type T, where T is a pointer, pointer-to-member, or scoped
7600 // enumeration type, there exist candidate operator functions of the form
7601 //
7602 // T operator?(bool, T, T);
7603 //
7604 void addConditionalOperatorOverloads() {
7605 /// Set of (canonical) types that we've already handled.
7606 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7607
7608 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7609 for (BuiltinCandidateTypeSet::iterator
7610 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7611 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7612 Ptr != PtrEnd; ++Ptr) {
7613 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7614 continue;
7615
7616 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007617 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007618 }
7619
7620 for (BuiltinCandidateTypeSet::iterator
7621 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7622 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7623 MemPtr != MemPtrEnd; ++MemPtr) {
7624 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7625 continue;
7626
7627 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007628 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007629 }
7630
Richard Smith80ad52f2013-01-02 11:42:31 +00007631 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007632 for (BuiltinCandidateTypeSet::iterator
7633 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7634 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7635 Enum != EnumEnd; ++Enum) {
7636 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7637 continue;
7638
7639 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7640 continue;
7641
7642 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007643 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007644 }
7645 }
7646 }
7647 }
7648};
7649
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007650} // end anonymous namespace
7651
7652/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7653/// operator overloads to the candidate set (C++ [over.built]), based
7654/// on the operator @p Op and the arguments given. For example, if the
7655/// operator is a binary '+', this routine might add "int
7656/// operator+(int, int)" to cover integer addition.
Robert Wilhelm834c0582013-08-09 18:02:13 +00007657void Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7658 SourceLocation OpLoc,
7659 ArrayRef<Expr *> Args,
7660 OverloadCandidateSet &CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007661 // Find all of the types that the arguments can convert to, but only
7662 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007663 // that make use of these types. Also record whether we encounter non-record
7664 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007665 Qualifiers VisibleTypeConversionsQuals;
7666 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007667 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007668 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007669
7670 bool HasNonRecordCandidateType = false;
7671 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007672 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007673 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007674 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7675 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7676 OpLoc,
7677 true,
7678 (Op == OO_Exclaim ||
7679 Op == OO_AmpAmp ||
7680 Op == OO_PipePipe),
7681 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007682 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7683 CandidateTypes[ArgIdx].hasNonRecordTypes();
7684 HasArithmeticOrEnumeralCandidateType =
7685 HasArithmeticOrEnumeralCandidateType ||
7686 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007687 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007688
Chandler Carruth6a577462010-12-13 01:44:01 +00007689 // Exit early when no non-record types have been added to the candidate set
7690 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007691 //
7692 // We can't exit early for !, ||, or &&, since there we have always have
7693 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007694 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007695 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007696 return;
7697
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007698 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007699 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007700 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007701 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007702 CandidateTypes, CandidateSet);
7703
7704 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007705 switch (Op) {
7706 case OO_None:
7707 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007708 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007709
Chandler Carruthabb71842010-12-12 08:51:33 +00007710 case OO_New:
7711 case OO_Delete:
7712 case OO_Array_New:
7713 case OO_Array_Delete:
7714 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007715 llvm_unreachable(
7716 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007717
7718 case OO_Comma:
7719 case OO_Arrow:
7720 // C++ [over.match.oper]p3:
7721 // -- For the operator ',', the unary operator '&', or the
7722 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007723 break;
7724
7725 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007726 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007727 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007728 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007729
7730 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007731 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007732 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007733 } else {
7734 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7735 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7736 }
Douglas Gregor74253732008-11-19 15:42:04 +00007737 break;
7738
Chandler Carruthabb71842010-12-12 08:51:33 +00007739 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007740 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007741 OpBuilder.addUnaryStarPointerOverloads();
7742 else
7743 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7744 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007745
Chandler Carruthabb71842010-12-12 08:51:33 +00007746 case OO_Slash:
7747 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007748 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007749
7750 case OO_PlusPlus:
7751 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007752 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7753 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007754 break;
7755
Douglas Gregor19b7b152009-08-24 13:43:27 +00007756 case OO_EqualEqual:
7757 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007758 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007759 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007760
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007761 case OO_Less:
7762 case OO_Greater:
7763 case OO_LessEqual:
7764 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007765 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007766 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7767 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007768
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007769 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007770 case OO_Caret:
7771 case OO_Pipe:
7772 case OO_LessLess:
7773 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007774 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007775 break;
7776
Chandler Carruthabb71842010-12-12 08:51:33 +00007777 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007778 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007779 // C++ [over.match.oper]p3:
7780 // -- For the operator ',', the unary operator '&', or the
7781 // operator '->', the built-in candidates set is empty.
7782 break;
7783
7784 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7785 break;
7786
7787 case OO_Tilde:
7788 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7789 break;
7790
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007791 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007792 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007793 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007794
7795 case OO_PlusEqual:
7796 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007797 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007798 // Fall through.
7799
7800 case OO_StarEqual:
7801 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007802 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007803 break;
7804
7805 case OO_PercentEqual:
7806 case OO_LessLessEqual:
7807 case OO_GreaterGreaterEqual:
7808 case OO_AmpEqual:
7809 case OO_CaretEqual:
7810 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007811 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007812 break;
7813
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007814 case OO_Exclaim:
7815 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007816 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007817
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007818 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007819 case OO_PipePipe:
7820 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007821 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007822
7823 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007824 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007825 break;
7826
7827 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007828 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007829 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007830
7831 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007832 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007833 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7834 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007835 }
7836}
7837
Douglas Gregorfa047642009-02-04 00:32:51 +00007838/// \brief Add function candidates found via argument-dependent lookup
7839/// to the set of overloading candidates.
7840///
7841/// This routine performs argument-dependent name lookup based on the
7842/// given function name (which may also be an operator name) and adds
7843/// all of the overload candidates found by ADL to the overload
7844/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007845void
Douglas Gregorfa047642009-02-04 00:32:51 +00007846Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007847 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007848 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007849 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007850 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007851 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007852 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007853
John McCalla113e722010-01-26 06:04:06 +00007854 // FIXME: This approach for uniquing ADL results (and removing
7855 // redundant candidates from the set) relies on pointer-equality,
7856 // which means we need to key off the canonical decl. However,
7857 // always going back to the canonical decl might not get us the
7858 // right set of default arguments. What default arguments are
7859 // we supposed to consider on ADL candidates, anyway?
7860
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007861 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007862 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007863
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007864 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007865 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7866 CandEnd = CandidateSet.end();
7867 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007868 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007869 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007870 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007871 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007872 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007873
7874 // For each of the ADL candidates we found, add it to the overload
7875 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007876 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007877 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007878 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007879 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007880 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007881
Ahmed Charles13a140c2012-02-25 11:00:22 +00007882 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7883 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007884 } else
John McCall6e266892010-01-26 03:27:55 +00007885 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007886 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007887 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007888 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007889}
7890
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007891/// isBetterOverloadCandidate - Determines whether the first overload
7892/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007893bool
John McCall120d63c2010-08-24 20:38:10 +00007894isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007895 const OverloadCandidate &Cand1,
7896 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007897 SourceLocation Loc,
7898 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007899 // Define viable functions to be better candidates than non-viable
7900 // functions.
7901 if (!Cand2.Viable)
7902 return Cand1.Viable;
7903 else if (!Cand1.Viable)
7904 return false;
7905
Douglas Gregor88a35142008-12-22 05:46:06 +00007906 // C++ [over.match.best]p1:
7907 //
7908 // -- if F is a static member function, ICS1(F) is defined such
7909 // that ICS1(F) is neither better nor worse than ICS1(G) for
7910 // any function G, and, symmetrically, ICS1(G) is neither
7911 // better nor worse than ICS1(F).
7912 unsigned StartArg = 0;
7913 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7914 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007915
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007916 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007917 // A viable function F1 is defined to be a better function than another
7918 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007919 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007920 unsigned NumArgs = Cand1.NumConversions;
7921 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007922 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007923 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007924 switch (CompareImplicitConversionSequences(S,
7925 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007926 Cand2.Conversions[ArgIdx])) {
7927 case ImplicitConversionSequence::Better:
7928 // Cand1 has a better conversion sequence.
7929 HasBetterConversion = true;
7930 break;
7931
7932 case ImplicitConversionSequence::Worse:
7933 // Cand1 can't be better than Cand2.
7934 return false;
7935
7936 case ImplicitConversionSequence::Indistinguishable:
7937 // Do nothing.
7938 break;
7939 }
7940 }
7941
Mike Stump1eb44332009-09-09 15:08:12 +00007942 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007943 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007944 if (HasBetterConversion)
7945 return true;
7946
Mike Stump1eb44332009-09-09 15:08:12 +00007947 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007948 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007949 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007950 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7951 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007952
7953 // -- F1 and F2 are function template specializations, and the function
7954 // template for F1 is more specialized than the template for F2
7955 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007956 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007957 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007958 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007959 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007960 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7961 Cand2.Function->getPrimaryTemplate(),
7962 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007963 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007964 : TPOC_Call,
Richard Smith66118c22013-09-11 00:52:39 +00007965 Cand1.ExplicitCallArguments,
7966 Cand2.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007967 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007968 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007969
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007970 // -- the context is an initialization by user-defined conversion
7971 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7972 // from the return type of F1 to the destination type (i.e.,
7973 // the type of the entity being initialized) is a better
7974 // conversion sequence than the standard conversion sequence
7975 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007976 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007977 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007978 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007979 // First check whether we prefer one of the conversion functions over the
7980 // other. This only distinguishes the results in non-standard, extension
7981 // cases such as the conversion from a lambda closure type to a function
7982 // pointer or block.
7983 ImplicitConversionSequence::CompareKind FuncResult
7984 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7985 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7986 return FuncResult;
7987
John McCall120d63c2010-08-24 20:38:10 +00007988 switch (CompareStandardConversionSequences(S,
7989 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007990 Cand2.FinalConversion)) {
7991 case ImplicitConversionSequence::Better:
7992 // Cand1 has a better conversion sequence.
7993 return true;
7994
7995 case ImplicitConversionSequence::Worse:
7996 // Cand1 can't be better than Cand2.
7997 return false;
7998
7999 case ImplicitConversionSequence::Indistinguishable:
8000 // Do nothing
8001 break;
8002 }
8003 }
8004
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008005 return false;
8006}
8007
Mike Stump1eb44332009-09-09 15:08:12 +00008008/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008009/// within an overload candidate set.
8010///
James Dennettefce31f2012-06-22 08:10:18 +00008011/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008012/// which overload resolution occurs.
8013///
James Dennettefce31f2012-06-22 08:10:18 +00008014/// \param Best If overload resolution was successful or found a deleted
8015/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008016///
8017/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008018OverloadingResult
8019OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008020 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008021 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008022 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008023 Best = end();
8024 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8025 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008026 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008027 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008028 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008029 }
8030
8031 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008032 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008033 return OR_No_Viable_Function;
8034
8035 // Make sure that this function is better than every other viable
8036 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008037 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008038 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008039 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008040 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008041 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008042 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008043 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008044 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008045 }
Mike Stump1eb44332009-09-09 15:08:12 +00008046
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008047 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008048 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008049 (Best->Function->isDeleted() ||
8050 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008051 return OR_Deleted;
8052
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008053 return OR_Success;
8054}
8055
John McCall3c80f572010-01-12 02:15:36 +00008056namespace {
8057
8058enum OverloadCandidateKind {
8059 oc_function,
8060 oc_method,
8061 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008062 oc_function_template,
8063 oc_method_template,
8064 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008065 oc_implicit_default_constructor,
8066 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008067 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008068 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008069 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008070 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008071};
8072
John McCall220ccbf2010-01-13 00:25:19 +00008073OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8074 FunctionDecl *Fn,
8075 std::string &Description) {
8076 bool isTemplate = false;
8077
8078 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8079 isTemplate = true;
8080 Description = S.getTemplateArgumentBindingsText(
8081 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8082 }
John McCallb1622a12010-01-06 09:43:14 +00008083
8084 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008085 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008086 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008087
Sebastian Redlf677ea32011-02-05 19:23:19 +00008088 if (Ctor->getInheritedConstructor())
8089 return oc_implicit_inherited_constructor;
8090
Sean Hunt82713172011-05-25 23:16:36 +00008091 if (Ctor->isDefaultConstructor())
8092 return oc_implicit_default_constructor;
8093
8094 if (Ctor->isMoveConstructor())
8095 return oc_implicit_move_constructor;
8096
8097 assert(Ctor->isCopyConstructor() &&
8098 "unexpected sort of implicit constructor");
8099 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008100 }
8101
8102 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8103 // This actually gets spelled 'candidate function' for now, but
8104 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008105 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008106 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008107
Sean Hunt82713172011-05-25 23:16:36 +00008108 if (Meth->isMoveAssignmentOperator())
8109 return oc_implicit_move_assignment;
8110
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008111 if (Meth->isCopyAssignmentOperator())
8112 return oc_implicit_copy_assignment;
8113
8114 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8115 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008116 }
8117
John McCall220ccbf2010-01-13 00:25:19 +00008118 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008119}
8120
Larisse Voufo43847122013-07-19 23:00:19 +00008121void MaybeEmitInheritedConstructorNote(Sema &S, Decl *Fn) {
Sebastian Redlf677ea32011-02-05 19:23:19 +00008122 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8123 if (!Ctor) return;
8124
8125 Ctor = Ctor->getInheritedConstructor();
8126 if (!Ctor) return;
8127
8128 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8129}
8130
John McCall3c80f572010-01-12 02:15:36 +00008131} // end anonymous namespace
8132
8133// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008134void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008135 std::string FnDesc;
8136 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008137 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8138 << (unsigned) K << FnDesc;
8139 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8140 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008141 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008142}
8143
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008144//Notes the location of all overload candidates designated through
8145// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008146void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008147 assert(OverloadedExpr->getType() == Context.OverloadTy);
8148
8149 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8150 OverloadExpr *OvlExpr = Ovl.Expression;
8151
8152 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8153 IEnd = OvlExpr->decls_end();
8154 I != IEnd; ++I) {
8155 if (FunctionTemplateDecl *FunTmpl =
8156 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008157 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008158 } else if (FunctionDecl *Fun
8159 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008160 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008161 }
8162 }
8163}
8164
John McCall1d318332010-01-12 00:44:57 +00008165/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8166/// "lead" diagnostic; it will be given two arguments, the source and
8167/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008168void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8169 Sema &S,
8170 SourceLocation CaretLoc,
8171 const PartialDiagnostic &PDiag) const {
8172 S.Diag(CaretLoc, PDiag)
8173 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008174 // FIXME: The note limiting machinery is borrowed from
8175 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8176 // refactoring here.
8177 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8178 unsigned CandsShown = 0;
8179 AmbiguousConversionSequence::const_iterator I, E;
8180 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8181 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8182 break;
8183 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008184 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008185 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008186 if (I != E)
8187 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008188}
8189
John McCall1d318332010-01-12 00:44:57 +00008190namespace {
8191
John McCalladbb8f82010-01-13 09:16:55 +00008192void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8193 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8194 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008195 assert(Cand->Function && "for now, candidate must be a function");
8196 FunctionDecl *Fn = Cand->Function;
8197
8198 // There's a conversion slot for the object argument if this is a
8199 // non-constructor method. Note that 'I' corresponds the
8200 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008201 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008202 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008203 if (I == 0)
8204 isObjectArgument = true;
8205 else
8206 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008207 }
8208
John McCall220ccbf2010-01-13 00:25:19 +00008209 std::string FnDesc;
8210 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8211
John McCalladbb8f82010-01-13 09:16:55 +00008212 Expr *FromExpr = Conv.Bad.FromExpr;
8213 QualType FromTy = Conv.Bad.getFromType();
8214 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008215
John McCall5920dbb2010-02-02 02:42:52 +00008216 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008217 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008218 Expr *E = FromExpr->IgnoreParens();
8219 if (isa<UnaryOperator>(E))
8220 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008221 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008222
8223 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8224 << (unsigned) FnKind << FnDesc
8225 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8226 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008227 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008228 return;
8229 }
8230
John McCall258b2032010-01-23 08:10:49 +00008231 // Do some hand-waving analysis to see if the non-viability is due
8232 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008233 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8234 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8235 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8236 CToTy = RT->getPointeeType();
8237 else {
8238 // TODO: detect and diagnose the full richness of const mismatches.
8239 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8240 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8241 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8242 }
8243
8244 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8245 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008246 Qualifiers FromQs = CFromTy.getQualifiers();
8247 Qualifiers ToQs = CToTy.getQualifiers();
8248
8249 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8251 << (unsigned) FnKind << FnDesc
8252 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8253 << FromTy
8254 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8255 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008256 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008257 return;
8258 }
8259
John McCallf85e1932011-06-15 23:02:42 +00008260 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008261 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008262 << (unsigned) FnKind << FnDesc
8263 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8264 << FromTy
8265 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8266 << (unsigned) isObjectArgument << I+1;
8267 MaybeEmitInheritedConstructorNote(S, Fn);
8268 return;
8269 }
8270
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008271 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8273 << (unsigned) FnKind << FnDesc
8274 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8275 << FromTy
8276 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8277 << (unsigned) isObjectArgument << I+1;
8278 MaybeEmitInheritedConstructorNote(S, Fn);
8279 return;
8280 }
8281
John McCall651f3ee2010-01-14 03:28:57 +00008282 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8283 assert(CVR && "unexpected qualifiers mismatch");
8284
8285 if (isObjectArgument) {
8286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8287 << (unsigned) FnKind << FnDesc
8288 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8289 << FromTy << (CVR - 1);
8290 } else {
8291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8292 << (unsigned) FnKind << FnDesc
8293 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8294 << FromTy << (CVR - 1) << I+1;
8295 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008296 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008297 return;
8298 }
8299
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008300 // Special diagnostic for failure to convert an initializer list, since
8301 // telling the user that it has type void is not useful.
8302 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8304 << (unsigned) FnKind << FnDesc
8305 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8306 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8307 MaybeEmitInheritedConstructorNote(S, Fn);
8308 return;
8309 }
8310
John McCall258b2032010-01-23 08:10:49 +00008311 // Diagnose references or pointers to incomplete types differently,
8312 // since it's far from impossible that the incompleteness triggered
8313 // the failure.
8314 QualType TempFromTy = FromTy.getNonReferenceType();
8315 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8316 TempFromTy = PTy->getPointeeType();
8317 if (TempFromTy->isIncompleteType()) {
8318 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8319 << (unsigned) FnKind << FnDesc
8320 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8321 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008322 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008323 return;
8324 }
8325
Douglas Gregor85789812010-06-30 23:01:39 +00008326 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008327 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008328 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8329 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8330 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8331 FromPtrTy->getPointeeType()) &&
8332 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8333 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008334 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008335 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008336 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008337 }
8338 } else if (const ObjCObjectPointerType *FromPtrTy
8339 = FromTy->getAs<ObjCObjectPointerType>()) {
8340 if (const ObjCObjectPointerType *ToPtrTy
8341 = ToTy->getAs<ObjCObjectPointerType>())
8342 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8343 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8344 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8345 FromPtrTy->getPointeeType()) &&
8346 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008347 BaseToDerivedConversion = 2;
8348 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008349 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8350 !FromTy->isIncompleteType() &&
8351 !ToRefTy->getPointeeType()->isIncompleteType() &&
8352 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8353 BaseToDerivedConversion = 3;
8354 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8355 ToTy.getNonReferenceType().getCanonicalType() ==
8356 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8358 << (unsigned) FnKind << FnDesc
8359 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8360 << (unsigned) isObjectArgument << I + 1;
8361 MaybeEmitInheritedConstructorNote(S, Fn);
8362 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008363 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008365
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008366 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008367 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008368 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008369 << (unsigned) FnKind << FnDesc
8370 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008371 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008372 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008373 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008374 return;
8375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008376
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008377 if (isa<ObjCObjectPointerType>(CFromTy) &&
8378 isa<PointerType>(CToTy)) {
8379 Qualifiers FromQs = CFromTy.getQualifiers();
8380 Qualifiers ToQs = CToTy.getQualifiers();
8381 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8383 << (unsigned) FnKind << FnDesc
8384 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8385 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8386 MaybeEmitInheritedConstructorNote(S, Fn);
8387 return;
8388 }
8389 }
8390
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008391 // Emit the generic diagnostic and, optionally, add the hints to it.
8392 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8393 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008394 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008395 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8396 << (unsigned) (Cand->Fix.Kind);
8397
8398 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008399 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8400 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008401 FDiag << *HI;
8402 S.Diag(Fn->getLocation(), FDiag);
8403
Sebastian Redlf677ea32011-02-05 19:23:19 +00008404 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008405}
8406
Larisse Voufo43847122013-07-19 23:00:19 +00008407/// Additional arity mismatch diagnosis specific to a function overload
8408/// candidates. This is not covered by the more general DiagnoseArityMismatch()
8409/// over a candidate in any candidate set.
8410bool CheckArityMismatch(Sema &S, OverloadCandidate *Cand,
8411 unsigned NumArgs) {
John McCalladbb8f82010-01-13 09:16:55 +00008412 FunctionDecl *Fn = Cand->Function;
John McCalladbb8f82010-01-13 09:16:55 +00008413 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008414
Douglas Gregor439d3c32011-05-05 00:13:13 +00008415 // With invalid overloaded operators, it's possible that we think we
Larisse Voufo43847122013-07-19 23:00:19 +00008416 // have an arity mismatch when in fact it looks like we have the
Douglas Gregor439d3c32011-05-05 00:13:13 +00008417 // right number of arguments, because only overloaded operators have
8418 // the weird behavior of overloading member and non-member functions.
8419 // Just don't report anything.
8420 if (Fn->isInvalidDecl() &&
8421 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
Larisse Voufo43847122013-07-19 23:00:19 +00008422 return true;
8423
8424 if (NumArgs < MinParams) {
8425 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8426 (Cand->FailureKind == ovl_fail_bad_deduction &&
8427 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
8428 } else {
8429 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8430 (Cand->FailureKind == ovl_fail_bad_deduction &&
8431 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
8432 }
8433
8434 return false;
8435}
8436
8437/// General arity mismatch diagnosis over a candidate in a candidate set.
8438void DiagnoseArityMismatch(Sema &S, Decl *D, unsigned NumFormalArgs) {
8439 assert(isa<FunctionDecl>(D) &&
8440 "The templated declaration should at least be a function"
8441 " when diagnosing bad template argument deduction due to too many"
8442 " or too few arguments");
8443
8444 FunctionDecl *Fn = cast<FunctionDecl>(D);
8445
8446 // TODO: treat calls to a missing default constructor as a special case
8447 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8448 unsigned MinParams = Fn->getMinRequiredArguments();
Douglas Gregor439d3c32011-05-05 00:13:13 +00008449
John McCalladbb8f82010-01-13 09:16:55 +00008450 // at least / at most / exactly
8451 unsigned mode, modeCount;
8452 if (NumFormalArgs < MinParams) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008453 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008454 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008455 mode = 0; // "at least"
8456 else
8457 mode = 2; // "exactly"
8458 modeCount = MinParams;
8459 } else {
John McCalladbb8f82010-01-13 09:16:55 +00008460 if (MinParams != FnTy->getNumArgs())
8461 mode = 1; // "at most"
8462 else
8463 mode = 2; // "exactly"
8464 modeCount = FnTy->getNumArgs();
8465 }
8466
8467 std::string Description;
8468 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8469
Richard Smithf7b80562012-05-11 05:16:41 +00008470 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8471 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8472 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8473 << Fn->getParamDecl(0) << NumFormalArgs;
8474 else
8475 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8476 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8477 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008478 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008479}
8480
Larisse Voufo43847122013-07-19 23:00:19 +00008481/// Arity mismatch diagnosis specific to a function overload candidate.
8482void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8483 unsigned NumFormalArgs) {
8484 if (!CheckArityMismatch(S, Cand, NumFormalArgs))
8485 DiagnoseArityMismatch(S, Cand->Function, NumFormalArgs);
8486}
Larisse Voufo8c5d4072013-07-19 22:53:23 +00008487
Larisse Voufo43847122013-07-19 23:00:19 +00008488TemplateDecl *getDescribedTemplate(Decl *Templated) {
8489 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Templated))
8490 return FD->getDescribedFunctionTemplate();
8491 else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Templated))
8492 return RD->getDescribedClassTemplate();
8493
8494 llvm_unreachable("Unsupported: Getting the described template declaration"
8495 " for bad deduction diagnosis");
8496}
8497
8498/// Diagnose a failed template-argument deduction.
8499void DiagnoseBadDeduction(Sema &S, Decl *Templated,
8500 DeductionFailureInfo &DeductionFailure,
8501 unsigned NumArgs) {
8502 TemplateParameter Param = DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008503 NamedDecl *ParamD;
8504 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8505 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8506 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
Larisse Voufo43847122013-07-19 23:00:19 +00008507 switch (DeductionFailure.Result) {
John McCall342fec42010-02-01 18:53:26 +00008508 case Sema::TDK_Success:
8509 llvm_unreachable("TDK_success while diagnosing bad deduction");
8510
8511 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008512 assert(ParamD && "no parameter found for incomplete deduction result");
Larisse Voufo43847122013-07-19 23:00:19 +00008513 S.Diag(Templated->getLocation(),
8514 diag::note_ovl_candidate_incomplete_deduction)
8515 << ParamD->getDeclName();
8516 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008517 return;
8518 }
8519
John McCall57e97782010-08-05 09:05:08 +00008520 case Sema::TDK_Underqualified: {
8521 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8522 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8523
Larisse Voufo43847122013-07-19 23:00:19 +00008524 QualType Param = DeductionFailure.getFirstArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008525
8526 // Param will have been canonicalized, but it should just be a
8527 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008528 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008529 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008530 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008531 assert(S.Context.hasSameType(Param, NonCanonParam));
8532
8533 // Arg has also been canonicalized, but there's nothing we can do
8534 // about that. It also doesn't matter as much, because it won't
8535 // have any template parameters in it (because deduction isn't
8536 // done on dependent types).
Larisse Voufo43847122013-07-19 23:00:19 +00008537 QualType Arg = DeductionFailure.getSecondArg()->getAsType();
John McCall57e97782010-08-05 09:05:08 +00008538
Larisse Voufo43847122013-07-19 23:00:19 +00008539 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_underqualified)
8540 << ParamD->getDeclName() << Arg << NonCanonParam;
8541 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall57e97782010-08-05 09:05:08 +00008542 return;
8543 }
8544
8545 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008546 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008547 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008548 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008549 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008550 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008551 which = 1;
8552 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008553 which = 2;
8554 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008555
Larisse Voufo43847122013-07-19 23:00:19 +00008556 S.Diag(Templated->getLocation(),
8557 diag::note_ovl_candidate_inconsistent_deduction)
8558 << which << ParamD->getDeclName() << *DeductionFailure.getFirstArg()
8559 << *DeductionFailure.getSecondArg();
8560 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregora9333192010-05-08 17:41:32 +00008561 return;
8562 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008563
Douglas Gregorf1a84452010-05-08 19:15:54 +00008564 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008565 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008566 if (ParamD->getDeclName())
Larisse Voufo43847122013-07-19 23:00:19 +00008567 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008568 diag::note_ovl_candidate_explicit_arg_mismatch_named)
Larisse Voufo43847122013-07-19 23:00:19 +00008569 << ParamD->getDeclName();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008570 else {
8571 int index = 0;
8572 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8573 index = TTP->getIndex();
8574 else if (NonTypeTemplateParmDecl *NTTP
8575 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8576 index = NTTP->getIndex();
8577 else
8578 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
Larisse Voufo43847122013-07-19 23:00:19 +00008579 S.Diag(Templated->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008580 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
Larisse Voufo43847122013-07-19 23:00:19 +00008581 << (index + 1);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008582 }
Larisse Voufo43847122013-07-19 23:00:19 +00008583 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008584 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008585
Douglas Gregora18592e2010-05-08 18:13:28 +00008586 case Sema::TDK_TooManyArguments:
8587 case Sema::TDK_TooFewArguments:
Larisse Voufo43847122013-07-19 23:00:19 +00008588 DiagnoseArityMismatch(S, Templated, NumArgs);
Douglas Gregora18592e2010-05-08 18:13:28 +00008589 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008590
8591 case Sema::TDK_InstantiationDepth:
Larisse Voufo43847122013-07-19 23:00:19 +00008592 S.Diag(Templated->getLocation(),
8593 diag::note_ovl_candidate_instantiation_depth);
8594 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008595 return;
8596
8597 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008598 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008599 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008600 if (TemplateArgumentList *Args =
Larisse Voufo43847122013-07-19 23:00:19 +00008601 DeductionFailure.getTemplateArgumentList()) {
Richard Smithb8590f32012-05-07 09:03:25 +00008602 TemplateArgString = " ";
8603 TemplateArgString += S.getTemplateArgumentBindingsText(
Larisse Voufo43847122013-07-19 23:00:19 +00008604 getDescribedTemplate(Templated)->getTemplateParameters(), *Args);
Richard Smithb8590f32012-05-07 09:03:25 +00008605 }
8606
Richard Smith4493c0a2012-05-09 05:17:00 +00008607 // If this candidate was disabled by enable_if, say so.
Larisse Voufo43847122013-07-19 23:00:19 +00008608 PartialDiagnosticAt *PDiag = DeductionFailure.getSFINAEDiagnostic();
Richard Smith4493c0a2012-05-09 05:17:00 +00008609 if (PDiag && PDiag->second.getDiagID() ==
8610 diag::err_typename_nested_not_found_enable_if) {
8611 // FIXME: Use the source range of the condition, and the fully-qualified
8612 // name of the enable_if template. These are both present in PDiag.
8613 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8614 << "'enable_if'" << TemplateArgString;
8615 return;
8616 }
8617
Richard Smithb8590f32012-05-07 09:03:25 +00008618 // Format the SFINAE diagnostic into the argument string.
8619 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8620 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008621 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008622 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008623 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008624 SFINAEArgString = ": ";
8625 R = SourceRange(PDiag->first, PDiag->first);
8626 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8627 }
8628
Larisse Voufo43847122013-07-19 23:00:19 +00008629 S.Diag(Templated->getLocation(),
8630 diag::note_ovl_candidate_substitution_failure)
8631 << TemplateArgString << SFINAEArgString << R;
8632 MaybeEmitInheritedConstructorNote(S, Templated);
Douglas Gregorec20f462010-05-08 20:07:26 +00008633 return;
8634 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008635
Richard Smith0efa62f2013-01-31 04:03:12 +00008636 case Sema::TDK_FailedOverloadResolution: {
Larisse Voufo43847122013-07-19 23:00:19 +00008637 OverloadExpr::FindResult R = OverloadExpr::find(DeductionFailure.getExpr());
8638 S.Diag(Templated->getLocation(),
Richard Smith0efa62f2013-01-31 04:03:12 +00008639 diag::note_ovl_candidate_failed_overload_resolution)
Larisse Voufo43847122013-07-19 23:00:19 +00008640 << R.Expression->getName();
Richard Smith0efa62f2013-01-31 04:03:12 +00008641 return;
8642 }
8643
Richard Trieueef35f82013-04-08 21:11:40 +00008644 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008645 // FIXME: Provide a source location to indicate what we couldn't match.
Larisse Voufo43847122013-07-19 23:00:19 +00008646 TemplateArgument FirstTA = *DeductionFailure.getFirstArg();
8647 TemplateArgument SecondTA = *DeductionFailure.getSecondArg();
Richard Trieueef35f82013-04-08 21:11:40 +00008648 if (FirstTA.getKind() == TemplateArgument::Template &&
8649 SecondTA.getKind() == TemplateArgument::Template) {
8650 TemplateName FirstTN = FirstTA.getAsTemplate();
8651 TemplateName SecondTN = SecondTA.getAsTemplate();
8652 if (FirstTN.getKind() == TemplateName::Template &&
8653 SecondTN.getKind() == TemplateName::Template) {
8654 if (FirstTN.getAsTemplateDecl()->getName() ==
8655 SecondTN.getAsTemplateDecl()->getName()) {
8656 // FIXME: This fixes a bad diagnostic where both templates are named
8657 // the same. This particular case is a bit difficult since:
8658 // 1) It is passed as a string to the diagnostic printer.
8659 // 2) The diagnostic printer only attempts to find a better
8660 // name for types, not decls.
8661 // Ideally, this should folded into the diagnostic printer.
Larisse Voufo43847122013-07-19 23:00:19 +00008662 S.Diag(Templated->getLocation(),
Richard Trieueef35f82013-04-08 21:11:40 +00008663 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8664 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8665 return;
8666 }
8667 }
8668 }
Larisse Voufo43847122013-07-19 23:00:19 +00008669 S.Diag(Templated->getLocation(),
8670 diag::note_ovl_candidate_non_deduced_mismatch)
8671 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008672 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008673 }
John McCall342fec42010-02-01 18:53:26 +00008674 // TODO: diagnose these individually, then kill off
8675 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008676 case Sema::TDK_MiscellaneousDeductionFailure:
Larisse Voufo43847122013-07-19 23:00:19 +00008677 S.Diag(Templated->getLocation(), diag::note_ovl_candidate_bad_deduction);
8678 MaybeEmitInheritedConstructorNote(S, Templated);
John McCall342fec42010-02-01 18:53:26 +00008679 return;
8680 }
8681}
8682
Larisse Voufo43847122013-07-19 23:00:19 +00008683/// Diagnose a failed template-argument deduction, for function calls.
8684void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand, unsigned NumArgs) {
8685 unsigned TDK = Cand->DeductionFailure.Result;
8686 if (TDK == Sema::TDK_TooFewArguments || TDK == Sema::TDK_TooManyArguments) {
8687 if (CheckArityMismatch(S, Cand, NumArgs))
8688 return;
8689 }
8690 DiagnoseBadDeduction(S, Cand->Function, // pattern
8691 Cand->DeductionFailure, NumArgs);
8692}
8693
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008694/// CUDA: diagnose an invalid call across targets.
8695void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8696 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8697 FunctionDecl *Callee = Cand->Function;
8698
8699 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8700 CalleeTarget = S.IdentifyCUDATarget(Callee);
8701
8702 std::string FnDesc;
8703 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8704
8705 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8706 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8707}
8708
John McCall342fec42010-02-01 18:53:26 +00008709/// Generates a 'note' diagnostic for an overload candidate. We've
8710/// already generated a primary error at the call site.
8711///
8712/// It really does need to be a single diagnostic with its caret
8713/// pointed at the candidate declaration. Yes, this creates some
8714/// major challenges of technical writing. Yes, this makes pointing
8715/// out problems with specific arguments quite awkward. It's still
8716/// better than generating twenty screens of text for every failed
8717/// overload.
8718///
8719/// It would be great to be able to express per-candidate problems
8720/// more richly for those diagnostic clients that cared, but we'd
8721/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008722void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008723 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008724 FunctionDecl *Fn = Cand->Function;
8725
John McCall81201622010-01-08 04:41:39 +00008726 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008727 if (Cand->Viable && (Fn->isDeleted() ||
8728 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008729 std::string FnDesc;
8730 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008731
8732 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008733 << FnKind << FnDesc
8734 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008735 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008736 return;
John McCall81201622010-01-08 04:41:39 +00008737 }
8738
John McCall220ccbf2010-01-13 00:25:19 +00008739 // We don't really have anything else to say about viable candidates.
8740 if (Cand->Viable) {
8741 S.NoteOverloadCandidate(Fn);
8742 return;
8743 }
John McCall1d318332010-01-12 00:44:57 +00008744
John McCalladbb8f82010-01-13 09:16:55 +00008745 switch (Cand->FailureKind) {
8746 case ovl_fail_too_many_arguments:
8747 case ovl_fail_too_few_arguments:
8748 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008749
John McCalladbb8f82010-01-13 09:16:55 +00008750 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008751 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008752
John McCall717e8912010-01-23 05:17:32 +00008753 case ovl_fail_trivial_conversion:
8754 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008755 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008756 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008757
John McCallb1bdc622010-02-25 01:37:24 +00008758 case ovl_fail_bad_conversion: {
8759 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008760 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008761 if (Cand->Conversions[I].isBad())
8762 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008763
John McCalladbb8f82010-01-13 09:16:55 +00008764 // FIXME: this currently happens when we're called from SemaInit
8765 // when user-conversion overload fails. Figure out how to handle
8766 // those conditions and diagnose them well.
8767 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008768 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008769
8770 case ovl_fail_bad_target:
8771 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008772 }
John McCalla1d7d622010-01-08 00:58:21 +00008773}
8774
8775void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8776 // Desugar the type of the surrogate down to a function type,
8777 // retaining as many typedefs as possible while still showing
8778 // the function type (and, therefore, its parameter types).
8779 QualType FnType = Cand->Surrogate->getConversionType();
8780 bool isLValueReference = false;
8781 bool isRValueReference = false;
8782 bool isPointer = false;
8783 if (const LValueReferenceType *FnTypeRef =
8784 FnType->getAs<LValueReferenceType>()) {
8785 FnType = FnTypeRef->getPointeeType();
8786 isLValueReference = true;
8787 } else if (const RValueReferenceType *FnTypeRef =
8788 FnType->getAs<RValueReferenceType>()) {
8789 FnType = FnTypeRef->getPointeeType();
8790 isRValueReference = true;
8791 }
8792 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8793 FnType = FnTypePtr->getPointeeType();
8794 isPointer = true;
8795 }
8796 // Desugar down to a function type.
8797 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8798 // Reconstruct the pointer/reference as appropriate.
8799 if (isPointer) FnType = S.Context.getPointerType(FnType);
8800 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8801 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8802
8803 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8804 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008805 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008806}
8807
8808void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008809 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008810 SourceLocation OpLoc,
8811 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008812 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008813 std::string TypeStr("operator");
8814 TypeStr += Opc;
8815 TypeStr += "(";
8816 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008817 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008818 TypeStr += ")";
8819 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8820 } else {
8821 TypeStr += ", ";
8822 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8823 TypeStr += ")";
8824 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8825 }
8826}
8827
8828void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8829 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008830 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008831 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8832 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008833 if (ICS.isBad()) break; // all meaningless after first invalid
8834 if (!ICS.isAmbiguous()) continue;
8835
John McCall120d63c2010-08-24 20:38:10 +00008836 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008837 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008838 }
8839}
8840
Larisse Voufo43847122013-07-19 23:00:19 +00008841static SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
John McCall1b77e732010-01-15 23:32:50 +00008842 if (Cand->Function)
8843 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008844 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008845 return Cand->Surrogate->getLocation();
8846 return SourceLocation();
8847}
8848
Larisse Voufo43847122013-07-19 23:00:19 +00008849static unsigned RankDeductionFailure(const DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008850 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008851 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008852 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008853
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008854 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008855 case Sema::TDK_Incomplete:
8856 return 1;
8857
8858 case Sema::TDK_Underqualified:
8859 case Sema::TDK_Inconsistent:
8860 return 2;
8861
8862 case Sema::TDK_SubstitutionFailure:
8863 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008864 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008865 return 3;
8866
8867 case Sema::TDK_InstantiationDepth:
8868 case Sema::TDK_FailedOverloadResolution:
8869 return 4;
8870
8871 case Sema::TDK_InvalidExplicitArguments:
8872 return 5;
8873
8874 case Sema::TDK_TooManyArguments:
8875 case Sema::TDK_TooFewArguments:
8876 return 6;
8877 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008878 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008879}
8880
John McCallbf65c0b2010-01-12 00:48:53 +00008881struct CompareOverloadCandidatesForDisplay {
8882 Sema &S;
8883 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008884
8885 bool operator()(const OverloadCandidate *L,
8886 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008887 // Fast-path this check.
8888 if (L == R) return false;
8889
John McCall81201622010-01-08 04:41:39 +00008890 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008891 if (L->Viable) {
8892 if (!R->Viable) return true;
8893
8894 // TODO: introduce a tri-valued comparison for overload
8895 // candidates. Would be more worthwhile if we had a sort
8896 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008897 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8898 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008899 } else if (R->Viable)
8900 return false;
John McCall81201622010-01-08 04:41:39 +00008901
John McCall1b77e732010-01-15 23:32:50 +00008902 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008903
John McCall1b77e732010-01-15 23:32:50 +00008904 // Criteria by which we can sort non-viable candidates:
8905 if (!L->Viable) {
8906 // 1. Arity mismatches come after other candidates.
8907 if (L->FailureKind == ovl_fail_too_many_arguments ||
8908 L->FailureKind == ovl_fail_too_few_arguments)
8909 return false;
8910 if (R->FailureKind == ovl_fail_too_many_arguments ||
8911 R->FailureKind == ovl_fail_too_few_arguments)
8912 return true;
John McCall81201622010-01-08 04:41:39 +00008913
John McCall717e8912010-01-23 05:17:32 +00008914 // 2. Bad conversions come first and are ordered by the number
8915 // of bad conversions and quality of good conversions.
8916 if (L->FailureKind == ovl_fail_bad_conversion) {
8917 if (R->FailureKind != ovl_fail_bad_conversion)
8918 return true;
8919
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008920 // The conversion that can be fixed with a smaller number of changes,
8921 // comes first.
8922 unsigned numLFixes = L->Fix.NumConversionsFixed;
8923 unsigned numRFixes = R->Fix.NumConversionsFixed;
8924 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8925 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008926 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008927 if (numLFixes < numRFixes)
8928 return true;
8929 else
8930 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008931 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008932
John McCall717e8912010-01-23 05:17:32 +00008933 // If there's any ordering between the defined conversions...
8934 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008935 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008936
8937 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008938 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008939 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008940 switch (CompareImplicitConversionSequences(S,
8941 L->Conversions[I],
8942 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008943 case ImplicitConversionSequence::Better:
8944 leftBetter++;
8945 break;
8946
8947 case ImplicitConversionSequence::Worse:
8948 leftBetter--;
8949 break;
8950
8951 case ImplicitConversionSequence::Indistinguishable:
8952 break;
8953 }
8954 }
8955 if (leftBetter > 0) return true;
8956 if (leftBetter < 0) return false;
8957
8958 } else if (R->FailureKind == ovl_fail_bad_conversion)
8959 return false;
8960
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008961 if (L->FailureKind == ovl_fail_bad_deduction) {
8962 if (R->FailureKind != ovl_fail_bad_deduction)
8963 return true;
8964
8965 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8966 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008967 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008968 } else if (R->FailureKind == ovl_fail_bad_deduction)
8969 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008970
John McCall1b77e732010-01-15 23:32:50 +00008971 // TODO: others?
8972 }
8973
8974 // Sort everything else by location.
8975 SourceLocation LLoc = GetLocationForCandidate(L);
8976 SourceLocation RLoc = GetLocationForCandidate(R);
8977
8978 // Put candidates without locations (e.g. builtins) at the end.
8979 if (LLoc.isInvalid()) return false;
8980 if (RLoc.isInvalid()) return true;
8981
8982 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008983 }
8984};
8985
John McCall717e8912010-01-23 05:17:32 +00008986/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008987/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008988void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008989 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008990 assert(!Cand->Viable);
8991
8992 // Don't do anything on failures other than bad conversion.
8993 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8994
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008995 // We only want the FixIts if all the arguments can be corrected.
8996 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008997 // Use a implicit copy initialization to check conversion fixes.
8998 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008999
John McCall717e8912010-01-23 05:17:32 +00009000 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00009001 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00009002 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00009003 while (true) {
9004 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
9005 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009006 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00009007 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00009008 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009009 }
John McCall717e8912010-01-23 05:17:32 +00009010 }
9011
9012 if (ConvIdx == ConvCount)
9013 return;
9014
John McCallb1bdc622010-02-25 01:37:24 +00009015 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
9016 "remaining conversion is initialized?");
9017
Douglas Gregor23ef6c02010-04-16 17:45:54 +00009018 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00009019 // operation somehow.
9020 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00009021
9022 const FunctionProtoType* Proto;
9023 unsigned ArgIdx = ConvIdx;
9024
9025 if (Cand->IsSurrogate) {
9026 QualType ConvType
9027 = Cand->Surrogate->getConversionType().getNonReferenceType();
9028 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9029 ConvType = ConvPtrType->getPointeeType();
9030 Proto = ConvType->getAs<FunctionProtoType>();
9031 ArgIdx--;
9032 } else if (Cand->Function) {
9033 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9034 if (isa<CXXMethodDecl>(Cand->Function) &&
9035 !isa<CXXConstructorDecl>(Cand->Function))
9036 ArgIdx--;
9037 } else {
9038 // Builtin binary operator with a bad first conversion.
9039 assert(ConvCount <= 3);
9040 for (; ConvIdx != ConvCount; ++ConvIdx)
9041 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009042 = TryCopyInitialization(S, Args[ConvIdx],
9043 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009044 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009045 /*InOverloadResolution*/ true,
9046 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009047 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009048 return;
9049 }
9050
9051 // Fill in the rest of the conversions.
9052 unsigned NumArgsInProto = Proto->getNumArgs();
9053 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009054 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009055 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009056 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009057 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009058 /*InOverloadResolution=*/true,
9059 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009060 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009061 // Store the FixIt in the candidate if it exists.
9062 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009063 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009064 }
John McCall717e8912010-01-23 05:17:32 +00009065 else
9066 Cand->Conversions[ConvIdx].setEllipsis();
9067 }
9068}
9069
John McCalla1d7d622010-01-08 00:58:21 +00009070} // end anonymous namespace
9071
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009072/// PrintOverloadCandidates - When overload resolution fails, prints
9073/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009074/// set.
John McCall120d63c2010-08-24 20:38:10 +00009075void OverloadCandidateSet::NoteCandidates(Sema &S,
9076 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009077 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009078 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009079 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009080 // Sort the candidates by viability and position. Sorting directly would
9081 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009082 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009083 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9084 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009085 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009086 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009087 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009088 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009089 if (Cand->Function || Cand->IsSurrogate)
9090 Cands.push_back(Cand);
9091 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9092 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009093 }
9094 }
9095
John McCallbf65c0b2010-01-12 00:48:53 +00009096 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009097 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009098
John McCall1d318332010-01-12 00:44:57 +00009099 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009100
Chris Lattner5f9e2722011-07-23 10:55:15 +00009101 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009102 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009103 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009104 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9105 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009106
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009107 // Set an arbitrary limit on the number of candidate functions we'll spam
9108 // the user with. FIXME: This limit should depend on details of the
9109 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009110 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009111 break;
9112 }
9113 ++CandsShown;
9114
John McCalla1d7d622010-01-08 00:58:21 +00009115 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009116 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009117 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009118 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009119 else {
9120 assert(Cand->Viable &&
9121 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009122 // Generally we only see ambiguities including viable builtin
9123 // operators if overload resolution got screwed up by an
9124 // ambiguous user-defined conversion.
9125 //
9126 // FIXME: It's quite possible for different conversions to see
9127 // different ambiguities, though.
9128 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009129 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009130 ReportedAmbiguousConversions = true;
9131 }
John McCalla1d7d622010-01-08 00:58:21 +00009132
John McCall1d318332010-01-12 00:44:57 +00009133 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009134 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009135 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009136 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009137
9138 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009139 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009140}
9141
Larisse Voufo43847122013-07-19 23:00:19 +00009142static SourceLocation
9143GetLocationForCandidate(const TemplateSpecCandidate *Cand) {
9144 return Cand->Specialization ? Cand->Specialization->getLocation()
9145 : SourceLocation();
9146}
9147
9148struct CompareTemplateSpecCandidatesForDisplay {
9149 Sema &S;
9150 CompareTemplateSpecCandidatesForDisplay(Sema &S) : S(S) {}
9151
9152 bool operator()(const TemplateSpecCandidate *L,
9153 const TemplateSpecCandidate *R) {
9154 // Fast-path this check.
9155 if (L == R)
9156 return false;
9157
9158 // Assuming that both candidates are not matches...
9159
9160 // Sort by the ranking of deduction failures.
9161 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
9162 return RankDeductionFailure(L->DeductionFailure) <
9163 RankDeductionFailure(R->DeductionFailure);
9164
9165 // Sort everything else by location.
9166 SourceLocation LLoc = GetLocationForCandidate(L);
9167 SourceLocation RLoc = GetLocationForCandidate(R);
9168
9169 // Put candidates without locations (e.g. builtins) at the end.
9170 if (LLoc.isInvalid())
9171 return false;
9172 if (RLoc.isInvalid())
9173 return true;
9174
9175 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
9176 }
9177};
9178
9179/// Diagnose a template argument deduction failure.
9180/// We are treating these failures as overload failures due to bad
9181/// deductions.
9182void TemplateSpecCandidate::NoteDeductionFailure(Sema &S) {
9183 DiagnoseBadDeduction(S, Specialization, // pattern
9184 DeductionFailure, /*NumArgs=*/0);
9185}
9186
9187void TemplateSpecCandidateSet::destroyCandidates() {
9188 for (iterator i = begin(), e = end(); i != e; ++i) {
9189 i->DeductionFailure.Destroy();
9190 }
9191}
9192
9193void TemplateSpecCandidateSet::clear() {
9194 destroyCandidates();
9195 Candidates.clear();
9196}
9197
9198/// NoteCandidates - When no template specialization match is found, prints
9199/// diagnostic messages containing the non-matching specializations that form
9200/// the candidate set.
9201/// This is analoguous to OverloadCandidateSet::NoteCandidates() with
9202/// OCD == OCD_AllCandidates and Cand->Viable == false.
9203void TemplateSpecCandidateSet::NoteCandidates(Sema &S, SourceLocation Loc) {
9204 // Sort the candidates by position (assuming no candidate is a match).
9205 // Sorting directly would be prohibitive, so we make a set of pointers
9206 // and sort those.
9207 SmallVector<TemplateSpecCandidate *, 32> Cands;
9208 Cands.reserve(size());
9209 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
9210 if (Cand->Specialization)
9211 Cands.push_back(Cand);
9212 // Otherwise, this is a non matching builtin candidate. We do not,
9213 // in general, want to list every possible builtin candidate.
9214 }
9215
9216 std::sort(Cands.begin(), Cands.end(),
9217 CompareTemplateSpecCandidatesForDisplay(S));
9218
9219 // FIXME: Perhaps rename OverloadsShown and getShowOverloads()
9220 // for generalization purposes (?).
9221 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
9222
9223 SmallVectorImpl<TemplateSpecCandidate *>::iterator I, E;
9224 unsigned CandsShown = 0;
9225 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9226 TemplateSpecCandidate *Cand = *I;
9227
9228 // Set an arbitrary limit on the number of candidates we'll spam
9229 // the user with. FIXME: This limit should depend on details of the
9230 // candidate list.
9231 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
9232 break;
9233 ++CandsShown;
9234
9235 assert(Cand->Specialization &&
9236 "Non-matching built-in candidates are not added to Cands.");
9237 Cand->NoteDeductionFailure(S);
9238 }
9239
9240 if (I != E)
9241 S.Diag(Loc, diag::note_ovl_too_many_candidates) << int(E - I);
9242}
9243
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009244// [PossiblyAFunctionType] --> [Return]
9245// NonFunctionType --> NonFunctionType
9246// R (A) --> R(A)
9247// R (*)(A) --> R (A)
9248// R (&)(A) --> R (A)
9249// R (S::*)(A) --> R (A)
9250QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9251 QualType Ret = PossiblyAFunctionType;
9252 if (const PointerType *ToTypePtr =
9253 PossiblyAFunctionType->getAs<PointerType>())
9254 Ret = ToTypePtr->getPointeeType();
9255 else if (const ReferenceType *ToTypeRef =
9256 PossiblyAFunctionType->getAs<ReferenceType>())
9257 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009258 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009259 PossiblyAFunctionType->getAs<MemberPointerType>())
9260 Ret = MemTypePtr->getPointeeType();
9261 Ret =
9262 Context.getCanonicalType(Ret).getUnqualifiedType();
9263 return Ret;
9264}
Douglas Gregor904eed32008-11-10 20:40:00 +00009265
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009266// A helper class to help with address of function resolution
9267// - allows us to avoid passing around all those ugly parameters
9268class AddressOfFunctionResolver
9269{
9270 Sema& S;
9271 Expr* SourceExpr;
9272 const QualType& TargetType;
9273 QualType TargetFunctionType; // Extracted function type from target type
9274
9275 bool Complain;
9276 //DeclAccessPair& ResultFunctionAccessPair;
9277 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009278
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009279 bool TargetTypeIsNonStaticMemberFunction;
9280 bool FoundNonTemplateFunction;
David Majnemer576a9af2013-08-01 06:13:59 +00009281 bool StaticMemberFunctionFromBoundPointer;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009282
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009283 OverloadExpr::FindResult OvlExprInfo;
9284 OverloadExpr *OvlExpr;
9285 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009286 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Larisse Voufo43847122013-07-19 23:00:19 +00009287 TemplateSpecCandidateSet FailedCandidates;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009288
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009289public:
Larisse Voufo43847122013-07-19 23:00:19 +00009290 AddressOfFunctionResolver(Sema &S, Expr *SourceExpr,
9291 const QualType &TargetType, bool Complain)
9292 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9293 Complain(Complain), Context(S.getASTContext()),
9294 TargetTypeIsNonStaticMemberFunction(
9295 !!TargetType->getAs<MemberPointerType>()),
9296 FoundNonTemplateFunction(false),
David Majnemer576a9af2013-08-01 06:13:59 +00009297 StaticMemberFunctionFromBoundPointer(false),
Larisse Voufo43847122013-07-19 23:00:19 +00009298 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9299 OvlExpr(OvlExprInfo.Expression),
9300 FailedCandidates(OvlExpr->getNameLoc()) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009301 ExtractUnqualifiedFunctionTypeFromTargetType();
Chandler Carruth90434232011-03-29 08:08:18 +00009302
David Majnemer576a9af2013-08-01 06:13:59 +00009303 if (TargetFunctionType->isFunctionType()) {
9304 if (UnresolvedMemberExpr *UME = dyn_cast<UnresolvedMemberExpr>(OvlExpr))
9305 if (!UME->isImplicitAccess() &&
9306 !S.ResolveSingleFunctionTemplateSpecialization(UME))
9307 StaticMemberFunctionFromBoundPointer = true;
9308 } else if (OvlExpr->hasExplicitTemplateArgs()) {
9309 DeclAccessPair dap;
9310 if (FunctionDecl *Fn = S.ResolveSingleFunctionTemplateSpecialization(
9311 OvlExpr, false, &dap)) {
9312 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn))
9313 if (!Method->isStatic()) {
9314 // If the target type is a non-function type and the function found
9315 // is a non-static member function, pretend as if that was the
9316 // target, it's the only possible type to end up with.
9317 TargetTypeIsNonStaticMemberFunction = true;
Chandler Carruth90434232011-03-29 08:08:18 +00009318
David Majnemer576a9af2013-08-01 06:13:59 +00009319 // And skip adding the function if its not in the proper form.
9320 // We'll diagnose this due to an empty set of functions.
9321 if (!OvlExprInfo.HasFormOfMemberPointer)
9322 return;
Chandler Carruth90434232011-03-29 08:08:18 +00009323 }
9324
David Majnemer576a9af2013-08-01 06:13:59 +00009325 Matches.push_back(std::make_pair(dap, Fn));
Douglas Gregor83314aa2009-07-08 20:55:45 +00009326 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009327 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009328 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009329
9330 if (OvlExpr->hasExplicitTemplateArgs())
9331 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009332
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009333 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9334 // C++ [over.over]p4:
9335 // If more than one function is selected, [...]
9336 if (Matches.size() > 1) {
9337 if (FoundNonTemplateFunction)
9338 EliminateAllTemplateMatches();
9339 else
9340 EliminateAllExceptMostSpecializedTemplate();
9341 }
9342 }
9343 }
9344
9345private:
9346 bool isTargetTypeAFunction() const {
9347 return TargetFunctionType->isFunctionType();
9348 }
9349
9350 // [ToType] [Return]
9351
9352 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9353 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9354 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9355 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9356 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9357 }
9358
9359 // return true if any matching specializations were found
9360 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9361 const DeclAccessPair& CurAccessFunPair) {
9362 if (CXXMethodDecl *Method
9363 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9364 // Skip non-static function templates when converting to pointer, and
9365 // static when converting to member pointer.
9366 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9367 return false;
9368 }
9369 else if (TargetTypeIsNonStaticMemberFunction)
9370 return false;
9371
9372 // C++ [over.over]p2:
9373 // If the name is a function template, template argument deduction is
9374 // done (14.8.2.2), and if the argument deduction succeeds, the
9375 // resulting template argument list is used to generate a single
9376 // function template specialization, which is added to the set of
9377 // overloaded functions considered.
9378 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009379 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009380 if (Sema::TemplateDeductionResult Result
9381 = S.DeduceTemplateArguments(FunctionTemplate,
9382 &OvlExplicitTemplateArgs,
9383 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009384 Info, /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009385 // Make a note of the failed deduction for diagnostics.
9386 FailedCandidates.addCandidate()
9387 .set(FunctionTemplate->getTemplatedDecl(),
9388 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009389 return false;
9390 }
9391
Douglas Gregor092140a2013-04-17 08:45:07 +00009392 // Template argument deduction ensures that we have an exact match or
9393 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009394 // This function template specicalization works.
9395 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009396 assert(S.isSameOrCompatibleFunctionType(
9397 Context.getCanonicalType(Specialization->getType()),
9398 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009399 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9400 return true;
9401 }
9402
9403 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9404 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009405 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009406 // Skip non-static functions when converting to pointer, and static
9407 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009408 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9409 return false;
9410 }
9411 else if (TargetTypeIsNonStaticMemberFunction)
9412 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009413
Chandler Carruthbd647292009-12-29 06:17:27 +00009414 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009415 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009416 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9417 if (S.CheckCUDATarget(Caller, FunDecl))
9418 return false;
9419
Richard Smith60e141e2013-05-04 07:00:32 +00009420 // If any candidate has a placeholder return type, trigger its deduction
9421 // now.
9422 if (S.getLangOpts().CPlusPlus1y &&
9423 FunDecl->getResultType()->isUndeducedType() &&
9424 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9425 return false;
9426
Douglas Gregor43c79c22009-12-09 00:47:37 +00009427 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009428 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9429 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009430 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9431 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009432 Matches.push_back(std::make_pair(CurAccessFunPair,
9433 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009434 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009435 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009436 }
Mike Stump1eb44332009-09-09 15:08:12 +00009437 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009438
9439 return false;
9440 }
9441
9442 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9443 bool Ret = false;
9444
9445 // If the overload expression doesn't have the form of a pointer to
9446 // member, don't try to convert it to a pointer-to-member type.
9447 if (IsInvalidFormOfPointerToMemberFunction())
9448 return false;
9449
9450 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9451 E = OvlExpr->decls_end();
9452 I != E; ++I) {
9453 // Look through any using declarations to find the underlying function.
9454 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9455
9456 // C++ [over.over]p3:
9457 // Non-member functions and static member functions match
9458 // targets of type "pointer-to-function" or "reference-to-function."
9459 // Nonstatic member functions match targets of
9460 // type "pointer-to-member-function."
9461 // Note that according to DR 247, the containing class does not matter.
9462 if (FunctionTemplateDecl *FunctionTemplate
9463 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9464 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9465 Ret = true;
9466 }
9467 // If we have explicit template arguments supplied, skip non-templates.
9468 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9469 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9470 Ret = true;
9471 }
9472 assert(Ret || Matches.empty());
9473 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009474 }
9475
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009476 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009477 // [...] and any given function template specialization F1 is
9478 // eliminated if the set contains a second function template
9479 // specialization whose function template is more specialized
9480 // than the function template of F1 according to the partial
9481 // ordering rules of 14.5.5.2.
9482
9483 // The algorithm specified above is quadratic. We instead use a
9484 // two-pass algorithm (similar to the one used to identify the
9485 // best viable function in an overload set) that identifies the
9486 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009487
9488 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9489 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9490 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009491
Larisse Voufo43847122013-07-19 23:00:19 +00009492 // TODO: It looks like FailedCandidates does not serve much purpose
9493 // here, since the no_viable diagnostic has index 0.
9494 UnresolvedSetIterator Result = S.getMostSpecialized(
Richard Smith4ad09e62013-09-10 22:59:25 +00009495 MatchesCopy.begin(), MatchesCopy.end(), FailedCandidates,
Larisse Voufo43847122013-07-19 23:00:19 +00009496 SourceExpr->getLocStart(), S.PDiag(),
9497 S.PDiag(diag::err_addr_ovl_ambiguous) << Matches[0]
9498 .second->getDeclName(),
9499 S.PDiag(diag::note_ovl_candidate) << (unsigned)oc_function_template,
9500 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009501
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009502 if (Result != MatchesCopy.end()) {
9503 // Make it the first and only element
9504 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9505 Matches[0].second = cast<FunctionDecl>(*Result);
9506 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009507 }
9508 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009509
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009510 void EliminateAllTemplateMatches() {
9511 // [...] any function template specializations in the set are
9512 // eliminated if the set also contains a non-template function, [...]
9513 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9514 if (Matches[I].second->getPrimaryTemplate() == 0)
9515 ++I;
9516 else {
9517 Matches[I] = Matches[--N];
9518 Matches.set_size(N);
9519 }
9520 }
9521 }
9522
9523public:
9524 void ComplainNoMatchesFound() const {
9525 assert(Matches.empty());
9526 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9527 << OvlExpr->getName() << TargetFunctionType
9528 << OvlExpr->getSourceRange();
Richard Smith72a36a12013-08-14 00:00:44 +00009529 if (FailedCandidates.empty())
9530 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
9531 else {
9532 // We have some deduction failure messages. Use them to diagnose
9533 // the function templates, and diagnose the non-template candidates
9534 // normally.
9535 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9536 IEnd = OvlExpr->decls_end();
9537 I != IEnd; ++I)
9538 if (FunctionDecl *Fun =
9539 dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
9540 S.NoteOverloadCandidate(Fun, TargetFunctionType);
9541 FailedCandidates.NoteCandidates(S, OvlExpr->getLocStart());
9542 }
9543 }
9544
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009545 bool IsInvalidFormOfPointerToMemberFunction() const {
9546 return TargetTypeIsNonStaticMemberFunction &&
9547 !OvlExprInfo.HasFormOfMemberPointer;
9548 }
David Majnemer576a9af2013-08-01 06:13:59 +00009549
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009550 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9551 // TODO: Should we condition this on whether any functions might
9552 // have matched, or is it more appropriate to do that in callers?
9553 // TODO: a fixit wouldn't hurt.
9554 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9555 << TargetType << OvlExpr->getSourceRange();
9556 }
David Majnemer576a9af2013-08-01 06:13:59 +00009557
9558 bool IsStaticMemberFunctionFromBoundPointer() const {
9559 return StaticMemberFunctionFromBoundPointer;
9560 }
9561
9562 void ComplainIsStaticMemberFunctionFromBoundPointer() const {
9563 S.Diag(OvlExpr->getLocStart(),
9564 diag::err_invalid_form_pointer_member_function)
9565 << OvlExpr->getSourceRange();
9566 }
9567
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009568 void ComplainOfInvalidConversion() const {
9569 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9570 << OvlExpr->getName() << TargetType;
9571 }
9572
9573 void ComplainMultipleMatchesFound() const {
9574 assert(Matches.size() > 1);
9575 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9576 << OvlExpr->getName()
9577 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009578 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009579 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009580
9581 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9582
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009583 int getNumMatches() const { return Matches.size(); }
9584
9585 FunctionDecl* getMatchingFunctionDecl() const {
9586 if (Matches.size() != 1) return 0;
9587 return Matches[0].second;
9588 }
9589
9590 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9591 if (Matches.size() != 1) return 0;
9592 return &Matches[0].first;
9593 }
9594};
9595
9596/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9597/// an overloaded function (C++ [over.over]), where @p From is an
9598/// expression with overloaded function type and @p ToType is the type
9599/// we're trying to resolve to. For example:
9600///
9601/// @code
9602/// int f(double);
9603/// int f(int);
9604///
9605/// int (*pfd)(double) = f; // selects f(double)
9606/// @endcode
9607///
9608/// This routine returns the resulting FunctionDecl if it could be
9609/// resolved, and NULL otherwise. When @p Complain is true, this
9610/// routine will emit diagnostics if there is an error.
9611FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009612Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9613 QualType TargetType,
9614 bool Complain,
9615 DeclAccessPair &FoundResult,
9616 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009617 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009618
9619 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9620 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009621 int NumMatches = Resolver.getNumMatches();
9622 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009623 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009624 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9625 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9626 else
9627 Resolver.ComplainNoMatchesFound();
9628 }
9629 else if (NumMatches > 1 && Complain)
9630 Resolver.ComplainMultipleMatchesFound();
9631 else if (NumMatches == 1) {
9632 Fn = Resolver.getMatchingFunctionDecl();
9633 assert(Fn);
9634 FoundResult = *Resolver.getMatchingFunctionAccessPair();
David Majnemer576a9af2013-08-01 06:13:59 +00009635 if (Complain) {
9636 if (Resolver.IsStaticMemberFunctionFromBoundPointer())
9637 Resolver.ComplainIsStaticMemberFunctionFromBoundPointer();
9638 else
9639 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
9640 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00009641 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009642
9643 if (pHadMultipleCandidates)
9644 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009645 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009646}
9647
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009648/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009649/// resolve that overloaded function expression down to a single function.
9650///
9651/// This routine can only resolve template-ids that refer to a single function
9652/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009653/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009654/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009655FunctionDecl *
9656Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9657 bool Complain,
9658 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009659 // C++ [over.over]p1:
9660 // [...] [Note: any redundant set of parentheses surrounding the
9661 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009662 // C++ [over.over]p1:
9663 // [...] The overloaded function name can be preceded by the &
9664 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009665
Douglas Gregor4b52e252009-12-21 23:17:24 +00009666 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009667 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009668 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009669
9670 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009671 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Larisse Voufo43847122013-07-19 23:00:19 +00009672 TemplateSpecCandidateSet FailedCandidates(ovl->getNameLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009673
Douglas Gregor4b52e252009-12-21 23:17:24 +00009674 // Look through all of the overloaded functions, searching for one
9675 // whose type matches exactly.
9676 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009677 for (UnresolvedSetIterator I = ovl->decls_begin(),
9678 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009679 // C++0x [temp.arg.explicit]p3:
9680 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009681 // where deduction is not done, if a template argument list is
9682 // specified and it, along with any default template arguments,
9683 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009684 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009685 FunctionTemplateDecl *FunctionTemplate
9686 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009687
Douglas Gregor4b52e252009-12-21 23:17:24 +00009688 // C++ [over.over]p2:
9689 // If the name is a function template, template argument deduction is
9690 // done (14.8.2.2), and if the argument deduction succeeds, the
9691 // resulting template argument list is used to generate a single
9692 // function template specialization, which is added to the set of
9693 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009694 FunctionDecl *Specialization = 0;
Larisse Voufo43847122013-07-19 23:00:19 +00009695 TemplateDeductionInfo Info(FailedCandidates.getLocation());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009696 if (TemplateDeductionResult Result
9697 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009698 Specialization, Info,
9699 /*InOverloadResolution=*/true)) {
Larisse Voufo43847122013-07-19 23:00:19 +00009700 // Make a note of the failed deduction for diagnostics.
9701 // TODO: Actually use the failed-deduction info?
9702 FailedCandidates.addCandidate()
9703 .set(FunctionTemplate->getTemplatedDecl(),
9704 MakeDeductionFailureInfo(Context, Result, Info));
Douglas Gregor4b52e252009-12-21 23:17:24 +00009705 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009706 }
9707
John McCall864c0412011-04-26 20:42:42 +00009708 assert(Specialization && "no specialization and no error?");
9709
Douglas Gregor4b52e252009-12-21 23:17:24 +00009710 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009711 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009712 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009713 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9714 << ovl->getName();
9715 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009716 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009717 return 0;
John McCall864c0412011-04-26 20:42:42 +00009718 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009719
John McCall864c0412011-04-26 20:42:42 +00009720 Matched = Specialization;
9721 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009722 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009723
Richard Smith60e141e2013-05-04 07:00:32 +00009724 if (Matched && getLangOpts().CPlusPlus1y &&
9725 Matched->getResultType()->isUndeducedType() &&
9726 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9727 return 0;
9728
Douglas Gregor4b52e252009-12-21 23:17:24 +00009729 return Matched;
9730}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009731
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009732
9733
9734
John McCall6dbba4f2011-10-11 23:14:30 +00009735// Resolve and fix an overloaded expression that can be resolved
9736// because it identifies a single function template specialization.
9737//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009738// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009739//
9740// Return true if it was logically possible to so resolve the
9741// expression, regardless of whether or not it succeeded. Always
9742// returns true if 'complain' is set.
9743bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9744 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9745 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009746 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009747 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009748 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009749
John McCall6dbba4f2011-10-11 23:14:30 +00009750 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009751
John McCall864c0412011-04-26 20:42:42 +00009752 DeclAccessPair found;
9753 ExprResult SingleFunctionExpression;
9754 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9755 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009756 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009757 SrcExpr = ExprError();
9758 return true;
9759 }
John McCall864c0412011-04-26 20:42:42 +00009760
9761 // It is only correct to resolve to an instance method if we're
9762 // resolving a form that's permitted to be a pointer to member.
9763 // Otherwise we'll end up making a bound member expression, which
9764 // is illegal in all the contexts we resolve like this.
9765 if (!ovl.HasFormOfMemberPointer &&
9766 isa<CXXMethodDecl>(fn) &&
9767 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009768 if (!complain) return false;
9769
9770 Diag(ovl.Expression->getExprLoc(),
9771 diag::err_bound_member_function)
9772 << 0 << ovl.Expression->getSourceRange();
9773
9774 // TODO: I believe we only end up here if there's a mix of
9775 // static and non-static candidates (otherwise the expression
9776 // would have 'bound member' type, not 'overload' type).
9777 // Ideally we would note which candidate was chosen and why
9778 // the static candidates were rejected.
9779 SrcExpr = ExprError();
9780 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009781 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009782
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009783 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009784 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009785 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009786
9787 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009788 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009789 SingleFunctionExpression =
9790 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009791 if (SingleFunctionExpression.isInvalid()) {
9792 SrcExpr = ExprError();
9793 return true;
9794 }
9795 }
John McCall864c0412011-04-26 20:42:42 +00009796 }
9797
9798 if (!SingleFunctionExpression.isUsable()) {
9799 if (complain) {
9800 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9801 << ovl.Expression->getName()
9802 << DestTypeForComplaining
9803 << OpRangeForComplaining
9804 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009805 NoteAllOverloadCandidates(SrcExpr.get());
9806
9807 SrcExpr = ExprError();
9808 return true;
9809 }
9810
9811 return false;
John McCall864c0412011-04-26 20:42:42 +00009812 }
9813
John McCall6dbba4f2011-10-11 23:14:30 +00009814 SrcExpr = SingleFunctionExpression;
9815 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009816}
9817
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009818/// \brief Add a single candidate to the overload set.
9819static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009820 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009821 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009822 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009823 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009824 bool PartialOverloading,
9825 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009826 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009827 if (isa<UsingShadowDecl>(Callee))
9828 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9829
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009830 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009831 if (ExplicitTemplateArgs) {
9832 assert(!KnownValid && "Explicit template arguments?");
9833 return;
9834 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009835 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9836 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009837 return;
John McCallba135432009-11-21 08:51:07 +00009838 }
9839
9840 if (FunctionTemplateDecl *FuncTemplate
9841 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009842 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009843 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009844 return;
9845 }
9846
Richard Smith2ced0442011-06-26 22:19:54 +00009847 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009848}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009849
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009850/// \brief Add the overload candidates named by callee and/or found by argument
9851/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009852void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009853 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009854 OverloadCandidateSet &CandidateSet,
9855 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009856
9857#ifndef NDEBUG
9858 // Verify that ArgumentDependentLookup is consistent with the rules
9859 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009860 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009861 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9862 // and let Y be the lookup set produced by argument dependent
9863 // lookup (defined as follows). If X contains
9864 //
9865 // -- a declaration of a class member, or
9866 //
9867 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009868 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009869 //
9870 // -- a declaration that is neither a function or a function
9871 // template
9872 //
9873 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009874
John McCall3b4294e2009-12-16 12:17:52 +00009875 if (ULE->requiresADL()) {
9876 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9877 E = ULE->decls_end(); I != E; ++I) {
9878 assert(!(*I)->getDeclContext()->isRecord());
9879 assert(isa<UsingShadowDecl>(*I) ||
9880 !(*I)->getDeclContext()->isFunctionOrMethod());
9881 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009882 }
9883 }
9884#endif
9885
John McCall3b4294e2009-12-16 12:17:52 +00009886 // It would be nice to avoid this copy.
9887 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009888 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009889 if (ULE->hasExplicitTemplateArgs()) {
9890 ULE->copyTemplateArgumentsInto(TABuffer);
9891 ExplicitTemplateArgs = &TABuffer;
9892 }
9893
9894 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9895 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009896 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9897 CandidateSet, PartialOverloading,
9898 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009899
John McCall3b4294e2009-12-16 12:17:52 +00009900 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009901 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009902 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009903 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009904 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009905}
John McCall578b69b2009-12-16 08:11:27 +00009906
Richard Smithd3ff3252013-06-12 22:56:54 +00009907/// Determine whether a declaration with the specified name could be moved into
9908/// a different namespace.
9909static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9910 switch (Name.getCXXOverloadedOperator()) {
9911 case OO_New: case OO_Array_New:
9912 case OO_Delete: case OO_Array_Delete:
9913 return false;
9914
9915 default:
9916 return true;
9917 }
9918}
9919
Richard Smithf50e88a2011-06-05 22:42:48 +00009920/// Attempt to recover from an ill-formed use of a non-dependent name in a
9921/// template, where the non-dependent name was declared after the template
9922/// was defined. This is common in code written for a compilers which do not
9923/// correctly implement two-stage name lookup.
9924///
9925/// Returns true if a viable candidate was found and a diagnostic was issued.
9926static bool
9927DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9928 const CXXScopeSpec &SS, LookupResult &R,
9929 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009930 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009931 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9932 return false;
9933
9934 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009935 if (DC->isTransparentContext())
9936 continue;
9937
Richard Smithf50e88a2011-06-05 22:42:48 +00009938 SemaRef.LookupQualifiedName(R, DC);
9939
9940 if (!R.empty()) {
9941 R.suppressDiagnostics();
9942
9943 if (isa<CXXRecordDecl>(DC)) {
9944 // Don't diagnose names we find in classes; we get much better
9945 // diagnostics for these from DiagnoseEmptyLookup.
9946 R.clear();
9947 return false;
9948 }
9949
9950 OverloadCandidateSet Candidates(FnLoc);
9951 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9952 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009953 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009954 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009955
9956 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009957 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009958 // No viable functions. Don't bother the user with notes for functions
9959 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009960 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009961 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009962 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009963
9964 // Find the namespaces where ADL would have looked, and suggest
9965 // declaring the function there instead.
9966 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9967 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009968 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009969 AssociatedNamespaces,
9970 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009971 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009972 if (canBeDeclaredInNamespace(R.getLookupName())) {
9973 DeclContext *Std = SemaRef.getStdNamespace();
9974 for (Sema::AssociatedNamespaceSet::iterator
9975 it = AssociatedNamespaces.begin(),
9976 end = AssociatedNamespaces.end(); it != end; ++it) {
9977 // Never suggest declaring a function within namespace 'std'.
9978 if (Std && Std->Encloses(*it))
9979 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009980
Richard Smithd3ff3252013-06-12 22:56:54 +00009981 // Never suggest declaring a function within a namespace with a
9982 // reserved name, like __gnu_cxx.
9983 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9984 if (NS &&
9985 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9986 continue;
9987
9988 SuggestedNamespaces.insert(*it);
9989 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009990 }
9991
9992 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9993 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009994 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009995 SemaRef.Diag(Best->Function->getLocation(),
9996 diag::note_not_found_by_two_phase_lookup)
9997 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009998 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009999 SemaRef.Diag(Best->Function->getLocation(),
10000 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +000010001 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +000010002 } else {
10003 // FIXME: It would be useful to list the associated namespaces here,
10004 // but the diagnostics infrastructure doesn't provide a way to produce
10005 // a localized representation of a list of items.
10006 SemaRef.Diag(Best->Function->getLocation(),
10007 diag::note_not_found_by_two_phase_lookup)
10008 << R.getLookupName() << 2;
10009 }
10010
10011 // Try to recover by calling this function.
10012 return true;
10013 }
10014
10015 R.clear();
10016 }
10017
10018 return false;
10019}
10020
10021/// Attempt to recover from ill-formed use of a non-dependent operator in a
10022/// template, where the non-dependent operator was declared after the template
10023/// was defined.
10024///
10025/// Returns true if a viable candidate was found and a diagnostic was issued.
10026static bool
10027DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
10028 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000010029 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +000010030 DeclarationName OpName =
10031 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
10032 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
10033 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010034 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +000010035}
10036
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010037namespace {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010038class BuildRecoveryCallExprRAII {
10039 Sema &SemaRef;
10040public:
10041 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
10042 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
10043 SemaRef.IsBuildingRecoveryCallExpr = true;
10044 }
10045
10046 ~BuildRecoveryCallExprRAII() {
10047 SemaRef.IsBuildingRecoveryCallExpr = false;
10048 }
10049};
10050
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +000010051}
10052
John McCall578b69b2009-12-16 08:11:27 +000010053/// Attempts to recover from a call where no functions were found.
10054///
10055/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +000010056static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +000010057BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +000010058 UnresolvedLookupExpr *ULE,
10059 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010060 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +000010061 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010062 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +000010063 // Do not try to recover if it is already building a recovery call.
10064 // This stops infinite loops for template instantiations like
10065 //
10066 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
10067 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
10068 //
10069 if (SemaRef.IsBuildingRecoveryCallExpr)
10070 return ExprError();
10071 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +000010072
10073 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +000010074 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010075 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +000010076
John McCall3b4294e2009-12-16 12:17:52 +000010077 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +000010078 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +000010079 if (ULE->hasExplicitTemplateArgs()) {
10080 ULE->copyTemplateArgumentsInto(TABuffer);
10081 ExplicitTemplateArgs = &TABuffer;
10082 }
10083
John McCall578b69b2009-12-16 08:11:27 +000010084 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
10085 Sema::LookupOrdinaryName);
Kaelyn Uhrain761695f2013-07-08 23:13:39 +000010086 FunctionCallFilterCCC Validator(SemaRef, Args.size(),
10087 ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010088 NoTypoCorrectionCCC RejectAll;
10089 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
10090 (CorrectionCandidateCallback*)&Validator :
10091 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +000010092 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010093 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +000010094 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010095 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010096 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +000010097 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +000010098
John McCall3b4294e2009-12-16 12:17:52 +000010099 assert(!R.empty() && "lookup results empty despite recovery");
10100
10101 // Build an implicit member call if appropriate. Just drop the
10102 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010103 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010104 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010105 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10106 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010107 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010108 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010109 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010110 else
10111 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10112
10113 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010114 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010115
10116 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010117 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010118 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010119 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010120 MultiExprArg(Args.data(), Args.size()),
10121 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010122}
Douglas Gregord7a95972010-06-08 17:35:15 +000010123
Sam Panzere1715b62012-08-21 00:52:01 +000010124/// \brief Constructs and populates an OverloadedCandidateSet from
10125/// the given function.
10126/// \returns true when an the ExprResult output parameter has been set.
10127bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10128 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010129 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010130 SourceLocation RParenLoc,
10131 OverloadCandidateSet *CandidateSet,
10132 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010133#ifndef NDEBUG
10134 if (ULE->requiresADL()) {
10135 // To do ADL, we must have found an unqualified name.
10136 assert(!ULE->getQualifier() && "qualified name with ADL");
10137
10138 // We don't perform ADL for implicit declarations of builtins.
10139 // Verify that this was correctly set up.
10140 FunctionDecl *F;
10141 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10142 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10143 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010144 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010145
John McCall3b4294e2009-12-16 12:17:52 +000010146 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010147 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010148 }
John McCall3b4294e2009-12-16 12:17:52 +000010149#endif
10150
John McCall5acb0c92011-10-17 18:40:02 +000010151 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010152 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010153 *Result = ExprError();
10154 return true;
10155 }
Douglas Gregor17330012009-02-04 15:01:18 +000010156
John McCall3b4294e2009-12-16 12:17:52 +000010157 // Add the functions denoted by the callee to the set of candidate
10158 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010159 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010160
10161 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010162 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10163 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010164 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010165 // In Microsoft mode, if we are inside a template class member function then
10166 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010167 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010168 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010169 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010170 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010171 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010172 Context.DependentTy, VK_RValue,
10173 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010174 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010175 *Result = Owned(CE);
10176 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010177 }
Sam Panzere1715b62012-08-21 00:52:01 +000010178 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010179 }
John McCall578b69b2009-12-16 08:11:27 +000010180
John McCall5acb0c92011-10-17 18:40:02 +000010181 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010182 return false;
10183}
John McCall5acb0c92011-10-17 18:40:02 +000010184
Sam Panzere1715b62012-08-21 00:52:01 +000010185/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10186/// the completed call expression. If overload resolution fails, emits
10187/// diagnostics and returns ExprError()
10188static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10189 UnresolvedLookupExpr *ULE,
10190 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010191 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010192 SourceLocation RParenLoc,
10193 Expr *ExecConfig,
10194 OverloadCandidateSet *CandidateSet,
10195 OverloadCandidateSet::iterator *Best,
10196 OverloadingResult OverloadResult,
10197 bool AllowTypoCorrection) {
10198 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010199 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010200 RParenLoc, /*EmptyLookup=*/true,
10201 AllowTypoCorrection);
10202
10203 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010204 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010205 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010206 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010207 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10208 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010209 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010210 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10211 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010212 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010213
Richard Smithf50e88a2011-06-05 22:42:48 +000010214 case OR_No_Viable_Function: {
10215 // Try to recover by looking for viable functions which the user might
10216 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010217 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010218 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010219 /*EmptyLookup=*/false,
10220 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010221 if (!Recovery.isInvalid())
10222 return Recovery;
10223
Sam Panzere1715b62012-08-21 00:52:01 +000010224 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010225 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010226 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010227 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010228 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010229 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010230
10231 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010232 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010233 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010234 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010235 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010236
Sam Panzere1715b62012-08-21 00:52:01 +000010237 case OR_Deleted: {
10238 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10239 << (*Best)->Function->isDeleted()
10240 << ULE->getName()
10241 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10242 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010243 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010244
Sam Panzere1715b62012-08-21 00:52:01 +000010245 // We emitted an error for the unvailable/deleted function call but keep
10246 // the call in the AST.
10247 FunctionDecl *FDecl = (*Best)->Function;
10248 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010249 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10250 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010251 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010252 }
10253
Douglas Gregorff331c12010-07-25 18:17:45 +000010254 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010255 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010256}
10257
Sam Panzere1715b62012-08-21 00:52:01 +000010258/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10259/// (which eventually refers to the declaration Func) and the call
10260/// arguments Args/NumArgs, attempt to resolve the function call down
10261/// to a specific function. If overload resolution succeeds, returns
10262/// the call expression produced by overload resolution.
10263/// Otherwise, emits diagnostics and returns ExprError.
10264ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10265 UnresolvedLookupExpr *ULE,
10266 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010267 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010268 SourceLocation RParenLoc,
10269 Expr *ExecConfig,
10270 bool AllowTypoCorrection) {
10271 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10272 ExprResult result;
10273
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010274 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10275 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010276 return result;
10277
10278 OverloadCandidateSet::iterator Best;
10279 OverloadingResult OverloadResult =
10280 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10281
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010282 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010283 RParenLoc, ExecConfig, &CandidateSet,
10284 &Best, OverloadResult,
10285 AllowTypoCorrection);
10286}
10287
John McCall6e266892010-01-26 03:27:55 +000010288static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010289 return Functions.size() > 1 ||
10290 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10291}
10292
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010293/// \brief Create a unary operation that may resolve to an overloaded
10294/// operator.
10295///
10296/// \param OpLoc The location of the operator itself (e.g., '*').
10297///
10298/// \param OpcIn The UnaryOperator::Opcode that describes this
10299/// operator.
10300///
James Dennett40ae6662012-06-22 08:52:37 +000010301/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010302/// considered by overload resolution. The caller needs to build this
10303/// set based on the context using, e.g.,
10304/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10305/// set should not contain any member functions; those will be added
10306/// by CreateOverloadedUnaryOp().
10307///
James Dennett8da16872012-06-22 10:32:46 +000010308/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010309ExprResult
John McCall6e266892010-01-26 03:27:55 +000010310Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10311 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010312 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010313 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010314
10315 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10316 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10317 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010318 // TODO: provide better source location info.
10319 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010320
John McCall5acb0c92011-10-17 18:40:02 +000010321 if (checkPlaceholderForOverload(*this, Input))
10322 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010323
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010324 Expr *Args[2] = { Input, 0 };
10325 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010326
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010327 // For post-increment and post-decrement, add the implicit '0' as
10328 // the second argument, so that we know this is a post-increment or
10329 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010330 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010331 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010332 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10333 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010334 NumArgs = 2;
10335 }
10336
Richard Smith958ba642013-05-05 15:51:06 +000010337 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10338
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010339 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010340 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010341 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010342 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010343 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010344 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010345 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010346
John McCallc373d482010-01-27 01:50:18 +000010347 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010348 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010349 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010350 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010351 /*ADL*/ true, IsOverloaded(Fns),
10352 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010353 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010354 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010355 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010356 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010357 }
10358
10359 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010360 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010361
10362 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010363 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010364
10365 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010366 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010367
John McCall6e266892010-01-26 03:27:55 +000010368 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010369 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10370 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010371 CandidateSet);
10372
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010373 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010374 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010375
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010376 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10377
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010378 // Perform overload resolution.
10379 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010380 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010381 case OR_Success: {
10382 // We found a built-in operator or an overloaded operator.
10383 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010384
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010385 if (FnDecl) {
10386 // We matched an overloaded operator. Build a call to that
10387 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010388
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010389 // Convert the arguments.
10390 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010391 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010392
John Wiegley429bb272011-04-08 18:41:53 +000010393 ExprResult InputRes =
10394 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10395 Best->FoundDecl, Method);
10396 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010397 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010398 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010399 } else {
10400 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010401 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010402 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010403 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010404 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010405 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010406 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010407 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010408 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010409 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010410 }
10411
John McCallf89e55a2010-11-18 06:31:45 +000010412 // Determine the result type.
10413 QualType ResultTy = FnDecl->getResultType();
10414 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10415 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010416
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010417 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010418 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010419 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010420 if (FnExpr.isInvalid())
10421 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010422
Eli Friedman4c3b8962009-11-18 03:58:17 +000010423 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010424 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010425 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010426 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010427
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010428 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010429 FnDecl))
10430 return ExprError();
10431
John McCall9ae2f072010-08-23 23:25:46 +000010432 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010433 } else {
10434 // We matched a built-in operator. Convert the arguments, then
10435 // break out so that we will build the appropriate built-in
10436 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010437 ExprResult InputRes =
10438 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10439 Best->Conversions[0], AA_Passing);
10440 if (InputRes.isInvalid())
10441 return ExprError();
10442 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010443 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010444 }
John Wiegley429bb272011-04-08 18:41:53 +000010445 }
10446
10447 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010448 // This is an erroneous use of an operator which can be overloaded by
10449 // a non-member function. Check for non-member operators which were
10450 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010451 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010452 // FIXME: Recover by calling the found function.
10453 return ExprError();
10454
John Wiegley429bb272011-04-08 18:41:53 +000010455 // No viable function; fall through to handling this as a
10456 // built-in operator, which will produce an error message for us.
10457 break;
10458
10459 case OR_Ambiguous:
10460 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10461 << UnaryOperator::getOpcodeStr(Opc)
10462 << Input->getType()
10463 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010464 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010465 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10466 return ExprError();
10467
10468 case OR_Deleted:
10469 Diag(OpLoc, diag::err_ovl_deleted_oper)
10470 << Best->Function->isDeleted()
10471 << UnaryOperator::getOpcodeStr(Opc)
10472 << getDeletedOrUnavailableSuffix(Best->Function)
10473 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010474 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010475 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010476 return ExprError();
10477 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010478
10479 // Either we found no viable overloaded operator or we matched a
10480 // built-in operator. In either case, fall through to trying to
10481 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010482 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010483}
10484
Douglas Gregor063daf62009-03-13 18:40:31 +000010485/// \brief Create a binary operation that may resolve to an overloaded
10486/// operator.
10487///
10488/// \param OpLoc The location of the operator itself (e.g., '+').
10489///
10490/// \param OpcIn The BinaryOperator::Opcode that describes this
10491/// operator.
10492///
James Dennett40ae6662012-06-22 08:52:37 +000010493/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010494/// considered by overload resolution. The caller needs to build this
10495/// set based on the context using, e.g.,
10496/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10497/// set should not contain any member functions; those will be added
10498/// by CreateOverloadedBinOp().
10499///
10500/// \param LHS Left-hand argument.
10501/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010502ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010503Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010504 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010505 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010506 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010507 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010508 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010509
10510 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10511 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10512 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10513
10514 // If either side is type-dependent, create an appropriate dependent
10515 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010516 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010517 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010518 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010519 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010520 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010521 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010522 Context.DependentTy,
10523 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010524 OpLoc,
10525 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010526
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010527 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10528 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010529 VK_LValue,
10530 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010531 Context.DependentTy,
10532 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010533 OpLoc,
10534 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010535 }
John McCall6e266892010-01-26 03:27:55 +000010536
10537 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010538 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010539 // TODO: provide better source location info in DNLoc component.
10540 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010541 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010542 = UnresolvedLookupExpr::Create(Context, NamingClass,
10543 NestedNameSpecifierLoc(), OpNameInfo,
10544 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010545 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010546 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10547 Context.DependentTy, VK_RValue,
10548 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010549 }
10550
John McCall5acb0c92011-10-17 18:40:02 +000010551 // Always do placeholder-like conversions on the RHS.
10552 if (checkPlaceholderForOverload(*this, Args[1]))
10553 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010554
John McCall3c3b7f92011-10-25 17:37:35 +000010555 // Do placeholder-like conversion on the LHS; note that we should
10556 // not get here with a PseudoObject LHS.
10557 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010558 if (checkPlaceholderForOverload(*this, Args[0]))
10559 return ExprError();
10560
Sebastian Redl275c2b42009-11-18 23:10:33 +000010561 // If this is the assignment operator, we only perform overload resolution
10562 // if the left-hand side is a class or enumeration type. This is actually
10563 // a hack. The standard requires that we do overload resolution between the
10564 // various built-in candidates, but as DR507 points out, this can lead to
10565 // problems. So we do it this way, which pretty much follows what GCC does.
10566 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010567 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010568 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010569
John McCall0e800c92010-12-04 08:14:53 +000010570 // If this is the .* operator, which is not overloadable, just
10571 // create a built-in binary operator.
10572 if (Opc == BO_PtrMemD)
10573 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10574
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010575 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010576 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010577
10578 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010579 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010580
10581 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010582 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010583
John McCall6e266892010-01-26 03:27:55 +000010584 // Add candidates from ADL.
10585 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010586 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010587 /*ExplicitTemplateArgs*/ 0,
10588 CandidateSet);
10589
Douglas Gregor063daf62009-03-13 18:40:31 +000010590 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010591 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010592
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010593 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10594
Douglas Gregor063daf62009-03-13 18:40:31 +000010595 // Perform overload resolution.
10596 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010597 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010598 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010599 // We found a built-in operator or an overloaded operator.
10600 FunctionDecl *FnDecl = Best->Function;
10601
10602 if (FnDecl) {
10603 // We matched an overloaded operator. Build a call to that
10604 // operator.
10605
10606 // Convert the arguments.
10607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010608 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010609 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010610
Chandler Carruth6df868e2010-12-12 08:17:55 +000010611 ExprResult Arg1 =
10612 PerformCopyInitialization(
10613 InitializedEntity::InitializeParameter(Context,
10614 FnDecl->getParamDecl(0)),
10615 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010616 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010617 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010618
John Wiegley429bb272011-04-08 18:41:53 +000010619 ExprResult Arg0 =
10620 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10621 Best->FoundDecl, Method);
10622 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010623 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010624 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010625 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010626 } else {
10627 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010628 ExprResult Arg0 = PerformCopyInitialization(
10629 InitializedEntity::InitializeParameter(Context,
10630 FnDecl->getParamDecl(0)),
10631 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010632 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010633 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010634
Chandler Carruth6df868e2010-12-12 08:17:55 +000010635 ExprResult Arg1 =
10636 PerformCopyInitialization(
10637 InitializedEntity::InitializeParameter(Context,
10638 FnDecl->getParamDecl(1)),
10639 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010640 if (Arg1.isInvalid())
10641 return ExprError();
10642 Args[0] = LHS = Arg0.takeAs<Expr>();
10643 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010644 }
10645
John McCallf89e55a2010-11-18 06:31:45 +000010646 // Determine the result type.
10647 QualType ResultTy = FnDecl->getResultType();
10648 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10649 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010650
10651 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010652 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010653 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010654 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010655 if (FnExpr.isInvalid())
10656 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010657
John McCall9ae2f072010-08-23 23:25:46 +000010658 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010659 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010660 Args, ResultTy, VK, OpLoc,
10661 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010662
10663 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010664 FnDecl))
10665 return ExprError();
10666
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010667 ArrayRef<const Expr *> ArgsArray(Args, 2);
10668 // Cut off the implicit 'this'.
10669 if (isa<CXXMethodDecl>(FnDecl))
10670 ArgsArray = ArgsArray.slice(1);
10671 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10672 TheCall->getSourceRange(), VariadicDoesNotApply);
10673
John McCall9ae2f072010-08-23 23:25:46 +000010674 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010675 } else {
10676 // We matched a built-in operator. Convert the arguments, then
10677 // break out so that we will build the appropriate built-in
10678 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010679 ExprResult ArgsRes0 =
10680 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10681 Best->Conversions[0], AA_Passing);
10682 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010683 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010684 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010685
John Wiegley429bb272011-04-08 18:41:53 +000010686 ExprResult ArgsRes1 =
10687 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10688 Best->Conversions[1], AA_Passing);
10689 if (ArgsRes1.isInvalid())
10690 return ExprError();
10691 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010692 break;
10693 }
10694 }
10695
Douglas Gregor33074752009-09-30 21:46:01 +000010696 case OR_No_Viable_Function: {
10697 // C++ [over.match.oper]p9:
10698 // If the operator is the operator , [...] and there are no
10699 // viable functions, then the operator is assumed to be the
10700 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010701 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010702 break;
10703
Chandler Carruth6df868e2010-12-12 08:17:55 +000010704 // For class as left operand for assignment or compound assigment
10705 // operator do not fall through to handling in built-in, but report that
10706 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010707 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010708 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010709 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010710 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10711 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010712 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman3f93d4c2013-08-28 20:35:35 +000010713 if (Args[0]->getType()->isIncompleteType()) {
10714 Diag(OpLoc, diag::note_assign_lhs_incomplete)
10715 << Args[0]->getType()
10716 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10717 }
Douglas Gregor33074752009-09-30 21:46:01 +000010718 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010719 // This is an erroneous use of an operator which can be overloaded by
10720 // a non-member function. Check for non-member operators which were
10721 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010722 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010723 // FIXME: Recover by calling the found function.
10724 return ExprError();
10725
Douglas Gregor33074752009-09-30 21:46:01 +000010726 // No viable function; try to create a built-in operation, which will
10727 // produce an error. Then, show the non-viable candidates.
10728 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010729 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010730 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010731 "C++ binary operator overloading is missing candidates!");
10732 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010733 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010734 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010735 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010736 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010737
10738 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010739 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010740 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010741 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010742 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010743 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010744 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010745 return ExprError();
10746
10747 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010748 if (isImplicitlyDeleted(Best->Function)) {
10749 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10750 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010751 << Context.getRecordType(Method->getParent())
10752 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010753
Richard Smith0f46e642012-12-28 12:23:24 +000010754 // The user probably meant to call this special member. Just
10755 // explain why it's deleted.
10756 NoteDeletedFunction(Method);
10757 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010758 } else {
10759 Diag(OpLoc, diag::err_ovl_deleted_oper)
10760 << Best->Function->isDeleted()
10761 << BinaryOperator::getOpcodeStr(Opc)
10762 << getDeletedOrUnavailableSuffix(Best->Function)
10763 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10764 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010765 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010766 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010767 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010768 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010769
Douglas Gregor33074752009-09-30 21:46:01 +000010770 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010771 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010772}
10773
John McCall60d7b3a2010-08-24 06:29:42 +000010774ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010775Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10776 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010777 Expr *Base, Expr *Idx) {
10778 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010779 DeclarationName OpName =
10780 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10781
10782 // If either side is type-dependent, create an appropriate dependent
10783 // expression.
10784 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10785
John McCallc373d482010-01-27 01:50:18 +000010786 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010787 // CHECKME: no 'operator' keyword?
10788 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10789 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010790 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010791 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010792 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010793 /*ADL*/ true, /*Overloaded*/ false,
10794 UnresolvedSetIterator(),
10795 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010796 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010797
Sebastian Redlf322ed62009-10-29 20:17:01 +000010798 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010799 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010800 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010801 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010802 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010803 }
10804
John McCall5acb0c92011-10-17 18:40:02 +000010805 // Handle placeholders on both operands.
10806 if (checkPlaceholderForOverload(*this, Args[0]))
10807 return ExprError();
10808 if (checkPlaceholderForOverload(*this, Args[1]))
10809 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010810
Sebastian Redlf322ed62009-10-29 20:17:01 +000010811 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010812 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010813
10814 // Subscript can only be overloaded as a member function.
10815
10816 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010817 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010818
10819 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010820 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010821
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010822 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10823
Sebastian Redlf322ed62009-10-29 20:17:01 +000010824 // Perform overload resolution.
10825 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010826 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010827 case OR_Success: {
10828 // We found a built-in operator or an overloaded operator.
10829 FunctionDecl *FnDecl = Best->Function;
10830
10831 if (FnDecl) {
10832 // We matched an overloaded operator. Build a call to that
10833 // operator.
10834
John McCall9aa472c2010-03-19 07:35:19 +000010835 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010836
Sebastian Redlf322ed62009-10-29 20:17:01 +000010837 // Convert the arguments.
10838 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010839 ExprResult Arg0 =
10840 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10841 Best->FoundDecl, Method);
10842 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010843 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010844 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010845
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010846 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010847 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010848 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010849 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010850 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010851 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010852 Owned(Args[1]));
10853 if (InputInit.isInvalid())
10854 return ExprError();
10855
10856 Args[1] = InputInit.takeAs<Expr>();
10857
Sebastian Redlf322ed62009-10-29 20:17:01 +000010858 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010859 QualType ResultTy = FnDecl->getResultType();
10860 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10861 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010862
10863 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010864 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10865 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010866 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010867 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010868 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010869 OpLocInfo.getLoc(),
10870 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010871 if (FnExpr.isInvalid())
10872 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010873
John McCall9ae2f072010-08-23 23:25:46 +000010874 CXXOperatorCallExpr *TheCall =
10875 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010876 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010877 ResultTy, VK, RLoc,
10878 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010879
John McCall9ae2f072010-08-23 23:25:46 +000010880 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010881 FnDecl))
10882 return ExprError();
10883
John McCall9ae2f072010-08-23 23:25:46 +000010884 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010885 } else {
10886 // We matched a built-in operator. Convert the arguments, then
10887 // break out so that we will build the appropriate built-in
10888 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010889 ExprResult ArgsRes0 =
10890 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10891 Best->Conversions[0], AA_Passing);
10892 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010893 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010894 Args[0] = ArgsRes0.take();
10895
10896 ExprResult ArgsRes1 =
10897 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10898 Best->Conversions[1], AA_Passing);
10899 if (ArgsRes1.isInvalid())
10900 return ExprError();
10901 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010902
10903 break;
10904 }
10905 }
10906
10907 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010908 if (CandidateSet.empty())
10909 Diag(LLoc, diag::err_ovl_no_oper)
10910 << Args[0]->getType() << /*subscript*/ 0
10911 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10912 else
10913 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10914 << Args[0]->getType()
10915 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010916 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010917 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010918 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010919 }
10920
10921 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010922 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010923 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010924 << Args[0]->getType() << Args[1]->getType()
10925 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010926 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010927 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010928 return ExprError();
10929
10930 case OR_Deleted:
10931 Diag(LLoc, diag::err_ovl_deleted_oper)
10932 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010933 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010934 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010935 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010936 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010937 return ExprError();
10938 }
10939
10940 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010941 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010942}
10943
Douglas Gregor88a35142008-12-22 05:46:06 +000010944/// BuildCallToMemberFunction - Build a call to a member
10945/// function. MemExpr is the expression that refers to the member
10946/// function (and includes the object parameter), Args/NumArgs are the
10947/// arguments to the function call (not including the object
10948/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010949/// expression refers to a non-static member function or an overloaded
10950/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010951ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010952Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010953 SourceLocation LParenLoc,
10954 MultiExprArg Args,
10955 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010956 assert(MemExprE->getType() == Context.BoundMemberTy ||
10957 MemExprE->getType() == Context.OverloadTy);
10958
Douglas Gregor88a35142008-12-22 05:46:06 +000010959 // Dig out the member expression. This holds both the object
10960 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010961 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010962
John McCall864c0412011-04-26 20:42:42 +000010963 // Determine whether this is a call to a pointer-to-member function.
10964 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10965 assert(op->getType() == Context.BoundMemberTy);
10966 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10967
10968 QualType fnType =
10969 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10970
10971 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10972 QualType resultType = proto->getCallResultType(Context);
10973 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10974
10975 // Check that the object type isn't more qualified than the
10976 // member function we're calling.
10977 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10978
10979 QualType objectType = op->getLHS()->getType();
10980 if (op->getOpcode() == BO_PtrMemI)
10981 objectType = objectType->castAs<PointerType>()->getPointeeType();
10982 Qualifiers objectQuals = objectType.getQualifiers();
10983
10984 Qualifiers difference = objectQuals - funcQuals;
10985 difference.removeObjCGCAttr();
10986 difference.removeAddressSpace();
10987 if (difference) {
10988 std::string qualsString = difference.getAsString();
10989 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10990 << fnType.getUnqualifiedType()
10991 << qualsString
10992 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10993 }
10994
10995 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010996 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000010997 resultType, valueKind, RParenLoc);
10998
10999 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000011000 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000011001 call, 0))
11002 return ExprError();
11003
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011004 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000011005 return ExprError();
11006
Richard Trieue2a90b82013-06-22 02:30:38 +000011007 if (CheckOtherCall(call, proto))
11008 return ExprError();
11009
John McCall864c0412011-04-26 20:42:42 +000011010 return MaybeBindToTemporary(call);
11011 }
11012
John McCall5acb0c92011-10-17 18:40:02 +000011013 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011014 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011015 return ExprError();
11016
John McCall129e2df2009-11-30 22:42:35 +000011017 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000011018 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000011019 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011020 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000011021 if (isa<MemberExpr>(NakedMemExpr)) {
11022 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000011023 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000011024 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000011025 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000011026 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000011027 } else {
11028 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000011029 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011030
John McCall701c89e2009-12-03 04:06:58 +000011031 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011032 Expr::Classification ObjectClassification
11033 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
11034 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000011035
Douglas Gregor88a35142008-12-22 05:46:06 +000011036 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000011037 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000011038
John McCallaa81e162009-12-01 22:10:20 +000011039 // FIXME: avoid copy.
11040 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11041 if (UnresExpr->hasExplicitTemplateArgs()) {
11042 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11043 TemplateArgs = &TemplateArgsBuffer;
11044 }
11045
John McCall129e2df2009-11-30 22:42:35 +000011046 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
11047 E = UnresExpr->decls_end(); I != E; ++I) {
11048
John McCall701c89e2009-12-03 04:06:58 +000011049 NamedDecl *Func = *I;
11050 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
11051 if (isa<UsingShadowDecl>(Func))
11052 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
11053
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011054
Francois Pichetdbee3412011-01-18 05:04:39 +000011055 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000011056 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000011057 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011058 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000011059 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011060 // If explicit template arguments were provided, we can't call a
11061 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000011062 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000011063 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011064
John McCall9aa472c2010-03-19 07:35:19 +000011065 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011066 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011067 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011068 } else {
John McCall129e2df2009-11-30 22:42:35 +000011069 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000011070 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011071 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011072 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000011073 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000011074 }
Douglas Gregordec06662009-08-21 18:42:58 +000011075 }
Mike Stump1eb44332009-09-09 15:08:12 +000011076
John McCall129e2df2009-11-30 22:42:35 +000011077 DeclarationName DeclName = UnresExpr->getMemberName();
11078
John McCall5acb0c92011-10-17 18:40:02 +000011079 UnbridgedCasts.restore();
11080
Douglas Gregor88a35142008-12-22 05:46:06 +000011081 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011082 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000011083 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000011084 case OR_Success:
11085 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000011086 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000011087 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011088 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
11089 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011090 // If FoundDecl is different from Method (such as if one is a template
11091 // and the other a specialization), make sure DiagnoseUseOfDecl is
11092 // called on both.
11093 // FIXME: This would be more comprehensively addressed by modifying
11094 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
11095 // being used.
11096 if (Method != FoundDecl.getDecl() &&
11097 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
11098 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011099 break;
11100
11101 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000011102 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000011103 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011104 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011105 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011106 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011107 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011108
11109 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011110 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011111 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011113 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011114 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011115
11116 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011117 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011118 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011119 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011120 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011121 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011122 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011123 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011124 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011125 }
11126
John McCall6bb80172010-03-30 21:47:33 +000011127 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011128
John McCallaa81e162009-12-01 22:10:20 +000011129 // If overload resolution picked a static member, build a
11130 // non-member call based on that function.
11131 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011132 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11133 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011134 }
11135
John McCall129e2df2009-11-30 22:42:35 +000011136 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011137 }
11138
John McCallf89e55a2010-11-18 06:31:45 +000011139 QualType ResultType = Method->getResultType();
11140 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11141 ResultType = ResultType.getNonLValueExprType(Context);
11142
Douglas Gregor88a35142008-12-22 05:46:06 +000011143 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011144 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011145 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011146 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011147
Anders Carlssoneed3e692009-10-10 00:06:20 +000011148 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011149 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011150 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011151 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011152
Douglas Gregor88a35142008-12-22 05:46:06 +000011153 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011154 // We only need to do this if there was actually an overload; otherwise
11155 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011156 if (!Method->isStatic()) {
11157 ExprResult ObjectArg =
11158 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11159 FoundDecl, Method);
11160 if (ObjectArg.isInvalid())
11161 return ExprError();
11162 MemExpr->setBase(ObjectArg.take());
11163 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011164
11165 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011166 const FunctionProtoType *Proto =
11167 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011168 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011169 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011170 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011171
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011172 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011173
Richard Smith831421f2012-06-25 20:30:08 +000011174 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011175 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011176
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011177 if ((isa<CXXConstructorDecl>(CurContext) ||
11178 isa<CXXDestructorDecl>(CurContext)) &&
11179 TheCall->getMethodDecl()->isPure()) {
11180 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11181
Chandler Carruthae198062011-06-27 08:31:58 +000011182 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011183 Diag(MemExpr->getLocStart(),
11184 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11185 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11186 << MD->getParent()->getDeclName();
11187
11188 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011189 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011190 }
John McCall9ae2f072010-08-23 23:25:46 +000011191 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011192}
11193
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011194/// BuildCallToObjectOfClassType - Build a call to an object of class
11195/// type (C++ [over.call.object]), which can end up invoking an
11196/// overloaded function call operator (@c operator()) or performing a
11197/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011198ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011199Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011200 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011201 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011202 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011203 if (checkPlaceholderForOverload(*this, Obj))
11204 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011205 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011206
11207 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011208 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011209 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011210
John Wiegley429bb272011-04-08 18:41:53 +000011211 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11212 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011213
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011214 // C++ [over.call.object]p1:
11215 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011216 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011217 // candidate functions includes at least the function call
11218 // operators of T. The function call operators of T are obtained by
11219 // ordinary lookup of the name operator() in the context of
11220 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011221 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011222 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011223
John Wiegley429bb272011-04-08 18:41:53 +000011224 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011225 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011226 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011227
John McCalla24dc2e2009-11-17 02:14:36 +000011228 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11229 LookupQualifiedName(R, Record->getDecl());
11230 R.suppressDiagnostics();
11231
Douglas Gregor593564b2009-11-15 07:48:03 +000011232 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011233 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011234 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011235 Object.get()->Classify(Context),
11236 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011237 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011238 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011239
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011240 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011241 // In addition, for each (non-explicit in C++0x) conversion function
11242 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011243 //
11244 // operator conversion-type-id () cv-qualifier;
11245 //
11246 // where cv-qualifier is the same cv-qualification as, or a
11247 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011248 // denotes the type "pointer to function of (P1,...,Pn) returning
11249 // R", or the type "reference to pointer to function of
11250 // (P1,...,Pn) returning R", or the type "reference to function
11251 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011252 // is also considered as a candidate function. Similarly,
11253 // surrogate call functions are added to the set of candidate
11254 // functions for each conversion function declared in an
11255 // accessible base class provided the function is not hidden
11256 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011257 std::pair<CXXRecordDecl::conversion_iterator,
11258 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011259 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011260 for (CXXRecordDecl::conversion_iterator
11261 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011262 NamedDecl *D = *I;
11263 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11264 if (isa<UsingShadowDecl>(D))
11265 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011266
Douglas Gregor4a27d702009-10-21 06:18:39 +000011267 // Skip over templated conversion functions; they aren't
11268 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011269 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011270 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011271
John McCall701c89e2009-12-03 04:06:58 +000011272 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011273 if (!Conv->isExplicit()) {
11274 // Strip the reference type (if any) and then the pointer type (if
11275 // any) to get down to what might be a function type.
11276 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11277 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11278 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011279
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011280 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11281 {
11282 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011283 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011284 }
11285 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011286 }
Mike Stump1eb44332009-09-09 15:08:12 +000011287
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011288 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11289
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011290 // Perform overload resolution.
11291 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011292 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011293 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011294 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011295 // Overload resolution succeeded; we'll build the appropriate call
11296 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011297 break;
11298
11299 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011300 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011301 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011302 << Object.get()->getType() << /*call*/ 1
11303 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011304 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011305 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011306 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011307 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011308 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011309 break;
11310
11311 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011312 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011313 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011314 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011315 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011316 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011317
11318 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011319 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011320 diag::err_ovl_deleted_object_call)
11321 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011322 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011323 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011324 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011325 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011326 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011327 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011328
Douglas Gregorff331c12010-07-25 18:17:45 +000011329 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011330 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011331
John McCall5acb0c92011-10-17 18:40:02 +000011332 UnbridgedCasts.restore();
11333
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011334 if (Best->Function == 0) {
11335 // Since there is no function declaration, this is one of the
11336 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011337 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011338 = cast<CXXConversionDecl>(
11339 Best->Conversions[0].UserDefined.ConversionFunction);
11340
John Wiegley429bb272011-04-08 18:41:53 +000011341 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011342 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11343 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011344 assert(Conv == Best->FoundDecl.getDecl() &&
11345 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011346 // We selected one of the surrogate functions that converts the
11347 // object parameter to a function pointer. Perform the conversion
11348 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011349
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011350 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011351 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011352 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11353 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011354 if (Call.isInvalid())
11355 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011356 // Record usage of conversion in an implicit cast.
11357 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11358 CK_UserDefinedConversion,
11359 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011360
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011361 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011362 }
11363
John Wiegley429bb272011-04-08 18:41:53 +000011364 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011365
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011366 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11367 // that calls this method, using Object for the implicit object
11368 // parameter and passing along the remaining arguments.
11369 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011370
11371 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011372 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011373 return ExprError();
11374
Chandler Carruth6df868e2010-12-12 08:17:55 +000011375 const FunctionProtoType *Proto =
11376 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011377
11378 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011379 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011380
11381 // Build the full argument list for the method call (the
11382 // implicit object parameter is placed at the beginning of the
11383 // list).
11384 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011385 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011386 NumArgsToCheck = NumArgsInProto;
11387 MethodArgs = new Expr*[NumArgsInProto + 1];
11388 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011389 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011390 }
John Wiegley429bb272011-04-08 18:41:53 +000011391 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011392 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011393 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011394
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011395 DeclarationNameInfo OpLocInfo(
11396 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11397 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011398 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011399 HadMultipleCandidates,
11400 OpLocInfo.getLoc(),
11401 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011402 if (NewFn.isInvalid())
11403 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011404
11405 // Once we've built TheCall, all of the expressions are properly
11406 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011407 QualType ResultTy = Method->getResultType();
11408 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11409 ResultTy = ResultTy.getNonLValueExprType(Context);
11410
John McCall9ae2f072010-08-23 23:25:46 +000011411 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011412 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011413 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011414 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011415 delete [] MethodArgs;
11416
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011417 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011418 Method))
11419 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011420
Douglas Gregor518fda12009-01-13 05:10:00 +000011421 // We may have default arguments. If so, we need to allocate more
11422 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011423 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011424 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011425 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011426 NumArgsToCheck = NumArgsInProto;
11427
Chris Lattner312531a2009-04-12 08:11:20 +000011428 bool IsError = false;
11429
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011430 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011431 ExprResult ObjRes =
11432 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11433 Best->FoundDecl, Method);
11434 if (ObjRes.isInvalid())
11435 IsError = true;
11436 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011437 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011438 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011439
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011440 // Check the argument types.
11441 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011442 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011443 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011444 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011445
Douglas Gregor518fda12009-01-13 05:10:00 +000011446 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011447
John McCall60d7b3a2010-08-24 06:29:42 +000011448 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011449 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011450 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011451 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011452 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011453
Anders Carlsson3faa4862010-01-29 18:43:53 +000011454 IsError |= InputInit.isInvalid();
11455 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011456 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011457 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011458 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11459 if (DefArg.isInvalid()) {
11460 IsError = true;
11461 break;
11462 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011463
Douglas Gregord47c47d2009-11-09 19:27:57 +000011464 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011465 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011466
11467 TheCall->setArg(i + 1, Arg);
11468 }
11469
11470 // If this is a variadic call, handle args passed through "...".
11471 if (Proto->isVariadic()) {
11472 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011473 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011474 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11475 IsError |= Arg.isInvalid();
11476 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011477 }
11478 }
11479
Chris Lattner312531a2009-04-12 08:11:20 +000011480 if (IsError) return true;
11481
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011482 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011483
Richard Smith831421f2012-06-25 20:30:08 +000011484 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011485 return true;
11486
John McCall182f7092010-08-24 06:09:16 +000011487 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011488}
11489
Douglas Gregor8ba10742008-11-20 16:27:02 +000011490/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011491/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011492/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011493ExprResult
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011494Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc,
11495 bool *NoArrowOperatorFound) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011496 assert(Base->getType()->isRecordType() &&
11497 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011498
John McCall5acb0c92011-10-17 18:40:02 +000011499 if (checkPlaceholderForOverload(*this, Base))
11500 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011501
John McCall5769d612010-02-08 23:07:23 +000011502 SourceLocation Loc = Base->getExprLoc();
11503
Douglas Gregor8ba10742008-11-20 16:27:02 +000011504 // C++ [over.ref]p1:
11505 //
11506 // [...] An expression x->m is interpreted as (x.operator->())->m
11507 // for a class object x of type T if T::operator->() exists and if
11508 // the operator is selected as the best match function by the
11509 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011510 DeclarationName OpName =
11511 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011512 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011513 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011514
John McCall5769d612010-02-08 23:07:23 +000011515 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011516 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011517 return ExprError();
11518
John McCalla24dc2e2009-11-17 02:14:36 +000011519 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11520 LookupQualifiedName(R, BaseRecord->getDecl());
11521 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011522
11523 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011524 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011525 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011526 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011527 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011528
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011529 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11530
Douglas Gregor8ba10742008-11-20 16:27:02 +000011531 // Perform overload resolution.
11532 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011533 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011534 case OR_Success:
11535 // Overload resolution succeeded; we'll build the call below.
11536 break;
11537
11538 case OR_No_Viable_Function:
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011539 if (CandidateSet.empty()) {
11540 QualType BaseType = Base->getType();
Kaelyn Uhrainbaaeb852013-07-31 17:38:24 +000011541 if (NoArrowOperatorFound) {
11542 // Report this specific error to the caller instead of emitting a
11543 // diagnostic, as requested.
11544 *NoArrowOperatorFound = true;
11545 return ExprError();
11546 }
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011547 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
11548 << BaseType << Base->getSourceRange();
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011549 if (BaseType->isRecordType() && !BaseType->isPointerType()) {
Kaelyn Uhraind4224342013-07-15 19:54:54 +000011550 Diag(OpLoc, diag::note_typecheck_member_reference_suggestion)
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011551 << FixItHint::CreateReplacement(OpLoc, ".");
Kaelyn Uhrain45c3ba72013-07-11 22:38:30 +000011552 }
11553 } else
Douglas Gregor8ba10742008-11-20 16:27:02 +000011554 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011555 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011556 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011557 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011558
11559 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011560 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11561 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011562 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011563 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011564
11565 case OR_Deleted:
11566 Diag(OpLoc, diag::err_ovl_deleted_oper)
11567 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011568 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011569 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011570 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011572 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011573 }
11574
John McCall9aa472c2010-03-19 07:35:19 +000011575 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11576
Douglas Gregor8ba10742008-11-20 16:27:02 +000011577 // Convert the object parameter.
11578 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011579 ExprResult BaseResult =
11580 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11581 Best->FoundDecl, Method);
11582 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011583 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011584 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011585
Douglas Gregor8ba10742008-11-20 16:27:02 +000011586 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011587 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011588 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011589 if (FnExpr.isInvalid())
11590 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011591
John McCallf89e55a2010-11-18 06:31:45 +000011592 QualType ResultTy = Method->getResultType();
11593 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11594 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011595 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011596 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011597 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011598
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011599 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011600 Method))
11601 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011602
11603 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011604}
11605
Richard Smith36f5cfe2012-03-09 08:00:36 +000011606/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11607/// a literal operator described by the provided lookup results.
11608ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11609 DeclarationNameInfo &SuffixInfo,
11610 ArrayRef<Expr*> Args,
11611 SourceLocation LitEndLoc,
11612 TemplateArgumentListInfo *TemplateArgs) {
11613 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011614
Richard Smith36f5cfe2012-03-09 08:00:36 +000011615 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11616 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11617 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011618
Richard Smith36f5cfe2012-03-09 08:00:36 +000011619 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11620
Richard Smith36f5cfe2012-03-09 08:00:36 +000011621 // Perform overload resolution. This will usually be trivial, but might need
11622 // to perform substitutions for a literal operator template.
11623 OverloadCandidateSet::iterator Best;
11624 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11625 case OR_Success:
11626 case OR_Deleted:
11627 break;
11628
11629 case OR_No_Viable_Function:
11630 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11631 << R.getLookupName();
11632 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11633 return ExprError();
11634
11635 case OR_Ambiguous:
11636 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11637 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11638 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011639 }
11640
Richard Smith36f5cfe2012-03-09 08:00:36 +000011641 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011642 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11643 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011644 SuffixInfo.getLoc(),
11645 SuffixInfo.getInfo());
11646 if (Fn.isInvalid())
11647 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011648
11649 // Check the argument types. This should almost always be a no-op, except
11650 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011651 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011652 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011653 ExprResult InputInit = PerformCopyInitialization(
11654 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11655 SourceLocation(), Args[ArgIdx]);
11656 if (InputInit.isInvalid())
11657 return true;
11658 ConvArgs[ArgIdx] = InputInit.take();
11659 }
11660
Richard Smith9fcce652012-03-07 08:35:16 +000011661 QualType ResultTy = FD->getResultType();
11662 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11663 ResultTy = ResultTy.getNonLValueExprType(Context);
11664
Richard Smith9fcce652012-03-07 08:35:16 +000011665 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011666 new (Context) UserDefinedLiteral(Context, Fn.take(),
11667 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011668 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11669
11670 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11671 return ExprError();
11672
Richard Smith831421f2012-06-25 20:30:08 +000011673 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011674 return ExprError();
11675
11676 return MaybeBindToTemporary(UDL);
11677}
11678
Sam Panzere1715b62012-08-21 00:52:01 +000011679/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11680/// given LookupResult is non-empty, it is assumed to describe a member which
11681/// will be invoked. Otherwise, the function will be found via argument
11682/// dependent lookup.
11683/// CallExpr is set to a valid expression and FRS_Success returned on success,
11684/// otherwise CallExpr is set to ExprError() and some non-success value
11685/// is returned.
11686Sema::ForRangeStatus
11687Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11688 SourceLocation RangeLoc, VarDecl *Decl,
11689 BeginEndFunction BEF,
11690 const DeclarationNameInfo &NameInfo,
11691 LookupResult &MemberLookup,
11692 OverloadCandidateSet *CandidateSet,
11693 Expr *Range, ExprResult *CallExpr) {
11694 CandidateSet->clear();
11695 if (!MemberLookup.empty()) {
11696 ExprResult MemberRef =
11697 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11698 /*IsPtr=*/false, CXXScopeSpec(),
11699 /*TemplateKWLoc=*/SourceLocation(),
11700 /*FirstQualifierInScope=*/0,
11701 MemberLookup,
11702 /*TemplateArgs=*/0);
11703 if (MemberRef.isInvalid()) {
11704 *CallExpr = ExprError();
11705 Diag(Range->getLocStart(), diag::note_in_for_range)
11706 << RangeLoc << BEF << Range->getType();
11707 return FRS_DiagnosticIssued;
11708 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011709 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011710 if (CallExpr->isInvalid()) {
11711 *CallExpr = ExprError();
11712 Diag(Range->getLocStart(), diag::note_in_for_range)
11713 << RangeLoc << BEF << Range->getType();
11714 return FRS_DiagnosticIssued;
11715 }
11716 } else {
11717 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011718 UnresolvedLookupExpr *Fn =
11719 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11720 NestedNameSpecifierLoc(), NameInfo,
11721 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011722 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011723
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011724 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011725 CandidateSet, CallExpr);
11726 if (CandidateSet->empty() || CandidateSetError) {
11727 *CallExpr = ExprError();
11728 return FRS_NoViableFunction;
11729 }
11730 OverloadCandidateSet::iterator Best;
11731 OverloadingResult OverloadResult =
11732 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11733
11734 if (OverloadResult == OR_No_Viable_Function) {
11735 *CallExpr = ExprError();
11736 return FRS_NoViableFunction;
11737 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011738 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011739 Loc, 0, CandidateSet, &Best,
11740 OverloadResult,
11741 /*AllowTypoCorrection=*/false);
11742 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11743 *CallExpr = ExprError();
11744 Diag(Range->getLocStart(), diag::note_in_for_range)
11745 << RangeLoc << BEF << Range->getType();
11746 return FRS_DiagnosticIssued;
11747 }
11748 }
11749 return FRS_Success;
11750}
11751
11752
Douglas Gregor904eed32008-11-10 20:40:00 +000011753/// FixOverloadedFunctionReference - E is an expression that refers to
11754/// a C++ overloaded function (possibly with some parentheses and
11755/// perhaps a '&' around it). We have resolved the overloaded function
11756/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011757/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011758Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011759 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011760 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011761 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11762 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011763 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011764 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011765
Douglas Gregor699ee522009-11-20 19:42:02 +000011766 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011767 }
11768
Douglas Gregor699ee522009-11-20 19:42:02 +000011769 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011770 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11771 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011772 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011773 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011774 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011775 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011776 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011777 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011778
11779 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011780 ICE->getCastKind(),
11781 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011782 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011783 }
11784
Douglas Gregor699ee522009-11-20 19:42:02 +000011785 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011786 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011787 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011788 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11789 if (Method->isStatic()) {
11790 // Do nothing: static member functions aren't any different
11791 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011792 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011793 // Fix the sub expression, which really has to be an
11794 // UnresolvedLookupExpr holding an overloaded member function
11795 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011796 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11797 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011798 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011799 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011800
John McCallba135432009-11-21 08:51:07 +000011801 assert(isa<DeclRefExpr>(SubExpr)
11802 && "fixed to something other than a decl ref");
11803 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11804 && "fixed to a member ref with no nested name qualifier");
11805
11806 // We have taken the address of a pointer to member
11807 // function. Perform the computation here so that we get the
11808 // appropriate pointer to member type.
11809 QualType ClassType
11810 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11811 QualType MemPtrType
11812 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11813
John McCallf89e55a2010-11-18 06:31:45 +000011814 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11815 VK_RValue, OK_Ordinary,
11816 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011817 }
11818 }
John McCall6bb80172010-03-30 21:47:33 +000011819 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11820 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011821 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011822 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011823
John McCall2de56d12010-08-25 11:45:40 +000011824 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011825 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011826 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011827 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011828 }
John McCallba135432009-11-21 08:51:07 +000011829
11830 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011831 // FIXME: avoid copy.
11832 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011833 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011834 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11835 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011836 }
11837
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011838 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11839 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011840 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011841 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011842 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011843 ULE->getNameLoc(),
11844 Fn->getType(),
11845 VK_LValue,
11846 Found.getDecl(),
11847 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011848 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011849 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11850 return DRE;
John McCallba135432009-11-21 08:51:07 +000011851 }
11852
John McCall129e2df2009-11-30 22:42:35 +000011853 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011854 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011855 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11856 if (MemExpr->hasExplicitTemplateArgs()) {
11857 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11858 TemplateArgs = &TemplateArgsBuffer;
11859 }
John McCalld5532b62009-11-23 01:53:49 +000011860
John McCallaa81e162009-12-01 22:10:20 +000011861 Expr *Base;
11862
John McCallf89e55a2010-11-18 06:31:45 +000011863 // If we're filling in a static method where we used to have an
11864 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011865 if (MemExpr->isImplicitAccess()) {
11866 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011867 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11868 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011869 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011870 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011871 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011872 MemExpr->getMemberLoc(),
11873 Fn->getType(),
11874 VK_LValue,
11875 Found.getDecl(),
11876 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011877 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011878 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11879 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011880 } else {
11881 SourceLocation Loc = MemExpr->getMemberLoc();
11882 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011883 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011884 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011885 Base = new (Context) CXXThisExpr(Loc,
11886 MemExpr->getBaseType(),
11887 /*isImplicit=*/true);
11888 }
John McCallaa81e162009-12-01 22:10:20 +000011889 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011890 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011891
John McCallf5307512011-04-27 00:36:17 +000011892 ExprValueKind valueKind;
11893 QualType type;
11894 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11895 valueKind = VK_LValue;
11896 type = Fn->getType();
11897 } else {
11898 valueKind = VK_RValue;
11899 type = Context.BoundMemberTy;
11900 }
11901
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011902 MemberExpr *ME = MemberExpr::Create(Context, Base,
11903 MemExpr->isArrow(),
11904 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011905 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011906 Fn,
11907 Found,
11908 MemExpr->getMemberNameInfo(),
11909 TemplateArgs,
11910 type, valueKind, OK_Ordinary);
11911 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011912 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011913 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011914 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011915
John McCall3fa5cae2010-10-26 07:05:15 +000011916 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011917}
11918
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011919ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011920 DeclAccessPair Found,
11921 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011922 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011923}
11924
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011925} // end namespace clang