blob: d4d08b4bff8d86af81a7b4e78adc5608ce8be850 [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();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000512 switch (ConversionKind) {
513 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000514 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515 Standard.DebugPrint();
516 break;
517 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000518 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 UserDefined.DebugPrint();
520 break;
521 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000522 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523 break;
John McCall1d318332010-01-12 00:44:57 +0000524 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000525 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000526 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000528 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529 break;
530 }
531
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000532 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533}
534
John McCall1d318332010-01-12 00:44:57 +0000535void AmbiguousConversionSequence::construct() {
536 new (&conversions()) ConversionSet();
537}
538
539void AmbiguousConversionSequence::destruct() {
540 conversions().~ConversionSet();
541}
542
543void
544AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
545 FromTypePtr = O.FromTypePtr;
546 ToTypePtr = O.ToTypePtr;
547 new (&conversions()) ConversionSet(O.conversions());
548}
549
Douglas Gregora9333192010-05-08 17:41:32 +0000550namespace {
551 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000552 // template argument information.
553 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000554 TemplateArgument FirstArg;
555 TemplateArgument SecondArg;
556 };
Richard Smith29805ca2013-01-31 05:19:49 +0000557 // Structure used by OverloadCandidate::DeductionFailureInfo to store
558 // template parameter and template argument information.
559 struct DFIParamWithArguments : DFIArguments {
560 TemplateParameter Param;
561 };
Douglas Gregora9333192010-05-08 17:41:32 +0000562}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000563
Douglas Gregora9333192010-05-08 17:41:32 +0000564/// \brief Convert from Sema's representation of template deduction information
565/// to the form used in overload-candidate information.
566OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000567static MakeDeductionFailureInfo(ASTContext &Context,
568 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000569 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000570 OverloadCandidate::DeductionFailureInfo Result;
571 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000572 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000573 Result.Data = 0;
574 switch (TDK) {
575 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000576 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000577 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000578 case Sema::TDK_TooManyArguments:
579 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000580 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000581
Douglas Gregora9333192010-05-08 17:41:32 +0000582 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000583 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000584 Result.Data = Info.Param.getOpaqueValue();
585 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000586
Richard Smith29805ca2013-01-31 05:19:49 +0000587 case Sema::TDK_NonDeducedMismatch: {
588 // FIXME: Should allocate from normal heap so that we can free this later.
589 DFIArguments *Saved = new (Context) DFIArguments;
590 Saved->FirstArg = Info.FirstArg;
591 Saved->SecondArg = Info.SecondArg;
592 Result.Data = Saved;
593 break;
594 }
595
Douglas Gregora9333192010-05-08 17:41:32 +0000596 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000597 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000598 // FIXME: Should allocate from normal heap so that we can free this later.
599 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000600 Saved->Param = Info.Param;
601 Saved->FirstArg = Info.FirstArg;
602 Saved->SecondArg = Info.SecondArg;
603 Result.Data = Saved;
604 break;
605 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000606
Douglas Gregora9333192010-05-08 17:41:32 +0000607 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000608 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000609 if (Info.hasSFINAEDiagnostic()) {
610 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
611 SourceLocation(), PartialDiagnostic::NullDiagnostic());
612 Info.takeSFINAEDiagnostic(*Diag);
613 Result.HasDiagnostic = true;
614 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000615 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000616
Douglas Gregora9333192010-05-08 17:41:32 +0000617 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000618 Result.Data = Info.Expression;
619 break;
620
Richard Smith29805ca2013-01-31 05:19:49 +0000621 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000622 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000623 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregora9333192010-05-08 17:41:32 +0000625 return Result;
626}
John McCall1d318332010-01-12 00:44:57 +0000627
Douglas Gregora9333192010-05-08 17:41:32 +0000628void OverloadCandidate::DeductionFailureInfo::Destroy() {
629 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
630 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000631 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000632 case Sema::TDK_InstantiationDepth:
633 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000634 case Sema::TDK_TooManyArguments:
635 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000636 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000637 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000638 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639
Douglas Gregora9333192010-05-08 17:41:32 +0000640 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000641 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000642 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000643 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000644 Data = 0;
645 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000646
647 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000648 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000649 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000650 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
651 Diag->~PartialDiagnosticAt();
652 HasDiagnostic = false;
653 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000654 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000655
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000656 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000657 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000658 break;
659 }
660}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000661
Richard Smithb8590f32012-05-07 09:03:25 +0000662PartialDiagnosticAt *
663OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
664 if (HasDiagnostic)
665 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
666 return 0;
667}
668
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000669TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000670OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
671 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
672 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000673 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000674 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000675 case Sema::TDK_TooManyArguments:
676 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000677 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000678 case Sema::TDK_NonDeducedMismatch:
679 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000680 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000681
Douglas Gregora9333192010-05-08 17:41:32 +0000682 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000683 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000685
686 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000687 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000688 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000689
Douglas Gregora9333192010-05-08 17:41:32 +0000690 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000691 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000692 break;
693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000694
Douglas Gregora9333192010-05-08 17:41:32 +0000695 return TemplateParameter();
696}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000697
Douglas Gregorec20f462010-05-08 20:07:26 +0000698TemplateArgumentList *
699OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
700 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000701 case Sema::TDK_Success:
702 case Sema::TDK_Invalid:
703 case Sema::TDK_InstantiationDepth:
704 case Sema::TDK_TooManyArguments:
705 case Sema::TDK_TooFewArguments:
706 case Sema::TDK_Incomplete:
707 case Sema::TDK_InvalidExplicitArguments:
708 case Sema::TDK_Inconsistent:
709 case Sema::TDK_Underqualified:
710 case Sema::TDK_NonDeducedMismatch:
711 case Sema::TDK_FailedOverloadResolution:
712 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000713
Richard Smith29805ca2013-01-31 05:19:49 +0000714 case Sema::TDK_SubstitutionFailure:
715 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716
Richard Smith29805ca2013-01-31 05:19:49 +0000717 // Unhandled
718 case Sema::TDK_MiscellaneousDeductionFailure:
719 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000720 }
721
722 return 0;
723}
724
Douglas Gregora9333192010-05-08 17:41:32 +0000725const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
726 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
727 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000728 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 case Sema::TDK_InstantiationDepth:
730 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000731 case Sema::TDK_TooManyArguments:
732 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000733 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000734 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000735 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000736 return 0;
737
Douglas Gregora9333192010-05-08 17:41:32 +0000738 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000739 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000740 case Sema::TDK_NonDeducedMismatch:
741 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000742
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000743 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000744 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000745 break;
746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000747
Douglas Gregora9333192010-05-08 17:41:32 +0000748 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000749}
Douglas Gregora9333192010-05-08 17:41:32 +0000750
751const TemplateArgument *
752OverloadCandidate::DeductionFailureInfo::getSecondArg() {
753 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
754 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000755 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000756 case Sema::TDK_InstantiationDepth:
757 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000758 case Sema::TDK_TooManyArguments:
759 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000760 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000761 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000762 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000763 return 0;
764
Douglas Gregora9333192010-05-08 17:41:32 +0000765 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000766 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000767 case Sema::TDK_NonDeducedMismatch:
768 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000769
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000770 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000771 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000772 break;
773 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000774
Douglas Gregora9333192010-05-08 17:41:32 +0000775 return 0;
776}
777
Richard Smith0efa62f2013-01-31 04:03:12 +0000778Expr *
779OverloadCandidate::DeductionFailureInfo::getExpr() {
780 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
781 Sema::TDK_FailedOverloadResolution)
782 return static_cast<Expr*>(Data);
783
784 return 0;
785}
786
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000787void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000788 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000789 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
790 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000791 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
792 i->DeductionFailure.Destroy();
793 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000794}
795
796void OverloadCandidateSet::clear() {
797 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000798 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000799 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000800 Functions.clear();
801}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000802
John McCall5acb0c92011-10-17 18:40:02 +0000803namespace {
804 class UnbridgedCastsSet {
805 struct Entry {
806 Expr **Addr;
807 Expr *Saved;
808 };
809 SmallVector<Entry, 2> Entries;
810
811 public:
812 void save(Sema &S, Expr *&E) {
813 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
814 Entry entry = { &E, E };
815 Entries.push_back(entry);
816 E = S.stripARCUnbridgedCast(E);
817 }
818
819 void restore() {
820 for (SmallVectorImpl<Entry>::iterator
821 i = Entries.begin(), e = Entries.end(); i != e; ++i)
822 *i->Addr = i->Saved;
823 }
824 };
825}
826
827/// checkPlaceholderForOverload - Do any interesting placeholder-like
828/// preprocessing on the given expression.
829///
830/// \param unbridgedCasts a collection to which to add unbridged casts;
831/// without this, they will be immediately diagnosed as errors
832///
833/// Return true on unrecoverable error.
834static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
835 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000836 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
837 // We can't handle overloaded expressions here because overload
838 // resolution might reasonably tweak them.
839 if (placeholder->getKind() == BuiltinType::Overload) return false;
840
841 // If the context potentially accepts unbridged ARC casts, strip
842 // the unbridged cast and add it to the collection for later restoration.
843 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
844 unbridgedCasts) {
845 unbridgedCasts->save(S, E);
846 return false;
847 }
848
849 // Go ahead and check everything else.
850 ExprResult result = S.CheckPlaceholderExpr(E);
851 if (result.isInvalid())
852 return true;
853
854 E = result.take();
855 return false;
856 }
857
858 // Nothing to do.
859 return false;
860}
861
862/// checkArgPlaceholdersForOverload - Check a set of call operands for
863/// placeholders.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000864static bool checkArgPlaceholdersForOverload(Sema &S,
865 MultiExprArg Args,
John McCall5acb0c92011-10-17 18:40:02 +0000866 UnbridgedCastsSet &unbridged) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +0000867 for (unsigned i = 0, e = Args.size(); i != e; ++i)
868 if (checkPlaceholderForOverload(S, Args[i], &unbridged))
John McCall5acb0c92011-10-17 18:40:02 +0000869 return true;
870
871 return false;
872}
873
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000874// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000875// overload of the declarations in Old. This routine returns false if
876// New and Old cannot be overloaded, e.g., if New has the same
877// signature as some function in Old (C++ 1.3.10) or if the Old
878// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000879// it does return false, MatchedDecl will point to the decl that New
880// cannot be overloaded with. This decl may be a UsingShadowDecl on
881// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000882//
883// Example: Given the following input:
884//
885// void f(int, float); // #1
886// void f(int, int); // #2
887// int f(int, int); // #3
888//
889// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000890// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000891//
John McCall51fa86f2009-12-02 08:47:38 +0000892// When we process #2, Old contains only the FunctionDecl for #1. By
893// comparing the parameter types, we see that #1 and #2 are overloaded
894// (since they have different signatures), so this routine returns
895// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000896//
John McCall51fa86f2009-12-02 08:47:38 +0000897// When we process #3, Old is an overload set containing #1 and #2. We
898// compare the signatures of #3 to #1 (they're overloaded, so we do
899// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
900// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000901// signature), IsOverload returns false and MatchedDecl will be set to
902// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000903//
904// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
905// into a class by a using declaration. The rules for whether to hide
906// shadow declarations ignore some properties which otherwise figure
907// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000908Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000909Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
910 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000911 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000912 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000913 NamedDecl *OldD = *I;
914
915 bool OldIsUsingDecl = false;
916 if (isa<UsingShadowDecl>(OldD)) {
917 OldIsUsingDecl = true;
918
919 // We can always introduce two using declarations into the same
920 // context, even if they have identical signatures.
921 if (NewIsUsingDecl) continue;
922
923 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
924 }
925
926 // If either declaration was introduced by a using declaration,
927 // we'll need to use slightly different rules for matching.
928 // Essentially, these rules are the normal rules, except that
929 // function templates hide function templates with different
930 // return types or template parameter lists.
931 bool UseMemberUsingDeclRules =
John McCall78037ac2013-04-03 21:19:47 +0000932 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord() &&
933 !New->getFriendObjectKind();
John McCallad00b772010-06-16 08:42:20 +0000934
John McCall51fa86f2009-12-02 08:47:38 +0000935 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000936 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
937 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
938 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
939 continue;
940 }
941
John McCall871b2e72009-12-09 03:35:25 +0000942 Match = *I;
943 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000944 }
John McCall51fa86f2009-12-02 08:47:38 +0000945 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000946 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
947 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
948 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
949 continue;
950 }
951
Rafael Espindola90cc3902013-04-15 12:49:13 +0000952 if (!shouldLinkPossiblyHiddenDecl(*I, New))
953 continue;
954
John McCall871b2e72009-12-09 03:35:25 +0000955 Match = *I;
956 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000957 }
John McCalld7945c62010-11-10 03:01:53 +0000958 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000959 // We can overload with these, which can show up when doing
960 // redeclaration checks for UsingDecls.
961 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000962 } else if (isa<TagDecl>(OldD)) {
963 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000964 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
965 // Optimistically assume that an unresolved using decl will
966 // overload; if it doesn't, we'll have to diagnose during
967 // template instantiation.
968 } else {
John McCall68263142009-11-18 22:49:29 +0000969 // (C++ 13p1):
970 // Only function declarations can be overloaded; object and type
971 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000972 Match = *I;
973 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000974 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000975 }
John McCall68263142009-11-18 22:49:29 +0000976
John McCall871b2e72009-12-09 03:35:25 +0000977 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000978}
979
Rafael Espindola78eeba82012-12-28 14:21:58 +0000980static bool canBeOverloaded(const FunctionDecl &D) {
981 if (D.getAttr<OverloadableAttr>())
982 return true;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000983 if (D.isExternC())
Rafael Espindola78eeba82012-12-28 14:21:58 +0000984 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000985
986 // Main cannot be overloaded (basic.start.main).
987 if (D.isMain())
988 return false;
989
Rafael Espindola78eeba82012-12-28 14:21:58 +0000990 return true;
991}
992
Rafael Espindola2d1b0962013-03-14 03:07:35 +0000993static bool shouldTryToOverload(Sema &S, FunctionDecl *New, FunctionDecl *Old,
994 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000995 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
996 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
997
998 // C++ [temp.fct]p2:
999 // A function template can be overloaded with other function templates
1000 // and with normal (non-template) functions.
1001 if ((OldTemplate == 0) != (NewTemplate == 0))
1002 return true;
1003
1004 // Is the function New an overload of the function Old?
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001005 QualType OldQType = S.Context.getCanonicalType(Old->getType());
1006 QualType NewQType = S.Context.getCanonicalType(New->getType());
John McCall68263142009-11-18 22:49:29 +00001007
1008 // Compare the signatures (C++ 1.3.10) of the two functions to
1009 // determine whether they are overloads. If we find any mismatch
1010 // in the signature, they are overloads.
1011
1012 // If either of these functions is a K&R-style function (no
1013 // prototype), then we consider them to have matching signatures.
1014 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1015 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1016 return false;
1017
John McCallf4c73712011-01-19 06:33:43 +00001018 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1019 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001020
1021 // The signature of a function includes the types of its
1022 // parameters (C++ 1.3.10), which includes the presence or absence
1023 // of the ellipsis; see C++ DR 357).
1024 if (OldQType != NewQType &&
1025 (OldType->getNumArgs() != NewType->getNumArgs() ||
1026 OldType->isVariadic() != NewType->isVariadic() ||
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001027 !S.FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001028 return true;
1029
1030 // C++ [temp.over.link]p4:
1031 // The signature of a function template consists of its function
1032 // signature, its return type and its template parameter list. The names
1033 // of the template parameters are significant only for establishing the
1034 // relationship between the template parameters and the rest of the
1035 // signature.
1036 //
1037 // We check the return type and template parameter lists for function
1038 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001039 //
1040 // However, we don't consider either of these when deciding whether
1041 // a member introduced by a shadow declaration is hidden.
1042 if (!UseUsingDeclRules && NewTemplate &&
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001043 (!S.TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1044 OldTemplate->getTemplateParameters(),
1045 false, S.TPL_TemplateMatch) ||
John McCall68263142009-11-18 22:49:29 +00001046 OldType->getResultType() != NewType->getResultType()))
1047 return true;
1048
1049 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001050 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001051 //
1052 // As part of this, also check whether one of the member functions
1053 // is static, in which case they are not overloads (C++
1054 // 13.1p2). While not part of the definition of the signature,
1055 // this check is important to determine whether these functions
1056 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001057 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1058 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001059 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001060 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1061 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1062 if (!UseUsingDeclRules &&
1063 (OldMethod->getRefQualifier() == RQ_None ||
1064 NewMethod->getRefQualifier() == RQ_None)) {
1065 // C++0x [over.load]p2:
1066 // - Member function declarations with the same name and the same
1067 // parameter-type-list as well as member function template
1068 // declarations with the same name, the same parameter-type-list, and
1069 // the same template parameter lists cannot be overloaded if any of
1070 // them, but not all, have a ref-qualifier (8.3.5).
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001071 S.Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
Richard Smith21c8fa82013-01-14 05:37:29 +00001072 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001073 S.Diag(OldMethod->getLocation(), diag::note_previous_declaration);
Richard Smith21c8fa82013-01-14 05:37:29 +00001074 }
1075 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001076 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001077
Richard Smith21c8fa82013-01-14 05:37:29 +00001078 // We may not have applied the implicit const for a constexpr member
1079 // function yet (because we haven't yet resolved whether this is a static
1080 // or non-static member function). Add it now, on the assumption that this
1081 // is a redeclaration of OldMethod.
1082 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smithdb2fe732013-06-25 18:46:26 +00001083 if (!S.getLangOpts().CPlusPlus1y && NewMethod->isConstexpr() &&
1084 !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001085 NewQuals |= Qualifiers::Const;
1086 if (OldMethod->getTypeQualifiers() != NewQuals)
1087 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001088 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001089
John McCall68263142009-11-18 22:49:29 +00001090 // The signatures match; this is not an overload.
1091 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001092}
1093
Rafael Espindola2d1b0962013-03-14 03:07:35 +00001094bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
1095 bool UseUsingDeclRules) {
1096 if (!shouldTryToOverload(*this, New, Old, UseUsingDeclRules))
1097 return false;
1098
1099 // If both of the functions are extern "C", then they are not
1100 // overloads.
1101 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
1102 return false;
1103
1104 return true;
1105}
1106
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001107/// \brief Checks availability of the function depending on the current
1108/// function context. Inside an unavailable function, unavailability is ignored.
1109///
1110/// \returns true if \arg FD is unavailable and current context is inside
1111/// an available function, false otherwise.
1112bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1113 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1114}
1115
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001116/// \brief Tries a user-defined conversion from From to ToType.
1117///
1118/// Produces an implicit conversion sequence for when a standard conversion
1119/// is not an option. See TryImplicitConversion for more information.
1120static ImplicitConversionSequence
1121TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1122 bool SuppressUserConversions,
1123 bool AllowExplicit,
1124 bool InOverloadResolution,
1125 bool CStyle,
1126 bool AllowObjCWritebackConversion) {
1127 ImplicitConversionSequence ICS;
1128
1129 if (SuppressUserConversions) {
1130 // We're not in the case above, so there is no conversion that
1131 // we can perform.
1132 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1133 return ICS;
1134 }
1135
1136 // Attempt user-defined conversion.
1137 OverloadCandidateSet Conversions(From->getExprLoc());
1138 OverloadingResult UserDefResult
1139 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1140 AllowExplicit);
1141
1142 if (UserDefResult == OR_Success) {
1143 ICS.setUserDefined();
1144 // C++ [over.ics.user]p4:
1145 // A conversion of an expression of class type to the same class
1146 // type is given Exact Match rank, and a conversion of an
1147 // expression of class type to a base class of that type is
1148 // given Conversion rank, in spite of the fact that a copy
1149 // constructor (i.e., a user-defined conversion function) is
1150 // called for those cases.
1151 if (CXXConstructorDecl *Constructor
1152 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1153 QualType FromCanon
1154 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1155 QualType ToCanon
1156 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1157 if (Constructor->isCopyConstructor() &&
1158 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1159 // Turn this into a "standard" conversion sequence, so that it
1160 // gets ranked with standard conversion sequences.
1161 ICS.setStandard();
1162 ICS.Standard.setAsIdentityConversion();
1163 ICS.Standard.setFromType(From->getType());
1164 ICS.Standard.setAllToTypes(ToType);
1165 ICS.Standard.CopyConstructor = Constructor;
1166 if (ToCanon != FromCanon)
1167 ICS.Standard.Second = ICK_Derived_To_Base;
1168 }
1169 }
1170
1171 // C++ [over.best.ics]p4:
1172 // However, when considering the argument of a user-defined
1173 // conversion function that is a candidate by 13.3.1.3 when
1174 // invoked for the copying of the temporary in the second step
1175 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1176 // 13.3.1.6 in all cases, only standard conversion sequences and
1177 // ellipsis conversion sequences are allowed.
1178 if (SuppressUserConversions && ICS.isUserDefined()) {
1179 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1180 }
1181 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1182 ICS.setAmbiguous();
1183 ICS.Ambiguous.setFromType(From->getType());
1184 ICS.Ambiguous.setToType(ToType);
1185 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1186 Cand != Conversions.end(); ++Cand)
1187 if (Cand->Viable)
1188 ICS.Ambiguous.addConversion(Cand->Function);
1189 } else {
1190 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1191 }
1192
1193 return ICS;
1194}
1195
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001196/// TryImplicitConversion - Attempt to perform an implicit conversion
1197/// from the given expression (Expr) to the given type (ToType). This
1198/// function returns an implicit conversion sequence that can be used
1199/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001200///
1201/// void f(float f);
1202/// void g(int i) { f(i); }
1203///
1204/// this routine would produce an implicit conversion sequence to
1205/// describe the initialization of f from i, which will be a standard
1206/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1207/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1208//
1209/// Note that this routine only determines how the conversion can be
1210/// performed; it does not actually perform the conversion. As such,
1211/// it will not produce any diagnostics if no conversion is available,
1212/// but will instead return an implicit conversion sequence of kind
1213/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001214///
1215/// If @p SuppressUserConversions, then user-defined conversions are
1216/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001217/// If @p AllowExplicit, then explicit user-defined conversions are
1218/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001219///
1220/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1221/// writeback conversion, which allows __autoreleasing id* parameters to
1222/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001223static ImplicitConversionSequence
1224TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1225 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001226 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001227 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001228 bool CStyle,
1229 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001230 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001231 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001232 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001233 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001234 return ICS;
1235 }
1236
David Blaikie4e4d0842012-03-11 07:00:24 +00001237 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001238 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001239 return ICS;
1240 }
1241
Douglas Gregor604eb652010-08-11 02:15:33 +00001242 // C++ [over.ics.user]p4:
1243 // A conversion of an expression of class type to the same class
1244 // type is given Exact Match rank, and a conversion of an
1245 // expression of class type to a base class of that type is
1246 // given Conversion rank, in spite of the fact that a copy/move
1247 // constructor (i.e., a user-defined conversion function) is
1248 // called for those cases.
1249 QualType FromType = From->getType();
1250 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001251 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1252 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001253 ICS.setStandard();
1254 ICS.Standard.setAsIdentityConversion();
1255 ICS.Standard.setFromType(FromType);
1256 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001257
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001258 // We don't actually check at this point whether there is a valid
1259 // copy/move constructor, since overloading just assumes that it
1260 // exists. When we actually perform initialization, we'll find the
1261 // appropriate constructor to copy the returned object, if needed.
1262 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001263
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001264 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001265 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001266 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001267
Douglas Gregor604eb652010-08-11 02:15:33 +00001268 return ICS;
1269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001270
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001271 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1272 AllowExplicit, InOverloadResolution, CStyle,
1273 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001274}
1275
John McCallf85e1932011-06-15 23:02:42 +00001276ImplicitConversionSequence
1277Sema::TryImplicitConversion(Expr *From, QualType ToType,
1278 bool SuppressUserConversions,
1279 bool AllowExplicit,
1280 bool InOverloadResolution,
1281 bool CStyle,
1282 bool AllowObjCWritebackConversion) {
1283 return clang::TryImplicitConversion(*this, From, ToType,
1284 SuppressUserConversions, AllowExplicit,
1285 InOverloadResolution, CStyle,
1286 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001287}
1288
Douglas Gregor575c63a2010-04-16 22:27:05 +00001289/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001290/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001291/// converted expression. Flavor is the kind of conversion we're
1292/// performing, used in the error message. If @p AllowExplicit,
1293/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001294ExprResult
1295Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001296 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001297 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001298 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001299}
1300
John Wiegley429bb272011-04-08 18:41:53 +00001301ExprResult
1302Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001303 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001304 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001305 if (checkPlaceholderForOverload(*this, From))
1306 return ExprError();
1307
John McCallf85e1932011-06-15 23:02:42 +00001308 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1309 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001310 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001311 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001312
John McCall120d63c2010-08-24 20:38:10 +00001313 ICS = clang::TryImplicitConversion(*this, From, ToType,
1314 /*SuppressUserConversions=*/false,
1315 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001316 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001317 /*CStyle=*/false,
1318 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001319 return PerformImplicitConversion(From, ToType, ICS, Action);
1320}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001321
1322/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001323/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001324bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1325 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001326 if (Context.hasSameUnqualifiedType(FromType, ToType))
1327 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001328
John McCall00ccbef2010-12-21 00:44:39 +00001329 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1330 // where F adds one of the following at most once:
1331 // - a pointer
1332 // - a member pointer
1333 // - a block pointer
1334 CanQualType CanTo = Context.getCanonicalType(ToType);
1335 CanQualType CanFrom = Context.getCanonicalType(FromType);
1336 Type::TypeClass TyClass = CanTo->getTypeClass();
1337 if (TyClass != CanFrom->getTypeClass()) return false;
1338 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1339 if (TyClass == Type::Pointer) {
1340 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1341 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1342 } else if (TyClass == Type::BlockPointer) {
1343 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1344 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1345 } else if (TyClass == Type::MemberPointer) {
1346 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1347 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1348 } else {
1349 return false;
1350 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001351
John McCall00ccbef2010-12-21 00:44:39 +00001352 TyClass = CanTo->getTypeClass();
1353 if (TyClass != CanFrom->getTypeClass()) return false;
1354 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1355 return false;
1356 }
1357
1358 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1359 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1360 if (!EInfo.getNoReturn()) return false;
1361
1362 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1363 assert(QualType(FromFn, 0).isCanonical());
1364 if (QualType(FromFn, 0) != CanTo) return false;
1365
1366 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001367 return true;
1368}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001369
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001370/// \brief Determine whether the conversion from FromType to ToType is a valid
1371/// vector conversion.
1372///
1373/// \param ICK Will be set to the vector conversion kind, if this is a vector
1374/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001375static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1376 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001377 // We need at least one of these types to be a vector type to have a vector
1378 // conversion.
1379 if (!ToType->isVectorType() && !FromType->isVectorType())
1380 return false;
1381
1382 // Identical types require no conversions.
1383 if (Context.hasSameUnqualifiedType(FromType, ToType))
1384 return false;
1385
1386 // There are no conversions between extended vector types, only identity.
1387 if (ToType->isExtVectorType()) {
1388 // There are no conversions between extended vector types other than the
1389 // identity conversion.
1390 if (FromType->isExtVectorType())
1391 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001392
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001393 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001394 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001395 ICK = ICK_Vector_Splat;
1396 return true;
1397 }
1398 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001399
1400 // We can perform the conversion between vector types in the following cases:
1401 // 1)vector types are equivalent AltiVec and GCC vector types
1402 // 2)lax vector conversions are permitted and the vector types are of the
1403 // same size
1404 if (ToType->isVectorType() && FromType->isVectorType()) {
1405 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001406 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001407 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001408 ICK = ICK_Vector_Conversion;
1409 return true;
1410 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001411 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001412
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001413 return false;
1414}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001415
Douglas Gregor7d000652012-04-12 20:48:09 +00001416static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1417 bool InOverloadResolution,
1418 StandardConversionSequence &SCS,
1419 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001420
Douglas Gregor60d62c22008-10-31 16:23:19 +00001421/// IsStandardConversion - Determines whether there is a standard
1422/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1423/// expression From to the type ToType. Standard conversion sequences
1424/// only consider non-class types; for conversions that involve class
1425/// types, use TryImplicitConversion. If a conversion exists, SCS will
1426/// contain the standard conversion sequence required to perform this
1427/// conversion and this routine will return true. Otherwise, this
1428/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001429static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1430 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001431 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001432 bool CStyle,
1433 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001434 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001435
Douglas Gregor60d62c22008-10-31 16:23:19 +00001436 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001437 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001438 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001439 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001440 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001441 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442
Douglas Gregorf9201e02009-02-11 23:02:49 +00001443 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001444 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001445 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001446 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001447 return false;
1448
Mike Stump1eb44332009-09-09 15:08:12 +00001449 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001450 }
1451
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001452 // The first conversion can be an lvalue-to-rvalue conversion,
1453 // array-to-pointer conversion, or function-to-pointer conversion
1454 // (C++ 4p1).
1455
John McCall120d63c2010-08-24 20:38:10 +00001456 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001457 DeclAccessPair AccessPair;
1458 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001459 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001460 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001461 // We were able to resolve the address of the overloaded function,
1462 // so we can convert to the type of that function.
1463 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001464
1465 // we can sometimes resolve &foo<int> regardless of ToType, so check
1466 // if the type matches (identity) or we are converting to bool
1467 if (!S.Context.hasSameUnqualifiedType(
1468 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1469 QualType resultTy;
1470 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001471 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001472 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1473 // otherwise, only a boolean conversion is standard
1474 if (!ToType->isBooleanType())
1475 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001476 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001477
Chandler Carruth90434232011-03-29 08:08:18 +00001478 // Check if the "from" expression is taking the address of an overloaded
1479 // function and recompute the FromType accordingly. Take advantage of the
1480 // fact that non-static member functions *must* have such an address-of
1481 // expression.
1482 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1483 if (Method && !Method->isStatic()) {
1484 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1485 "Non-unary operator on non-static member address");
1486 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1487 == UO_AddrOf &&
1488 "Non-address-of operator on non-static member address");
1489 const Type *ClassType
1490 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1491 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001492 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1493 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1494 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001495 "Non-address-of operator for overloaded function expression");
1496 FromType = S.Context.getPointerType(FromType);
1497 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001498
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001499 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001500 assert(S.Context.hasSameType(
1501 FromType,
1502 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001503 } else {
1504 return false;
1505 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001506 }
John McCall21480112011-08-30 00:57:29 +00001507 // Lvalue-to-rvalue conversion (C++11 4.1):
1508 // A glvalue (3.10) of a non-function, non-array type T can
1509 // be converted to a prvalue.
1510 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001511 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001512 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001513 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001514 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001515
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001516 // C11 6.3.2.1p2:
1517 // ... if the lvalue has atomic type, the value has the non-atomic version
1518 // of the type of the lvalue ...
1519 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1520 FromType = Atomic->getValueType();
1521
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001522 // If T is a non-class type, the type of the rvalue is the
1523 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001524 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1525 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001526 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001527 } else if (FromType->isArrayType()) {
1528 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001529 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001530
1531 // An lvalue or rvalue of type "array of N T" or "array of unknown
1532 // bound of T" can be converted to an rvalue of type "pointer to
1533 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001534 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001535
John McCall120d63c2010-08-24 20:38:10 +00001536 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001537 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001538 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539
1540 // For the purpose of ranking in overload resolution
1541 // (13.3.3.1.1), this conversion is considered an
1542 // array-to-pointer conversion followed by a qualification
1543 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001544 SCS.Second = ICK_Identity;
1545 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001546 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001547 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001548 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001549 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001550 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001551 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001552 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553
1554 // An lvalue of function type T can be converted to an rvalue of
1555 // type "pointer to T." The result is a pointer to the
1556 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001557 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001558 } else {
1559 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001560 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001561 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001562 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001563
1564 // The second conversion can be an integral promotion, floating
1565 // point promotion, integral conversion, floating point conversion,
1566 // floating-integral conversion, pointer conversion,
1567 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001568 // For overloading in C, this can also be a "compatible-type"
1569 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001570 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001571 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001572 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001573 // The unqualified versions of the types are the same: there's no
1574 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001575 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001576 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001577 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001578 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001579 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001580 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001581 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001582 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001583 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001584 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001585 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001586 SCS.Second = ICK_Complex_Promotion;
1587 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001588 } else if (ToType->isBooleanType() &&
1589 (FromType->isArithmeticType() ||
1590 FromType->isAnyPointerType() ||
1591 FromType->isBlockPointerType() ||
1592 FromType->isMemberPointerType() ||
1593 FromType->isNullPtrType())) {
1594 // Boolean conversions (C++ 4.12).
1595 SCS.Second = ICK_Boolean_Conversion;
1596 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001597 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001598 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001599 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001600 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001601 FromType = ToType.getUnqualifiedType();
Richard Smith42860f12013-05-10 20:29:50 +00001602 } else if (FromType->isAnyComplexType() && ToType->isAnyComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001603 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001604 SCS.Second = ICK_Complex_Conversion;
1605 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001606 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1607 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001608 // Complex-real conversions (C99 6.3.1.7)
1609 SCS.Second = ICK_Complex_Real;
1610 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001611 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001612 // Floating point conversions (C++ 4.8).
1613 SCS.Second = ICK_Floating_Conversion;
1614 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001615 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001616 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001617 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001618 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001619 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001620 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001621 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001622 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001623 SCS.Second = ICK_Block_Pointer_Conversion;
1624 } else if (AllowObjCWritebackConversion &&
1625 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1626 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001627 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1628 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001629 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001630 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001631 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001632 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001634 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001635 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001636 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001637 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001638 SCS.Second = SecondICK;
1639 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001640 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001641 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001642 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001643 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001644 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001645 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001646 // Treat a conversion that strips "noreturn" as an identity conversion.
1647 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001648 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1649 InOverloadResolution,
1650 SCS, CStyle)) {
1651 SCS.Second = ICK_TransparentUnionConversion;
1652 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001653 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1654 CStyle)) {
1655 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001656 // appropriately.
1657 return true;
Guy Benyei6959acd2013-02-07 16:05:33 +00001658 } else if (ToType->isEventT() &&
1659 From->isIntegerConstantExpr(S.getASTContext()) &&
1660 (From->EvaluateKnownConstInt(S.getASTContext()) == 0)) {
1661 SCS.Second = ICK_Zero_Event_Conversion;
1662 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001663 } else {
1664 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001665 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001666 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001667 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001668
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001669 QualType CanonFrom;
1670 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001671 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001672 bool ObjCLifetimeConversion;
1673 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1674 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001675 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001676 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001677 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001678 CanonFrom = S.Context.getCanonicalType(FromType);
1679 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001680 } else {
1681 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001682 SCS.Third = ICK_Identity;
1683
Mike Stump1eb44332009-09-09 15:08:12 +00001684 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001685 // [...] Any difference in top-level cv-qualification is
1686 // subsumed by the initialization itself and does not constitute
1687 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001688 CanonFrom = S.Context.getCanonicalType(FromType);
1689 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001690 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001691 == CanonTo.getLocalUnqualifiedType() &&
Matt Arsenault5509f372013-02-26 21:15:54 +00001692 CanonFrom.getLocalQualifiers() != CanonTo.getLocalQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001693 FromType = ToType;
1694 CanonFrom = CanonTo;
1695 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001696 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001697 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001698
1699 // If we have not converted the argument type to the parameter type,
1700 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001701 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001702 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001703
Douglas Gregor60d62c22008-10-31 16:23:19 +00001704 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001705}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001706
1707static bool
1708IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1709 QualType &ToType,
1710 bool InOverloadResolution,
1711 StandardConversionSequence &SCS,
1712 bool CStyle) {
1713
1714 const RecordType *UT = ToType->getAsUnionType();
1715 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1716 return false;
1717 // The field to initialize within the transparent union.
1718 RecordDecl *UD = UT->getDecl();
1719 // It's compatible if the expression matches any of the fields.
1720 for (RecordDecl::field_iterator it = UD->field_begin(),
1721 itend = UD->field_end();
1722 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001723 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1724 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001725 ToType = it->getType();
1726 return true;
1727 }
1728 }
1729 return false;
1730}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001731
1732/// IsIntegralPromotion - Determines whether the conversion from the
1733/// expression From (whose potentially-adjusted type is FromType) to
1734/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1735/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001736bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001737 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001738 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001739 if (!To) {
1740 return false;
1741 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001742
1743 // An rvalue of type char, signed char, unsigned char, short int, or
1744 // unsigned short int can be converted to an rvalue of type int if
1745 // int can represent all the values of the source type; otherwise,
1746 // the source rvalue can be converted to an rvalue of type unsigned
1747 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001748 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1749 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001750 if (// We can promote any signed, promotable integer type to an int
1751 (FromType->isSignedIntegerType() ||
1752 // We can promote any unsigned integer type whose size is
1753 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001754 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001755 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001756 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001757 }
1758
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001759 return To->getKind() == BuiltinType::UInt;
1760 }
1761
Richard Smithe7ff9192012-09-13 21:18:54 +00001762 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001763 // A prvalue of an unscoped enumeration type whose underlying type is not
1764 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1765 // following types that can represent all the values of the enumeration
1766 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1767 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001768 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001769 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001770 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001771 // with lowest integer conversion rank (4.13) greater than the rank of long
1772 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001773 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001774 // C++11 [conv.prom]p4:
1775 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1776 // can be converted to a prvalue of its underlying type. Moreover, if
1777 // integral promotion can be applied to its underlying type, a prvalue of an
1778 // unscoped enumeration type whose underlying type is fixed can also be
1779 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001780 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1781 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1782 // provided for a scoped enumeration.
1783 if (FromEnumType->getDecl()->isScoped())
1784 return false;
1785
Richard Smithe7ff9192012-09-13 21:18:54 +00001786 // We can perform an integral promotion to the underlying type of the enum,
1787 // even if that's not the promoted type.
1788 if (FromEnumType->getDecl()->isFixed()) {
1789 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1790 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1791 IsIntegralPromotion(From, Underlying, ToType);
1792 }
1793
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001794 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001795 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001796 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001797 return Context.hasSameUnqualifiedType(ToType,
1798 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001799 }
John McCall842aef82009-12-09 09:09:27 +00001800
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001801 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001802 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1803 // to an rvalue a prvalue of the first of the following types that can
1804 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001805 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001806 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001807 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001808 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001809 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001810 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001811 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001812 // Determine whether the type we're converting from is signed or
1813 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001814 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001815 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001816
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001817 // The types we'll try to promote to, in the appropriate
1818 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001819 QualType PromoteTypes[6] = {
1820 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001821 Context.LongTy, Context.UnsignedLongTy ,
1822 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001823 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001824 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001825 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1826 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001827 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001828 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1829 // We found the type that we can promote to. If this is the
1830 // type we wanted, we have a promotion. Otherwise, no
1831 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001832 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001833 }
1834 }
1835 }
1836
1837 // An rvalue for an integral bit-field (9.6) can be converted to an
1838 // rvalue of type int if int can represent all the values of the
1839 // bit-field; otherwise, it can be converted to unsigned int if
1840 // unsigned int can represent all the values of the bit-field. If
1841 // the bit-field is larger yet, no integral promotion applies to
1842 // it. If the bit-field has an enumerated type, it is treated as any
1843 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001844 // FIXME: We should delay checking of bit-fields until we actually perform the
1845 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001846 using llvm::APSInt;
1847 if (From)
John McCall993f43f2013-05-06 21:39:12 +00001848 if (FieldDecl *MemberDecl = From->getSourceBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001849 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001850 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001851 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1852 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1853 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001854
Douglas Gregor86f19402008-12-20 23:49:58 +00001855 // Are we promoting to an int from a bitfield that fits in an int?
1856 if (BitWidth < ToSize ||
1857 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1858 return To->getKind() == BuiltinType::Int;
1859 }
Mike Stump1eb44332009-09-09 15:08:12 +00001860
Douglas Gregor86f19402008-12-20 23:49:58 +00001861 // Are we promoting to an unsigned int from an unsigned bitfield
1862 // that fits into an unsigned int?
1863 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1864 return To->getKind() == BuiltinType::UInt;
1865 }
Mike Stump1eb44332009-09-09 15:08:12 +00001866
Douglas Gregor86f19402008-12-20 23:49:58 +00001867 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001868 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001869 }
Mike Stump1eb44332009-09-09 15:08:12 +00001870
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001871 // An rvalue of type bool can be converted to an rvalue of type int,
1872 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001873 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001874 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001875 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001876
1877 return false;
1878}
1879
1880/// IsFloatingPointPromotion - Determines whether the conversion from
1881/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1882/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001883bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001884 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1885 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001886 /// An rvalue of type float can be converted to an rvalue of type
1887 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001888 if (FromBuiltin->getKind() == BuiltinType::Float &&
1889 ToBuiltin->getKind() == BuiltinType::Double)
1890 return true;
1891
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001892 // C99 6.3.1.5p1:
1893 // When a float is promoted to double or long double, or a
1894 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001895 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001896 (FromBuiltin->getKind() == BuiltinType::Float ||
1897 FromBuiltin->getKind() == BuiltinType::Double) &&
1898 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1899 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001900
1901 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001902 if (!getLangOpts().NativeHalfType &&
1903 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001904 ToBuiltin->getKind() == BuiltinType::Float)
1905 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001906 }
1907
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001908 return false;
1909}
1910
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001911/// \brief Determine if a conversion is a complex promotion.
1912///
1913/// A complex promotion is defined as a complex -> complex conversion
1914/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001915/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001916bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001917 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001918 if (!FromComplex)
1919 return false;
1920
John McCall183700f2009-09-21 23:43:11 +00001921 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001922 if (!ToComplex)
1923 return false;
1924
1925 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001926 ToComplex->getElementType()) ||
1927 IsIntegralPromotion(0, FromComplex->getElementType(),
1928 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001929}
1930
Douglas Gregorcb7de522008-11-26 23:31:11 +00001931/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1932/// the pointer type FromPtr to a pointer to type ToPointee, with the
1933/// same type qualifiers as FromPtr has on its pointee type. ToType,
1934/// if non-empty, will be a pointer to ToType that may or may not have
1935/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001936///
Mike Stump1eb44332009-09-09 15:08:12 +00001937static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001938BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001939 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001940 ASTContext &Context,
1941 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001942 assert((FromPtr->getTypeClass() == Type::Pointer ||
1943 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1944 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001945
John McCallf85e1932011-06-15 23:02:42 +00001946 /// Conversions to 'id' subsume cv-qualifier conversions.
1947 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001948 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001949
1950 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001951 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001952 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001953 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001954
John McCallf85e1932011-06-15 23:02:42 +00001955 if (StripObjCLifetime)
1956 Quals.removeObjCLifetime();
1957
Mike Stump1eb44332009-09-09 15:08:12 +00001958 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001959 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001960 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001961 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001962 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001963
1964 // Build a pointer to ToPointee. It has the right qualifiers
1965 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001966 if (isa<ObjCObjectPointerType>(ToType))
1967 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001968 return Context.getPointerType(ToPointee);
1969 }
1970
1971 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001972 QualType QualifiedCanonToPointee
1973 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001974
Douglas Gregorda80f742010-12-01 21:43:58 +00001975 if (isa<ObjCObjectPointerType>(ToType))
1976 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1977 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001978}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001979
Mike Stump1eb44332009-09-09 15:08:12 +00001980static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001981 bool InOverloadResolution,
1982 ASTContext &Context) {
1983 // Handle value-dependent integral null pointer constants correctly.
1984 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1985 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001986 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001987 return !InOverloadResolution;
1988
Douglas Gregorce940492009-09-25 04:25:58 +00001989 return Expr->isNullPointerConstant(Context,
1990 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1991 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001992}
Mike Stump1eb44332009-09-09 15:08:12 +00001993
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001994/// IsPointerConversion - Determines whether the conversion of the
1995/// expression From, which has the (possibly adjusted) type FromType,
1996/// can be converted to the type ToType via a pointer conversion (C++
1997/// 4.10). If so, returns true and places the converted type (that
1998/// might differ from ToType in its cv-qualifiers at some level) into
1999/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002000///
Douglas Gregor7ca09762008-11-27 01:19:21 +00002001/// This routine also supports conversions to and from block pointers
2002/// and conversions with Objective-C's 'id', 'id<protocols...>', and
2003/// pointers to interfaces. FIXME: Once we've determined the
2004/// appropriate overloading rules for Objective-C, we may want to
2005/// split the Objective-C checks into a different routine; however,
2006/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00002007/// conversions, so for now they live here. IncompatibleObjC will be
2008/// set if the conversion is an allowed Objective-C conversion that
2009/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002010bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00002011 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00002012 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00002013 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00002014 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00002015 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
2016 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00002017 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00002018
Mike Stump1eb44332009-09-09 15:08:12 +00002019 // Conversion from a null pointer constant to any Objective-C pointer type.
2020 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002021 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00002022 ConvertedType = ToType;
2023 return true;
2024 }
2025
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002026 // Blocks: Block pointers can be converted to void*.
2027 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00002028 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002029 ConvertedType = ToType;
2030 return true;
2031 }
2032 // Blocks: A null pointer constant can be converted to a block
2033 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002034 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002035 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002036 ConvertedType = ToType;
2037 return true;
2038 }
2039
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002040 // If the left-hand-side is nullptr_t, the right side can be a null
2041 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002042 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002043 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002044 ConvertedType = ToType;
2045 return true;
2046 }
2047
Ted Kremenek6217b802009-07-29 21:53:49 +00002048 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002049 if (!ToTypePtr)
2050 return false;
2051
2052 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002053 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002054 ConvertedType = ToType;
2055 return true;
2056 }
Sebastian Redl07779722008-10-31 14:43:28 +00002057
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002058 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002059 // , including objective-c pointers.
2060 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002061 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002062 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002063 ConvertedType = BuildSimilarlyQualifiedPointerType(
2064 FromType->getAs<ObjCObjectPointerType>(),
2065 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002066 ToType, Context);
2067 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002068 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002069 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002070 if (!FromTypePtr)
2071 return false;
2072
2073 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002074
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002075 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002076 // pointer conversion, so don't do all of the work below.
2077 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2078 return false;
2079
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002080 // An rvalue of type "pointer to cv T," where T is an object type,
2081 // can be converted to an rvalue of type "pointer to cv void" (C++
2082 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002083 if (FromPointeeType->isIncompleteOrObjectType() &&
2084 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002085 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002086 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002087 ToType, Context,
2088 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002089 return true;
2090 }
2091
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002092 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002093 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002094 ToPointeeType->isVoidType()) {
2095 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2096 ToPointeeType,
2097 ToType, Context);
2098 return true;
2099 }
2100
Douglas Gregorf9201e02009-02-11 23:02:49 +00002101 // When we're overloading in C, we allow a special kind of pointer
2102 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002103 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002104 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002105 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002106 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002107 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002108 return true;
2109 }
2110
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002111 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002112 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002113 // An rvalue of type "pointer to cv D," where D is a class type,
2114 // can be converted to an rvalue of type "pointer to cv B," where
2115 // B is a base class (clause 10) of D. If B is an inaccessible
2116 // (clause 11) or ambiguous (10.2) base class of D, a program that
2117 // necessitates this conversion is ill-formed. The result of the
2118 // conversion is a pointer to the base class sub-object of the
2119 // derived class object. The null pointer value is converted to
2120 // the null pointer value of the destination type.
2121 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002122 // Note that we do not check for ambiguity or inaccessibility
2123 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002124 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002125 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002126 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002127 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002128 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002129 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002130 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002131 ToType, Context);
2132 return true;
2133 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002134
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002135 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2136 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2137 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2138 ToPointeeType,
2139 ToType, Context);
2140 return true;
2141 }
2142
Douglas Gregorc7887512008-12-19 19:13:09 +00002143 return false;
2144}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002145
2146/// \brief Adopt the given qualifiers for the given type.
2147static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2148 Qualifiers TQs = T.getQualifiers();
2149
2150 // Check whether qualifiers already match.
2151 if (TQs == Qs)
2152 return T;
2153
2154 if (Qs.compatiblyIncludes(TQs))
2155 return Context.getQualifiedType(T, Qs);
2156
2157 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2158}
Douglas Gregorc7887512008-12-19 19:13:09 +00002159
2160/// isObjCPointerConversion - Determines whether this is an
2161/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2162/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002163bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002164 QualType& ConvertedType,
2165 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002166 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002167 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002168
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002169 // The set of qualifiers on the type we're converting from.
2170 Qualifiers FromQualifiers = FromType.getQualifiers();
2171
Steve Naroff14108da2009-07-10 23:34:53 +00002172 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002173 const ObjCObjectPointerType* ToObjCPtr =
2174 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002175 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002176 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002177
Steve Naroff14108da2009-07-10 23:34:53 +00002178 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002179 // If the pointee types are the same (ignoring qualifications),
2180 // then this is not a pointer conversion.
2181 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2182 FromObjCPtr->getPointeeType()))
2183 return false;
2184
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002185 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002186 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002187 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002188 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002189 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002190 return true;
2191 }
2192 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002193 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002194 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002195 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002196 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002197 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002198 return true;
2199 }
2200 // Objective C++: We're able to convert from a pointer to an
2201 // interface to a pointer to a different interface.
2202 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002203 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2204 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002205 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002206 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2207 FromObjCPtr->getPointeeType()))
2208 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002209 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002210 ToObjCPtr->getPointeeType(),
2211 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002212 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002213 return true;
2214 }
2215
2216 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2217 // Okay: this is some kind of implicit downcast of Objective-C
2218 // interfaces, which is permitted. However, we're going to
2219 // complain about it.
2220 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002221 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002222 ToObjCPtr->getPointeeType(),
2223 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002224 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002225 return true;
2226 }
Mike Stump1eb44332009-09-09 15:08:12 +00002227 }
Steve Naroff14108da2009-07-10 23:34:53 +00002228 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002229 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002230 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002231 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002232 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002233 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002234 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002235 // to a block pointer type.
2236 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002237 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002238 return true;
2239 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002240 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002242 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002243 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002244 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002245 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002246 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002247 return true;
2248 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002249 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002250 return false;
2251
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002252 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002253 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002254 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002255 else if (const BlockPointerType *FromBlockPtr =
2256 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002257 FromPointeeType = FromBlockPtr->getPointeeType();
2258 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002259 return false;
2260
Douglas Gregorc7887512008-12-19 19:13:09 +00002261 // If we have pointers to pointers, recursively check whether this
2262 // is an Objective-C conversion.
2263 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2264 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2265 IncompatibleObjC)) {
2266 // We always complain about this conversion.
2267 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002268 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002269 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002270 return true;
2271 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002272 // Allow conversion of pointee being objective-c pointer to another one;
2273 // as in I* to id.
2274 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2275 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2276 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2277 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002278
Douglas Gregorda80f742010-12-01 21:43:58 +00002279 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002280 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002281 return true;
2282 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002283
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002284 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002285 // differences in the argument and result types are in Objective-C
2286 // pointer conversions. If so, we permit the conversion (but
2287 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002288 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002289 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002290 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002291 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002292 if (FromFunctionType && ToFunctionType) {
2293 // If the function types are exactly the same, this isn't an
2294 // Objective-C pointer conversion.
2295 if (Context.getCanonicalType(FromPointeeType)
2296 == Context.getCanonicalType(ToPointeeType))
2297 return false;
2298
2299 // Perform the quick checks that will tell us whether these
2300 // function types are obviously different.
2301 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2302 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2303 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2304 return false;
2305
2306 bool HasObjCConversion = false;
2307 if (Context.getCanonicalType(FromFunctionType->getResultType())
2308 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2309 // Okay, the types match exactly. Nothing to do.
2310 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2311 ToFunctionType->getResultType(),
2312 ConvertedType, IncompatibleObjC)) {
2313 // Okay, we have an Objective-C pointer conversion.
2314 HasObjCConversion = true;
2315 } else {
2316 // Function types are too different. Abort.
2317 return false;
2318 }
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Douglas Gregorc7887512008-12-19 19:13:09 +00002320 // Check argument types.
2321 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2322 ArgIdx != NumArgs; ++ArgIdx) {
2323 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2324 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2325 if (Context.getCanonicalType(FromArgType)
2326 == Context.getCanonicalType(ToArgType)) {
2327 // Okay, the types match exactly. Nothing to do.
2328 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2329 ConvertedType, IncompatibleObjC)) {
2330 // Okay, we have an Objective-C pointer conversion.
2331 HasObjCConversion = true;
2332 } else {
2333 // Argument types are too different. Abort.
2334 return false;
2335 }
2336 }
2337
2338 if (HasObjCConversion) {
2339 // We had an Objective-C conversion. Allow this pointer
2340 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002341 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002342 IncompatibleObjC = true;
2343 return true;
2344 }
2345 }
2346
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002347 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002348}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002349
John McCallf85e1932011-06-15 23:02:42 +00002350/// \brief Determine whether this is an Objective-C writeback conversion,
2351/// used for parameter passing when performing automatic reference counting.
2352///
2353/// \param FromType The type we're converting form.
2354///
2355/// \param ToType The type we're converting to.
2356///
2357/// \param ConvertedType The type that will be produced after applying
2358/// this conversion.
2359bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2360 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002361 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002362 Context.hasSameUnqualifiedType(FromType, ToType))
2363 return false;
2364
2365 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2366 QualType ToPointee;
2367 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2368 ToPointee = ToPointer->getPointeeType();
2369 else
2370 return false;
2371
2372 Qualifiers ToQuals = ToPointee.getQualifiers();
2373 if (!ToPointee->isObjCLifetimeType() ||
2374 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002375 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002376 return false;
2377
2378 // Argument must be a pointer to __strong to __weak.
2379 QualType FromPointee;
2380 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2381 FromPointee = FromPointer->getPointeeType();
2382 else
2383 return false;
2384
2385 Qualifiers FromQuals = FromPointee.getQualifiers();
2386 if (!FromPointee->isObjCLifetimeType() ||
2387 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2388 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2389 return false;
2390
2391 // Make sure that we have compatible qualifiers.
2392 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2393 if (!ToQuals.compatiblyIncludes(FromQuals))
2394 return false;
2395
2396 // Remove qualifiers from the pointee type we're converting from; they
2397 // aren't used in the compatibility check belong, and we'll be adding back
2398 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2399 FromPointee = FromPointee.getUnqualifiedType();
2400
2401 // The unqualified form of the pointee types must be compatible.
2402 ToPointee = ToPointee.getUnqualifiedType();
2403 bool IncompatibleObjC;
2404 if (Context.typesAreCompatible(FromPointee, ToPointee))
2405 FromPointee = ToPointee;
2406 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2407 IncompatibleObjC))
2408 return false;
2409
2410 /// \brief Construct the type we're converting to, which is a pointer to
2411 /// __autoreleasing pointee.
2412 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2413 ConvertedType = Context.getPointerType(FromPointee);
2414 return true;
2415}
2416
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002417bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2418 QualType& ConvertedType) {
2419 QualType ToPointeeType;
2420 if (const BlockPointerType *ToBlockPtr =
2421 ToType->getAs<BlockPointerType>())
2422 ToPointeeType = ToBlockPtr->getPointeeType();
2423 else
2424 return false;
2425
2426 QualType FromPointeeType;
2427 if (const BlockPointerType *FromBlockPtr =
2428 FromType->getAs<BlockPointerType>())
2429 FromPointeeType = FromBlockPtr->getPointeeType();
2430 else
2431 return false;
2432 // We have pointer to blocks, check whether the only
2433 // differences in the argument and result types are in Objective-C
2434 // pointer conversions. If so, we permit the conversion.
2435
2436 const FunctionProtoType *FromFunctionType
2437 = FromPointeeType->getAs<FunctionProtoType>();
2438 const FunctionProtoType *ToFunctionType
2439 = ToPointeeType->getAs<FunctionProtoType>();
2440
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002441 if (!FromFunctionType || !ToFunctionType)
2442 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002443
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002444 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002445 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002446
2447 // Perform the quick checks that will tell us whether these
2448 // function types are obviously different.
2449 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2450 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2451 return false;
2452
2453 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2454 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2455 if (FromEInfo != ToEInfo)
2456 return false;
2457
2458 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002459 if (Context.hasSameType(FromFunctionType->getResultType(),
2460 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002461 // Okay, the types match exactly. Nothing to do.
2462 } else {
2463 QualType RHS = FromFunctionType->getResultType();
2464 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002465 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002466 !RHS.hasQualifiers() && LHS.hasQualifiers())
2467 LHS = LHS.getUnqualifiedType();
2468
2469 if (Context.hasSameType(RHS,LHS)) {
2470 // OK exact match.
2471 } else if (isObjCPointerConversion(RHS, LHS,
2472 ConvertedType, IncompatibleObjC)) {
2473 if (IncompatibleObjC)
2474 return false;
2475 // Okay, we have an Objective-C pointer conversion.
2476 }
2477 else
2478 return false;
2479 }
2480
2481 // Check argument types.
2482 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2483 ArgIdx != NumArgs; ++ArgIdx) {
2484 IncompatibleObjC = false;
2485 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2486 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2487 if (Context.hasSameType(FromArgType, ToArgType)) {
2488 // Okay, the types match exactly. Nothing to do.
2489 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2490 ConvertedType, IncompatibleObjC)) {
2491 if (IncompatibleObjC)
2492 return false;
2493 // Okay, we have an Objective-C pointer conversion.
2494 } else
2495 // Argument types are too different. Abort.
2496 return false;
2497 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002498 if (LangOpts.ObjCAutoRefCount &&
2499 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2500 ToFunctionType))
2501 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002502
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002503 ConvertedType = ToType;
2504 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002505}
2506
Richard Trieu6efd4c52011-11-23 22:32:32 +00002507enum {
2508 ft_default,
2509 ft_different_class,
2510 ft_parameter_arity,
2511 ft_parameter_mismatch,
2512 ft_return_type,
2513 ft_qualifer_mismatch
2514};
2515
2516/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2517/// function types. Catches different number of parameter, mismatch in
2518/// parameter types, and different return types.
2519void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2520 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002521 // If either type is not valid, include no extra info.
2522 if (FromType.isNull() || ToType.isNull()) {
2523 PDiag << ft_default;
2524 return;
2525 }
2526
Richard Trieu6efd4c52011-11-23 22:32:32 +00002527 // Get the function type from the pointers.
2528 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2529 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2530 *ToMember = ToType->getAs<MemberPointerType>();
2531 if (FromMember->getClass() != ToMember->getClass()) {
2532 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2533 << QualType(FromMember->getClass(), 0);
2534 return;
2535 }
2536 FromType = FromMember->getPointeeType();
2537 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002538 }
2539
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002540 if (FromType->isPointerType())
2541 FromType = FromType->getPointeeType();
2542 if (ToType->isPointerType())
2543 ToType = ToType->getPointeeType();
2544
2545 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002546 FromType = FromType.getNonReferenceType();
2547 ToType = ToType.getNonReferenceType();
2548
Richard Trieu6efd4c52011-11-23 22:32:32 +00002549 // Don't print extra info for non-specialized template functions.
2550 if (FromType->isInstantiationDependentType() &&
2551 !FromType->getAs<TemplateSpecializationType>()) {
2552 PDiag << ft_default;
2553 return;
2554 }
2555
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002556 // No extra info for same types.
2557 if (Context.hasSameType(FromType, ToType)) {
2558 PDiag << ft_default;
2559 return;
2560 }
2561
Richard Trieu6efd4c52011-11-23 22:32:32 +00002562 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2563 *ToFunction = ToType->getAs<FunctionProtoType>();
2564
2565 // Both types need to be function types.
2566 if (!FromFunction || !ToFunction) {
2567 PDiag << ft_default;
2568 return;
2569 }
2570
2571 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2572 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2573 << FromFunction->getNumArgs();
2574 return;
2575 }
2576
2577 // Handle different parameter types.
2578 unsigned ArgPos;
2579 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2580 PDiag << ft_parameter_mismatch << ArgPos + 1
2581 << ToFunction->getArgType(ArgPos)
2582 << FromFunction->getArgType(ArgPos);
2583 return;
2584 }
2585
2586 // Handle different return type.
2587 if (!Context.hasSameType(FromFunction->getResultType(),
2588 ToFunction->getResultType())) {
2589 PDiag << ft_return_type << ToFunction->getResultType()
2590 << FromFunction->getResultType();
2591 return;
2592 }
2593
2594 unsigned FromQuals = FromFunction->getTypeQuals(),
2595 ToQuals = ToFunction->getTypeQuals();
2596 if (FromQuals != ToQuals) {
2597 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2598 return;
2599 }
2600
2601 // Unable to find a difference, so add no extra info.
2602 PDiag << ft_default;
2603}
2604
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002605/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002606/// for equality of their argument types. Caller has already checked that
Eli Friedman06017002013-06-18 22:41:37 +00002607/// they have same number of arguments. If the parameters are different,
2608/// ArgPos will have the parameter index of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002609bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002610 const FunctionProtoType *NewType,
2611 unsigned *ArgPos) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002612 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2613 N = NewType->arg_type_begin(),
2614 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
Eli Friedman06017002013-06-18 22:41:37 +00002615 if (!Context.hasSameType(*O, *N)) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002616 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002617 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002618 }
2619 }
2620 return true;
2621}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002622
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002623/// CheckPointerConversion - Check the pointer conversion from the
2624/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002625/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002626/// conversions for which IsPointerConversion has already returned
2627/// true. It returns true and produces a diagnostic if there was an
2628/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002629bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002630 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002631 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002632 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002633 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002634 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002635
John McCalldaa8e4e2010-11-15 09:13:47 +00002636 Kind = CK_BitCast;
2637
David Blaikie50800fc2012-08-08 17:33:31 +00002638 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2639 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2640 Expr::NPCK_ZeroExpression) {
2641 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2642 DiagRuntimeBehavior(From->getExprLoc(), From,
2643 PDiag(diag::warn_impcast_bool_to_null_pointer)
2644 << ToType << From->getSourceRange());
2645 else if (!isUnevaluatedContext())
2646 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2647 << ToType << From->getSourceRange();
2648 }
John McCall1d9b3b22011-09-09 05:25:32 +00002649 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2650 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002651 QualType FromPointeeType = FromPtrType->getPointeeType(),
2652 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002653
Douglas Gregor5fccd362010-03-03 23:55:11 +00002654 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2655 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002656 // We must have a derived-to-base conversion. Check an
2657 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002658 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2659 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002660 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002661 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002662 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002663
Anders Carlsson61faec12009-09-12 04:46:44 +00002664 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002665 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002666 }
2667 }
John McCall1d9b3b22011-09-09 05:25:32 +00002668 } else if (const ObjCObjectPointerType *ToPtrType =
2669 ToType->getAs<ObjCObjectPointerType>()) {
2670 if (const ObjCObjectPointerType *FromPtrType =
2671 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002672 // Objective-C++ conversions are always okay.
2673 // FIXME: We should have a different class of conversions for the
2674 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002675 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002676 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002677 } else if (FromType->isBlockPointerType()) {
2678 Kind = CK_BlockPointerToObjCPointerCast;
2679 } else {
2680 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002681 }
John McCall1d9b3b22011-09-09 05:25:32 +00002682 } else if (ToType->isBlockPointerType()) {
2683 if (!FromType->isBlockPointerType())
2684 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002685 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002686
2687 // We shouldn't fall into this case unless it's valid for other
2688 // reasons.
2689 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2690 Kind = CK_NullToPointer;
2691
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002692 return false;
2693}
2694
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002695/// IsMemberPointerConversion - Determines whether the conversion of the
2696/// expression From, which has the (possibly adjusted) type FromType, can be
2697/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2698/// If so, returns true and places the converted type (that might differ from
2699/// ToType in its cv-qualifiers at some level) into ConvertedType.
2700bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002701 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002702 bool InOverloadResolution,
2703 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002704 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002705 if (!ToTypePtr)
2706 return false;
2707
2708 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002709 if (From->isNullPointerConstant(Context,
2710 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2711 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002712 ConvertedType = ToType;
2713 return true;
2714 }
2715
2716 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002717 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002718 if (!FromTypePtr)
2719 return false;
2720
2721 // A pointer to member of B can be converted to a pointer to member of D,
2722 // where D is derived from B (C++ 4.11p2).
2723 QualType FromClass(FromTypePtr->getClass(), 0);
2724 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002725
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002726 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002727 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002728 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002729 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2730 ToClass.getTypePtr());
2731 return true;
2732 }
2733
2734 return false;
2735}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002736
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002737/// CheckMemberPointerConversion - Check the member pointer conversion from the
2738/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002739/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002740/// for which IsMemberPointerConversion has already returned true. It returns
2741/// true and produces a diagnostic if there was an error, or returns false
2742/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002743bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002744 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002745 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002746 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002747 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002748 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002749 if (!FromPtrType) {
2750 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002751 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002752 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002753 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002754 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002755 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002756 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002757
Ted Kremenek6217b802009-07-29 21:53:49 +00002758 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002759 assert(ToPtrType && "No member pointer cast has a target type "
2760 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002761
Sebastian Redl21593ac2009-01-28 18:33:18 +00002762 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2763 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002764
Sebastian Redl21593ac2009-01-28 18:33:18 +00002765 // FIXME: What about dependent types?
2766 assert(FromClass->isRecordType() && "Pointer into non-class.");
2767 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002768
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002769 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002770 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002771 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2772 assert(DerivationOkay &&
2773 "Should not have been called if derivation isn't OK.");
2774 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002775
Sebastian Redl21593ac2009-01-28 18:33:18 +00002776 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2777 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002778 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2779 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2780 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2781 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002782 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002783
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002784 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002785 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2786 << FromClass << ToClass << QualType(VBase, 0)
2787 << From->getSourceRange();
2788 return true;
2789 }
2790
John McCall6b2accb2010-02-10 09:31:12 +00002791 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002792 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2793 Paths.front(),
2794 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002795
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002796 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002797 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002798 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002799 return false;
2800}
2801
Douglas Gregor98cd5992008-10-21 23:43:52 +00002802/// IsQualificationConversion - Determines whether the conversion from
2803/// an rvalue of type FromType to ToType is a qualification conversion
2804/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002805///
2806/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2807/// when the qualification conversion involves a change in the Objective-C
2808/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002809bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002810Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002811 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002812 FromType = Context.getCanonicalType(FromType);
2813 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002814 ObjCLifetimeConversion = false;
2815
Douglas Gregor98cd5992008-10-21 23:43:52 +00002816 // If FromType and ToType are the same type, this is not a
2817 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002818 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002819 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002820
Douglas Gregor98cd5992008-10-21 23:43:52 +00002821 // (C++ 4.4p4):
2822 // A conversion can add cv-qualifiers at levels other than the first
2823 // in multi-level pointers, subject to the following rules: [...]
2824 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002825 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002826 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002827 // Within each iteration of the loop, we check the qualifiers to
2828 // determine if this still looks like a qualification
2829 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002830 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002831 // until there are no more pointers or pointers-to-members left to
2832 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002833 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002834
Douglas Gregor621c92a2011-04-25 18:40:17 +00002835 Qualifiers FromQuals = FromType.getQualifiers();
2836 Qualifiers ToQuals = ToType.getQualifiers();
2837
John McCallf85e1932011-06-15 23:02:42 +00002838 // Objective-C ARC:
2839 // Check Objective-C lifetime conversions.
2840 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2841 UnwrappedAnyPointer) {
2842 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2843 ObjCLifetimeConversion = true;
2844 FromQuals.removeObjCLifetime();
2845 ToQuals.removeObjCLifetime();
2846 } else {
2847 // Qualification conversions cannot cast between different
2848 // Objective-C lifetime qualifiers.
2849 return false;
2850 }
2851 }
2852
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002853 // Allow addition/removal of GC attributes but not changing GC attributes.
2854 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2855 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2856 FromQuals.removeObjCGCAttr();
2857 ToQuals.removeObjCGCAttr();
2858 }
2859
Douglas Gregor98cd5992008-10-21 23:43:52 +00002860 // -- for every j > 0, if const is in cv 1,j then const is in cv
2861 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002862 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002863 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002864
Douglas Gregor98cd5992008-10-21 23:43:52 +00002865 // -- if the cv 1,j and cv 2,j are different, then const is in
2866 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002867 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002868 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002869 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002870
Douglas Gregor98cd5992008-10-21 23:43:52 +00002871 // Keep track of whether all prior cv-qualifiers in the "to" type
2872 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002873 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002874 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002875 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002876
2877 // We are left with FromType and ToType being the pointee types
2878 // after unwrapping the original FromType and ToType the same number
2879 // of types. If we unwrapped any pointers, and if FromType and
2880 // ToType have the same unqualified type (since we checked
2881 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002882 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002883}
2884
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002885/// \brief - Determine whether this is a conversion from a scalar type to an
2886/// atomic type.
2887///
2888/// If successful, updates \c SCS's second and third steps in the conversion
2889/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002890static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2891 bool InOverloadResolution,
2892 StandardConversionSequence &SCS,
2893 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002894 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2895 if (!ToAtomic)
2896 return false;
2897
2898 StandardConversionSequence InnerSCS;
2899 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2900 InOverloadResolution, InnerSCS,
2901 CStyle, /*AllowObjCWritebackConversion=*/false))
2902 return false;
2903
2904 SCS.Second = InnerSCS.Second;
2905 SCS.setToType(1, InnerSCS.getToType(1));
2906 SCS.Third = InnerSCS.Third;
2907 SCS.QualificationIncludesObjCLifetime
2908 = InnerSCS.QualificationIncludesObjCLifetime;
2909 SCS.setToType(2, InnerSCS.getToType(2));
2910 return true;
2911}
2912
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002913static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2914 CXXConstructorDecl *Constructor,
2915 QualType Type) {
2916 const FunctionProtoType *CtorType =
2917 Constructor->getType()->getAs<FunctionProtoType>();
2918 if (CtorType->getNumArgs() > 0) {
2919 QualType FirstArg = CtorType->getArgType(0);
2920 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2921 return true;
2922 }
2923 return false;
2924}
2925
Sebastian Redl56a04282012-02-11 23:51:08 +00002926static OverloadingResult
2927IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2928 CXXRecordDecl *To,
2929 UserDefinedConversionSequence &User,
2930 OverloadCandidateSet &CandidateSet,
2931 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002932 DeclContext::lookup_result R = S.LookupConstructors(To);
2933 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002934 Con != ConEnd; ++Con) {
2935 NamedDecl *D = *Con;
2936 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2937
2938 // Find the constructor (which may be a template).
2939 CXXConstructorDecl *Constructor = 0;
2940 FunctionTemplateDecl *ConstructorTmpl
2941 = dyn_cast<FunctionTemplateDecl>(D);
2942 if (ConstructorTmpl)
2943 Constructor
2944 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2945 else
2946 Constructor = cast<CXXConstructorDecl>(D);
2947
2948 bool Usable = !Constructor->isInvalidDecl() &&
2949 S.isInitListConstructor(Constructor) &&
2950 (AllowExplicit || !Constructor->isExplicit());
2951 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002952 // If the first argument is (a reference to) the target type,
2953 // suppress conversions.
2954 bool SuppressUserConversions =
2955 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002956 if (ConstructorTmpl)
2957 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2958 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002959 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002960 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002961 else
2962 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002963 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002964 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002965 }
2966 }
2967
2968 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2969
2970 OverloadCandidateSet::iterator Best;
2971 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2972 case OR_Success: {
2973 // Record the standard conversion we used and the conversion function.
2974 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002975 QualType ThisType = Constructor->getThisType(S.Context);
2976 // Initializer lists don't have conversions as such.
2977 User.Before.setAsIdentityConversion();
2978 User.HadMultipleCandidates = HadMultipleCandidates;
2979 User.ConversionFunction = Constructor;
2980 User.FoundConversionFunction = Best->FoundDecl;
2981 User.After.setAsIdentityConversion();
2982 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2983 User.After.setAllToTypes(ToType);
2984 return OR_Success;
2985 }
2986
2987 case OR_No_Viable_Function:
2988 return OR_No_Viable_Function;
2989 case OR_Deleted:
2990 return OR_Deleted;
2991 case OR_Ambiguous:
2992 return OR_Ambiguous;
2993 }
2994
2995 llvm_unreachable("Invalid OverloadResult!");
2996}
2997
Douglas Gregor734d9862009-01-30 23:27:23 +00002998/// Determines whether there is a user-defined conversion sequence
2999/// (C++ [over.ics.user]) that converts expression From to the type
3000/// ToType. If such a conversion exists, User will contain the
3001/// user-defined conversion sequence that performs such a conversion
3002/// and this routine will return true. Otherwise, this routine returns
3003/// false and User is unspecified.
3004///
Douglas Gregor734d9862009-01-30 23:27:23 +00003005/// \param AllowExplicit true if the conversion should consider C++0x
3006/// "explicit" conversion functions as well as non-explicit conversion
3007/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003008static OverloadingResult
3009IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003010 UserDefinedConversionSequence &User,
3011 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003012 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003013 // Whether we will only visit constructors.
3014 bool ConstructorsOnly = false;
3015
3016 // If the type we are conversion to is a class type, enumerate its
3017 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003018 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003019 // C++ [over.match.ctor]p1:
3020 // When objects of class type are direct-initialized (8.5), or
3021 // copy-initialized from an expression of the same or a
3022 // derived class type (8.5), overload resolution selects the
3023 // constructor. [...] For copy-initialization, the candidate
3024 // functions are all the converting constructors (12.3.1) of
3025 // that class. The argument list is the expression-list within
3026 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003027 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003028 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003029 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003030 ConstructorsOnly = true;
3031
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003032 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003033 // RequireCompleteType may have returned true due to some invalid decl
3034 // during template instantiation, but ToType may be complete enough now
3035 // to try to recover.
3036 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003037 // We're not going to find any constructors.
3038 } else if (CXXRecordDecl *ToRecordDecl
3039 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003040
3041 Expr **Args = &From;
3042 unsigned NumArgs = 1;
3043 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003044 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003045 // But first, see if there is an init-list-contructor that will work.
3046 OverloadingResult Result = IsInitializerListConstructorConversion(
3047 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3048 if (Result != OR_No_Viable_Function)
3049 return Result;
3050 // Never mind.
3051 CandidateSet.clear();
3052
3053 // If we're list-initializing, we pass the individual elements as
3054 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003055 Args = InitList->getInits();
3056 NumArgs = InitList->getNumInits();
3057 ListInitializing = true;
3058 }
3059
David Blaikie3bc93e32012-12-19 00:45:41 +00003060 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3061 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003062 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003063 NamedDecl *D = *Con;
3064 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3065
Douglas Gregordec06662009-08-21 18:42:58 +00003066 // Find the constructor (which may be a template).
3067 CXXConstructorDecl *Constructor = 0;
3068 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003069 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003070 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003071 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003072 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3073 else
John McCall9aa472c2010-03-19 07:35:19 +00003074 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003075
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003076 bool Usable = !Constructor->isInvalidDecl();
3077 if (ListInitializing)
3078 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3079 else
3080 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3081 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003082 bool SuppressUserConversions = !ConstructorsOnly;
3083 if (SuppressUserConversions && ListInitializing) {
3084 SuppressUserConversions = false;
3085 if (NumArgs == 1) {
3086 // If the first argument is (a reference to) the target type,
3087 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003088 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3089 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003090 }
3091 }
Douglas Gregordec06662009-08-21 18:42:58 +00003092 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003093 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3094 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003095 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003096 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003097 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003098 // Allow one user-defined conversion when user specifies a
3099 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003100 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003101 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003102 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003103 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003104 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003105 }
3106 }
3107
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003108 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003109 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003110 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003111 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003112 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003113 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003114 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003115 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3116 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003117 std::pair<CXXRecordDecl::conversion_iterator,
3118 CXXRecordDecl::conversion_iterator>
3119 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3120 for (CXXRecordDecl::conversion_iterator
3121 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003122 DeclAccessPair FoundDecl = I.getPair();
3123 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003124 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3125 if (isa<UsingShadowDecl>(D))
3126 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3127
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003128 CXXConversionDecl *Conv;
3129 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003130 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3131 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003132 else
John McCall32daa422010-03-31 01:36:47 +00003133 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003134
3135 if (AllowExplicit || !Conv->isExplicit()) {
3136 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003137 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3138 ActingContext, From, ToType,
3139 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003140 else
John McCall120d63c2010-08-24 20:38:10 +00003141 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3142 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003143 }
3144 }
3145 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003146 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003147
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003148 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3149
Douglas Gregor60d62c22008-10-31 16:23:19 +00003150 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003151 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003152 case OR_Success:
3153 // Record the standard conversion we used and the conversion function.
3154 if (CXXConstructorDecl *Constructor
3155 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3156 // C++ [over.ics.user]p1:
3157 // If the user-defined conversion is specified by a
3158 // constructor (12.3.1), the initial standard conversion
3159 // sequence converts the source type to the type required by
3160 // the argument of the constructor.
3161 //
3162 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003163 if (isa<InitListExpr>(From)) {
3164 // Initializer lists don't have conversions as such.
3165 User.Before.setAsIdentityConversion();
3166 } else {
3167 if (Best->Conversions[0].isEllipsis())
3168 User.EllipsisConversion = true;
3169 else {
3170 User.Before = Best->Conversions[0].Standard;
3171 User.EllipsisConversion = false;
3172 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003173 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003174 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003175 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003176 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003177 User.After.setAsIdentityConversion();
3178 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3179 User.After.setAllToTypes(ToType);
3180 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003181 }
3182 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003183 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3184 // C++ [over.ics.user]p1:
3185 //
3186 // [...] If the user-defined conversion is specified by a
3187 // conversion function (12.3.2), the initial standard
3188 // conversion sequence converts the source type to the
3189 // implicit object parameter of the conversion function.
3190 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003191 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003192 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003193 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003194 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003195
John McCall120d63c2010-08-24 20:38:10 +00003196 // C++ [over.ics.user]p2:
3197 // The second standard conversion sequence converts the
3198 // result of the user-defined conversion to the target type
3199 // for the sequence. Since an implicit conversion sequence
3200 // is an initialization, the special rules for
3201 // initialization by user-defined conversion apply when
3202 // selecting the best user-defined conversion for a
3203 // user-defined conversion sequence (see 13.3.3 and
3204 // 13.3.3.1).
3205 User.After = Best->FinalConversion;
3206 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003207 }
David Blaikie7530c032012-01-17 06:56:22 +00003208 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003209
John McCall120d63c2010-08-24 20:38:10 +00003210 case OR_No_Viable_Function:
3211 return OR_No_Viable_Function;
3212 case OR_Deleted:
3213 // No conversion here! We're done.
3214 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003215
John McCall120d63c2010-08-24 20:38:10 +00003216 case OR_Ambiguous:
3217 return OR_Ambiguous;
3218 }
3219
David Blaikie7530c032012-01-17 06:56:22 +00003220 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003221}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003222
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003223bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003225 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003226 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003227 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003228 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003229 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003230 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003231 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003232 diag::err_typecheck_ambiguous_condition)
3233 << From->getType() << ToType << From->getSourceRange();
3234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003235 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003236 diag::err_typecheck_nonviable_condition)
3237 << From->getType() << ToType << From->getSourceRange();
3238 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003239 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003240 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003241 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003242}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003243
Douglas Gregorb734e242012-02-22 17:32:19 +00003244/// \brief Compare the user-defined conversion functions or constructors
3245/// of two user-defined conversion sequences to determine whether any ordering
3246/// is possible.
3247static ImplicitConversionSequence::CompareKind
3248compareConversionFunctions(Sema &S,
3249 FunctionDecl *Function1,
3250 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003251 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003252 return ImplicitConversionSequence::Indistinguishable;
3253
3254 // Objective-C++:
3255 // If both conversion functions are implicitly-declared conversions from
3256 // a lambda closure type to a function pointer and a block pointer,
3257 // respectively, always prefer the conversion to a function pointer,
3258 // because the function pointer is more lightweight and is more likely
3259 // to keep code working.
3260 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3261 if (!Conv1)
3262 return ImplicitConversionSequence::Indistinguishable;
3263
3264 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3265 if (!Conv2)
3266 return ImplicitConversionSequence::Indistinguishable;
3267
3268 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3269 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3270 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3271 if (Block1 != Block2)
3272 return Block1? ImplicitConversionSequence::Worse
3273 : ImplicitConversionSequence::Better;
3274 }
3275
3276 return ImplicitConversionSequence::Indistinguishable;
3277}
3278
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003279/// CompareImplicitConversionSequences - Compare two implicit
3280/// conversion sequences to determine whether one is better than the
3281/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003282static ImplicitConversionSequence::CompareKind
3283CompareImplicitConversionSequences(Sema &S,
3284 const ImplicitConversionSequence& ICS1,
3285 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003286{
3287 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3288 // conversion sequences (as defined in 13.3.3.1)
3289 // -- a standard conversion sequence (13.3.3.1.1) is a better
3290 // conversion sequence than a user-defined conversion sequence or
3291 // an ellipsis conversion sequence, and
3292 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3293 // conversion sequence than an ellipsis conversion sequence
3294 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003295 //
John McCall1d318332010-01-12 00:44:57 +00003296 // C++0x [over.best.ics]p10:
3297 // For the purpose of ranking implicit conversion sequences as
3298 // described in 13.3.3.2, the ambiguous conversion sequence is
3299 // treated as a user-defined sequence that is indistinguishable
3300 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003301 if (ICS1.getKindRank() < ICS2.getKindRank())
3302 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003303 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003304 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003305
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003306 // The following checks require both conversion sequences to be of
3307 // the same kind.
3308 if (ICS1.getKind() != ICS2.getKind())
3309 return ImplicitConversionSequence::Indistinguishable;
3310
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003311 ImplicitConversionSequence::CompareKind Result =
3312 ImplicitConversionSequence::Indistinguishable;
3313
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003314 // Two implicit conversion sequences of the same form are
3315 // indistinguishable conversion sequences unless one of the
3316 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003317 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003318 Result = CompareStandardConversionSequences(S,
3319 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003320 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003321 // User-defined conversion sequence U1 is a better conversion
3322 // sequence than another user-defined conversion sequence U2 if
3323 // they contain the same user-defined conversion function or
3324 // constructor and if the second standard conversion sequence of
3325 // U1 is better than the second standard conversion sequence of
3326 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003327 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003328 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003329 Result = CompareStandardConversionSequences(S,
3330 ICS1.UserDefined.After,
3331 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003332 else
3333 Result = compareConversionFunctions(S,
3334 ICS1.UserDefined.ConversionFunction,
3335 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003336 }
3337
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003338 // List-initialization sequence L1 is a better conversion sequence than
3339 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3340 // for some X and L2 does not.
3341 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003342 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003343 ICS1.isListInitializationSequence() &&
3344 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003345 if (ICS1.isStdInitializerListElement() &&
3346 !ICS2.isStdInitializerListElement())
3347 return ImplicitConversionSequence::Better;
3348 if (!ICS1.isStdInitializerListElement() &&
3349 ICS2.isStdInitializerListElement())
3350 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003351 }
3352
3353 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003354}
3355
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003356static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3357 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3358 Qualifiers Quals;
3359 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003361 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003363 return Context.hasSameUnqualifiedType(T1, T2);
3364}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003365
Douglas Gregorad323a82010-01-27 03:51:04 +00003366// Per 13.3.3.2p3, compare the given standard conversion sequences to
3367// determine if one is a proper subset of the other.
3368static ImplicitConversionSequence::CompareKind
3369compareStandardConversionSubsets(ASTContext &Context,
3370 const StandardConversionSequence& SCS1,
3371 const StandardConversionSequence& SCS2) {
3372 ImplicitConversionSequence::CompareKind Result
3373 = ImplicitConversionSequence::Indistinguishable;
3374
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003375 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003376 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003377 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3378 return ImplicitConversionSequence::Better;
3379 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3380 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003381
Douglas Gregorad323a82010-01-27 03:51:04 +00003382 if (SCS1.Second != SCS2.Second) {
3383 if (SCS1.Second == ICK_Identity)
3384 Result = ImplicitConversionSequence::Better;
3385 else if (SCS2.Second == ICK_Identity)
3386 Result = ImplicitConversionSequence::Worse;
3387 else
3388 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003389 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003390 return ImplicitConversionSequence::Indistinguishable;
3391
3392 if (SCS1.Third == SCS2.Third) {
3393 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3394 : ImplicitConversionSequence::Indistinguishable;
3395 }
3396
3397 if (SCS1.Third == ICK_Identity)
3398 return Result == ImplicitConversionSequence::Worse
3399 ? ImplicitConversionSequence::Indistinguishable
3400 : ImplicitConversionSequence::Better;
3401
3402 if (SCS2.Third == ICK_Identity)
3403 return Result == ImplicitConversionSequence::Better
3404 ? ImplicitConversionSequence::Indistinguishable
3405 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Douglas Gregorad323a82010-01-27 03:51:04 +00003407 return ImplicitConversionSequence::Indistinguishable;
3408}
3409
Douglas Gregor440a4832011-01-26 14:52:12 +00003410/// \brief Determine whether one of the given reference bindings is better
3411/// than the other based on what kind of bindings they are.
3412static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3413 const StandardConversionSequence &SCS2) {
3414 // C++0x [over.ics.rank]p3b4:
3415 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3416 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003417 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003418 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003419 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003420 // reference*.
3421 //
3422 // FIXME: Rvalue references. We're going rogue with the above edits,
3423 // because the semantics in the current C++0x working paper (N3225 at the
3424 // time of this writing) break the standard definition of std::forward
3425 // and std::reference_wrapper when dealing with references to functions.
3426 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003427 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3428 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3429 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003430
Douglas Gregor440a4832011-01-26 14:52:12 +00003431 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3432 SCS2.IsLvalueReference) ||
3433 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3434 !SCS2.IsLvalueReference);
3435}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003436
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003437/// CompareStandardConversionSequences - Compare two standard
3438/// conversion sequences to determine whether one is better than the
3439/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003440static ImplicitConversionSequence::CompareKind
3441CompareStandardConversionSequences(Sema &S,
3442 const StandardConversionSequence& SCS1,
3443 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003444{
3445 // Standard conversion sequence S1 is a better conversion sequence
3446 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3447
3448 // -- S1 is a proper subsequence of S2 (comparing the conversion
3449 // sequences in the canonical form defined by 13.3.3.1.1,
3450 // excluding any Lvalue Transformation; the identity conversion
3451 // sequence is considered to be a subsequence of any
3452 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003453 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003454 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003455 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003456
3457 // -- the rank of S1 is better than the rank of S2 (by the rules
3458 // defined below), or, if not that,
3459 ImplicitConversionRank Rank1 = SCS1.getRank();
3460 ImplicitConversionRank Rank2 = SCS2.getRank();
3461 if (Rank1 < Rank2)
3462 return ImplicitConversionSequence::Better;
3463 else if (Rank2 < Rank1)
3464 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003465
Douglas Gregor57373262008-10-22 14:17:15 +00003466 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3467 // are indistinguishable unless one of the following rules
3468 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003469
Douglas Gregor57373262008-10-22 14:17:15 +00003470 // A conversion that is not a conversion of a pointer, or
3471 // pointer to member, to bool is better than another conversion
3472 // that is such a conversion.
3473 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3474 return SCS2.isPointerConversionToBool()
3475 ? ImplicitConversionSequence::Better
3476 : ImplicitConversionSequence::Worse;
3477
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003478 // C++ [over.ics.rank]p4b2:
3479 //
3480 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003481 // conversion of B* to A* is better than conversion of B* to
3482 // void*, and conversion of A* to void* is better than conversion
3483 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003484 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003485 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003486 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003487 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003488 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3489 // Exactly one of the conversion sequences is a conversion to
3490 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003491 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3492 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003493 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3494 // Neither conversion sequence converts to a void pointer; compare
3495 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003496 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003497 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003498 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003499 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3500 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003501 // Both conversion sequences are conversions to void
3502 // pointers. Compare the source types to determine if there's an
3503 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003504 QualType FromType1 = SCS1.getFromType();
3505 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003506
3507 // Adjust the types we're converting from via the array-to-pointer
3508 // conversion, if we need to.
3509 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003510 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003511 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003512 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003513
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003514 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3515 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003516
John McCall120d63c2010-08-24 20:38:10 +00003517 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003518 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003519 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003520 return ImplicitConversionSequence::Worse;
3521
3522 // Objective-C++: If one interface is more specific than the
3523 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003524 const ObjCObjectPointerType* FromObjCPtr1
3525 = FromType1->getAs<ObjCObjectPointerType>();
3526 const ObjCObjectPointerType* FromObjCPtr2
3527 = FromType2->getAs<ObjCObjectPointerType>();
3528 if (FromObjCPtr1 && FromObjCPtr2) {
3529 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3530 FromObjCPtr2);
3531 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3532 FromObjCPtr1);
3533 if (AssignLeft != AssignRight) {
3534 return AssignLeft? ImplicitConversionSequence::Better
3535 : ImplicitConversionSequence::Worse;
3536 }
Douglas Gregor01919692009-12-13 21:37:05 +00003537 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003538 }
Douglas Gregor57373262008-10-22 14:17:15 +00003539
3540 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3541 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003542 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003543 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003544 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003545
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003546 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003547 // Check for a better reference binding based on the kind of bindings.
3548 if (isBetterReferenceBindingKind(SCS1, SCS2))
3549 return ImplicitConversionSequence::Better;
3550 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3551 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003552
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003553 // C++ [over.ics.rank]p3b4:
3554 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3555 // which the references refer are the same type except for
3556 // top-level cv-qualifiers, and the type to which the reference
3557 // initialized by S2 refers is more cv-qualified than the type
3558 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003559 QualType T1 = SCS1.getToType(2);
3560 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003561 T1 = S.Context.getCanonicalType(T1);
3562 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003563 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003564 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3565 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003566 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003567 // Objective-C++ ARC: If the references refer to objects with different
3568 // lifetimes, prefer bindings that don't change lifetime.
3569 if (SCS1.ObjCLifetimeConversionBinding !=
3570 SCS2.ObjCLifetimeConversionBinding) {
3571 return SCS1.ObjCLifetimeConversionBinding
3572 ? ImplicitConversionSequence::Worse
3573 : ImplicitConversionSequence::Better;
3574 }
3575
Chandler Carruth6df868e2010-12-12 08:17:55 +00003576 // If the type is an array type, promote the element qualifiers to the
3577 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003578 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003579 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003580 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003581 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003582 if (T2.isMoreQualifiedThan(T1))
3583 return ImplicitConversionSequence::Better;
3584 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003585 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003586 }
3587 }
Douglas Gregor57373262008-10-22 14:17:15 +00003588
Francois Pichet1c98d622011-09-18 21:37:37 +00003589 // In Microsoft mode, prefer an integral conversion to a
3590 // floating-to-integral conversion if the integral conversion
3591 // is between types of the same size.
3592 // For example:
3593 // void f(float);
3594 // void f(int);
3595 // int main {
3596 // long a;
3597 // f(a);
3598 // }
3599 // Here, MSVC will call f(int) instead of generating a compile error
3600 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003601 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003602 SCS1.Second == ICK_Integral_Conversion &&
3603 SCS2.Second == ICK_Floating_Integral &&
3604 S.Context.getTypeSize(SCS1.getFromType()) ==
3605 S.Context.getTypeSize(SCS1.getToType(2)))
3606 return ImplicitConversionSequence::Better;
3607
Douglas Gregor57373262008-10-22 14:17:15 +00003608 return ImplicitConversionSequence::Indistinguishable;
3609}
3610
3611/// CompareQualificationConversions - Compares two standard conversion
3612/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003613/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3614ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003615CompareQualificationConversions(Sema &S,
3616 const StandardConversionSequence& SCS1,
3617 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003618 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003619 // -- S1 and S2 differ only in their qualification conversion and
3620 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3621 // cv-qualification signature of type T1 is a proper subset of
3622 // the cv-qualification signature of type T2, and S1 is not the
3623 // deprecated string literal array-to-pointer conversion (4.2).
3624 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3625 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3626 return ImplicitConversionSequence::Indistinguishable;
3627
3628 // FIXME: the example in the standard doesn't use a qualification
3629 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003630 QualType T1 = SCS1.getToType(2);
3631 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003632 T1 = S.Context.getCanonicalType(T1);
3633 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003634 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003635 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3636 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003637
3638 // If the types are the same, we won't learn anything by unwrapped
3639 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003640 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003641 return ImplicitConversionSequence::Indistinguishable;
3642
Chandler Carruth28e318c2009-12-29 07:16:59 +00003643 // If the type is an array type, promote the element qualifiers to the type
3644 // for comparison.
3645 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003646 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003647 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003648 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003649
Mike Stump1eb44332009-09-09 15:08:12 +00003650 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003651 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003652
3653 // Objective-C++ ARC:
3654 // Prefer qualification conversions not involving a change in lifetime
3655 // to qualification conversions that do not change lifetime.
3656 if (SCS1.QualificationIncludesObjCLifetime !=
3657 SCS2.QualificationIncludesObjCLifetime) {
3658 Result = SCS1.QualificationIncludesObjCLifetime
3659 ? ImplicitConversionSequence::Worse
3660 : ImplicitConversionSequence::Better;
3661 }
3662
John McCall120d63c2010-08-24 20:38:10 +00003663 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003664 // Within each iteration of the loop, we check the qualifiers to
3665 // determine if this still looks like a qualification
3666 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003667 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003668 // until there are no more pointers or pointers-to-members left
3669 // to unwrap. This essentially mimics what
3670 // IsQualificationConversion does, but here we're checking for a
3671 // strict subset of qualifiers.
3672 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3673 // The qualifiers are the same, so this doesn't tell us anything
3674 // about how the sequences rank.
3675 ;
3676 else if (T2.isMoreQualifiedThan(T1)) {
3677 // T1 has fewer qualifiers, so it could be the better sequence.
3678 if (Result == ImplicitConversionSequence::Worse)
3679 // Neither has qualifiers that are a subset of the other's
3680 // qualifiers.
3681 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003682
Douglas Gregor57373262008-10-22 14:17:15 +00003683 Result = ImplicitConversionSequence::Better;
3684 } else if (T1.isMoreQualifiedThan(T2)) {
3685 // T2 has fewer qualifiers, so it could be the better sequence.
3686 if (Result == ImplicitConversionSequence::Better)
3687 // Neither has qualifiers that are a subset of the other's
3688 // qualifiers.
3689 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003690
Douglas Gregor57373262008-10-22 14:17:15 +00003691 Result = ImplicitConversionSequence::Worse;
3692 } else {
3693 // Qualifiers are disjoint.
3694 return ImplicitConversionSequence::Indistinguishable;
3695 }
3696
3697 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003698 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003699 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003700 }
3701
Douglas Gregor57373262008-10-22 14:17:15 +00003702 // Check that the winning standard conversion sequence isn't using
3703 // the deprecated string literal array to pointer conversion.
3704 switch (Result) {
3705 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003706 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003707 Result = ImplicitConversionSequence::Indistinguishable;
3708 break;
3709
3710 case ImplicitConversionSequence::Indistinguishable:
3711 break;
3712
3713 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003714 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003715 Result = ImplicitConversionSequence::Indistinguishable;
3716 break;
3717 }
3718
3719 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003720}
3721
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003722/// CompareDerivedToBaseConversions - Compares two standard conversion
3723/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003724/// various kinds of derived-to-base conversions (C++
3725/// [over.ics.rank]p4b3). As part of these checks, we also look at
3726/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003727ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003728CompareDerivedToBaseConversions(Sema &S,
3729 const StandardConversionSequence& SCS1,
3730 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003731 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003732 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003733 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003734 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003735
3736 // Adjust the types we're converting from via the array-to-pointer
3737 // conversion, if we need to.
3738 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003739 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003740 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003741 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003742
3743 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003744 FromType1 = S.Context.getCanonicalType(FromType1);
3745 ToType1 = S.Context.getCanonicalType(ToType1);
3746 FromType2 = S.Context.getCanonicalType(FromType2);
3747 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003748
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003749 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003750 //
3751 // If class B is derived directly or indirectly from class A and
3752 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003753 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003754 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003755 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003756 SCS2.Second == ICK_Pointer_Conversion &&
3757 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3758 FromType1->isPointerType() && FromType2->isPointerType() &&
3759 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003760 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003761 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003762 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003763 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003764 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003765 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003766 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003767 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003768
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003769 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003770 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003771 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003772 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003773 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003774 return ImplicitConversionSequence::Worse;
3775 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003776
3777 // -- conversion of B* to A* is better than conversion of C* to A*,
3778 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003779 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003780 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003781 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003782 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003783 }
3784 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3785 SCS2.Second == ICK_Pointer_Conversion) {
3786 const ObjCObjectPointerType *FromPtr1
3787 = FromType1->getAs<ObjCObjectPointerType>();
3788 const ObjCObjectPointerType *FromPtr2
3789 = FromType2->getAs<ObjCObjectPointerType>();
3790 const ObjCObjectPointerType *ToPtr1
3791 = ToType1->getAs<ObjCObjectPointerType>();
3792 const ObjCObjectPointerType *ToPtr2
3793 = ToType2->getAs<ObjCObjectPointerType>();
3794
3795 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3796 // Apply the same conversion ranking rules for Objective-C pointer types
3797 // that we do for C++ pointers to class types. However, we employ the
3798 // Objective-C pseudo-subtyping relationship used for assignment of
3799 // Objective-C pointer types.
3800 bool FromAssignLeft
3801 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3802 bool FromAssignRight
3803 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3804 bool ToAssignLeft
3805 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3806 bool ToAssignRight
3807 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3808
3809 // A conversion to an a non-id object pointer type or qualified 'id'
3810 // type is better than a conversion to 'id'.
3811 if (ToPtr1->isObjCIdType() &&
3812 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3813 return ImplicitConversionSequence::Worse;
3814 if (ToPtr2->isObjCIdType() &&
3815 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3816 return ImplicitConversionSequence::Better;
3817
3818 // A conversion to a non-id object pointer type is better than a
3819 // conversion to a qualified 'id' type
3820 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3821 return ImplicitConversionSequence::Worse;
3822 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3823 return ImplicitConversionSequence::Better;
3824
3825 // A conversion to an a non-Class object pointer type or qualified 'Class'
3826 // type is better than a conversion to 'Class'.
3827 if (ToPtr1->isObjCClassType() &&
3828 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3829 return ImplicitConversionSequence::Worse;
3830 if (ToPtr2->isObjCClassType() &&
3831 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3832 return ImplicitConversionSequence::Better;
3833
3834 // A conversion to a non-Class object pointer type is better than a
3835 // conversion to a qualified 'Class' type.
3836 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3837 return ImplicitConversionSequence::Worse;
3838 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3839 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003840
Douglas Gregor395cc372011-01-31 18:51:41 +00003841 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3842 if (S.Context.hasSameType(FromType1, FromType2) &&
3843 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3844 (ToAssignLeft != ToAssignRight))
3845 return ToAssignLeft? ImplicitConversionSequence::Worse
3846 : ImplicitConversionSequence::Better;
3847
3848 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3849 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3850 (FromAssignLeft != FromAssignRight))
3851 return FromAssignLeft? ImplicitConversionSequence::Better
3852 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003853 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003854 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003855
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003856 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003857 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3858 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3859 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003860 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003861 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003862 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003863 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003865 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003866 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003867 ToType2->getAs<MemberPointerType>();
3868 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3869 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3870 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3871 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3872 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3873 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3874 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3875 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003876 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003877 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003878 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003879 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003880 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003881 return ImplicitConversionSequence::Better;
3882 }
3883 // conversion of B::* to C::* is better than conversion of A::* to C::*
3884 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003885 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003886 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003887 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003888 return ImplicitConversionSequence::Worse;
3889 }
3890 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003891
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003892 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003893 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003894 // -- binding of an expression of type C to a reference of type
3895 // B& is better than binding an expression of type C to a
3896 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003897 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3898 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3899 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003900 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003901 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003902 return ImplicitConversionSequence::Worse;
3903 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003904
Douglas Gregor225c41e2008-11-03 19:09:14 +00003905 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003906 // -- binding of an expression of type B to a reference of type
3907 // A& is better than binding an expression of type C to a
3908 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003909 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3910 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3911 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003912 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003913 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003914 return ImplicitConversionSequence::Worse;
3915 }
3916 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003917
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003918 return ImplicitConversionSequence::Indistinguishable;
3919}
3920
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003921/// \brief Determine whether the given type is valid, e.g., it is not an invalid
3922/// C++ class.
3923static bool isTypeValid(QualType T) {
3924 if (CXXRecordDecl *Record = T->getAsCXXRecordDecl())
3925 return !Record->isInvalidDecl();
3926
3927 return true;
3928}
3929
Douglas Gregorabe183d2010-04-13 16:31:36 +00003930/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3931/// determine whether they are reference-related,
3932/// reference-compatible, reference-compatible with added
3933/// qualification, or incompatible, for use in C++ initialization by
3934/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3935/// type, and the first type (T1) is the pointee type of the reference
3936/// type being initialized.
3937Sema::ReferenceCompareResult
3938Sema::CompareReferenceRelationship(SourceLocation Loc,
3939 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003940 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003941 bool &ObjCConversion,
3942 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003943 assert(!OrigT1->isReferenceType() &&
3944 "T1 must be the pointee type of the reference type");
3945 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3946
3947 QualType T1 = Context.getCanonicalType(OrigT1);
3948 QualType T2 = Context.getCanonicalType(OrigT2);
3949 Qualifiers T1Quals, T2Quals;
3950 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3951 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3952
3953 // C++ [dcl.init.ref]p4:
3954 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3955 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3956 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003957 DerivedToBase = false;
3958 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003959 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003960 if (UnqualT1 == UnqualT2) {
3961 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003962 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregor0162c1c2013-03-26 23:36:30 +00003963 isTypeValid(UnqualT1) && isTypeValid(UnqualT2) &&
3964 IsDerivedFrom(UnqualT2, UnqualT1))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003965 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003966 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3967 UnqualT2->isObjCObjectOrInterfaceType() &&
3968 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3969 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003970 else
3971 return Ref_Incompatible;
3972
3973 // At this point, we know that T1 and T2 are reference-related (at
3974 // least).
3975
3976 // If the type is an array type, promote the element qualifiers to the type
3977 // for comparison.
3978 if (isa<ArrayType>(T1) && T1Quals)
3979 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3980 if (isa<ArrayType>(T2) && T2Quals)
3981 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3982
3983 // C++ [dcl.init.ref]p4:
3984 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3985 // reference-related to T2 and cv1 is the same cv-qualification
3986 // as, or greater cv-qualification than, cv2. For purposes of
3987 // overload resolution, cases for which cv1 is greater
3988 // cv-qualification than cv2 are identified as
3989 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003990 //
3991 // Note that we also require equivalence of Objective-C GC and address-space
3992 // qualifiers when performing these computations, so that e.g., an int in
3993 // address space 1 is not reference-compatible with an int in address
3994 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003995 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3996 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3997 T1Quals.removeObjCLifetime();
3998 T2Quals.removeObjCLifetime();
3999 ObjCLifetimeConversion = true;
4000 }
4001
Douglas Gregora6ce3e62011-04-28 17:56:11 +00004002 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00004003 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00004004 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004005 return Ref_Compatible_With_Added_Qualification;
4006 else
4007 return Ref_Related;
4008}
4009
Douglas Gregor604eb652010-08-11 02:15:33 +00004010/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004011/// with DeclType. Return true if something definite is found.
4012static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004013FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4014 QualType DeclType, SourceLocation DeclLoc,
4015 Expr *Init, QualType T2, bool AllowRvalues,
4016 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004017 assert(T2->isRecordType() && "Can only find conversions of record types.");
4018 CXXRecordDecl *T2RecordDecl
4019 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4020
4021 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004022 std::pair<CXXRecordDecl::conversion_iterator,
4023 CXXRecordDecl::conversion_iterator>
4024 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4025 for (CXXRecordDecl::conversion_iterator
4026 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004027 NamedDecl *D = *I;
4028 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4029 if (isa<UsingShadowDecl>(D))
4030 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4031
4032 FunctionTemplateDecl *ConvTemplate
4033 = dyn_cast<FunctionTemplateDecl>(D);
4034 CXXConversionDecl *Conv;
4035 if (ConvTemplate)
4036 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4037 else
4038 Conv = cast<CXXConversionDecl>(D);
4039
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004040 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004041 // explicit conversions, skip it.
4042 if (!AllowExplicit && Conv->isExplicit())
4043 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004044
Douglas Gregor604eb652010-08-11 02:15:33 +00004045 if (AllowRvalues) {
4046 bool DerivedToBase = false;
4047 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004048 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004049
4050 // If we are initializing an rvalue reference, don't permit conversion
4051 // functions that return lvalues.
4052 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4053 const ReferenceType *RefType
4054 = Conv->getConversionType()->getAs<LValueReferenceType>();
4055 if (RefType && !RefType->getPointeeType()->isFunctionType())
4056 continue;
4057 }
4058
Douglas Gregor604eb652010-08-11 02:15:33 +00004059 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004060 S.CompareReferenceRelationship(
4061 DeclLoc,
4062 Conv->getConversionType().getNonReferenceType()
4063 .getUnqualifiedType(),
4064 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004065 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004066 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004067 continue;
4068 } else {
4069 // If the conversion function doesn't return a reference type,
4070 // it can't be considered for this conversion. An rvalue reference
4071 // is only acceptable if its referencee is a function type.
4072
4073 const ReferenceType *RefType =
4074 Conv->getConversionType()->getAs<ReferenceType>();
4075 if (!RefType ||
4076 (!RefType->isLValueReferenceType() &&
4077 !RefType->getPointeeType()->isFunctionType()))
4078 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004079 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004080
Douglas Gregor604eb652010-08-11 02:15:33 +00004081 if (ConvTemplate)
4082 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004083 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004084 else
4085 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004086 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004087 }
4088
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004089 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4090
Sebastian Redl4680bf22010-06-30 18:13:39 +00004091 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004092 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004093 case OR_Success:
4094 // C++ [over.ics.ref]p1:
4095 //
4096 // [...] If the parameter binds directly to the result of
4097 // applying a conversion function to the argument
4098 // expression, the implicit conversion sequence is a
4099 // user-defined conversion sequence (13.3.3.1.2), with the
4100 // second standard conversion sequence either an identity
4101 // conversion or, if the conversion function returns an
4102 // entity of a type that is a derived class of the parameter
4103 // type, a derived-to-base Conversion.
4104 if (!Best->FinalConversion.DirectBinding)
4105 return false;
4106
4107 ICS.setUserDefined();
4108 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4109 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004110 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004111 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004112 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004113 ICS.UserDefined.EllipsisConversion = false;
4114 assert(ICS.UserDefined.After.ReferenceBinding &&
4115 ICS.UserDefined.After.DirectBinding &&
4116 "Expected a direct reference binding!");
4117 return true;
4118
4119 case OR_Ambiguous:
4120 ICS.setAmbiguous();
4121 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4122 Cand != CandidateSet.end(); ++Cand)
4123 if (Cand->Viable)
4124 ICS.Ambiguous.addConversion(Cand->Function);
4125 return true;
4126
4127 case OR_No_Viable_Function:
4128 case OR_Deleted:
4129 // There was no suitable conversion, or we found a deleted
4130 // conversion; continue with other checks.
4131 return false;
4132 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004133
David Blaikie7530c032012-01-17 06:56:22 +00004134 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004135}
4136
Douglas Gregorabe183d2010-04-13 16:31:36 +00004137/// \brief Compute an implicit conversion sequence for reference
4138/// initialization.
4139static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004140TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004141 SourceLocation DeclLoc,
4142 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004143 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004144 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4145
4146 // Most paths end in a failed conversion.
4147 ImplicitConversionSequence ICS;
4148 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4149
4150 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4151 QualType T2 = Init->getType();
4152
4153 // If the initializer is the address of an overloaded function, try
4154 // to resolve the overloaded function. If all goes well, T2 is the
4155 // type of the resulting function.
4156 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4157 DeclAccessPair Found;
4158 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4159 false, Found))
4160 T2 = Fn->getType();
4161 }
4162
4163 // Compute some basic properties of the types and the initializer.
4164 bool isRValRef = DeclType->isRValueReferenceType();
4165 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004166 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004167 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004168 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004169 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004170 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004171 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004172
Douglas Gregorabe183d2010-04-13 16:31:36 +00004173
Sebastian Redl4680bf22010-06-30 18:13:39 +00004174 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004175 // A reference to type "cv1 T1" is initialized by an expression
4176 // of type "cv2 T2" as follows:
4177
Sebastian Redl4680bf22010-06-30 18:13:39 +00004178 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004179 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004180 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4181 // reference-compatible with "cv2 T2," or
4182 //
4183 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4184 if (InitCategory.isLValue() &&
4185 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004186 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004187 // When a parameter of reference type binds directly (8.5.3)
4188 // to an argument expression, the implicit conversion sequence
4189 // is the identity conversion, unless the argument expression
4190 // has a type that is a derived class of the parameter type,
4191 // in which case the implicit conversion sequence is a
4192 // derived-to-base Conversion (13.3.3.1).
4193 ICS.setStandard();
4194 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004195 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4196 : ObjCConversion? ICK_Compatible_Conversion
4197 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004198 ICS.Standard.Third = ICK_Identity;
4199 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4200 ICS.Standard.setToType(0, T2);
4201 ICS.Standard.setToType(1, T1);
4202 ICS.Standard.setToType(2, T1);
4203 ICS.Standard.ReferenceBinding = true;
4204 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004205 ICS.Standard.IsLvalueReference = !isRValRef;
4206 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4207 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004208 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004209 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004210 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004211
Sebastian Redl4680bf22010-06-30 18:13:39 +00004212 // Nothing more to do: the inaccessibility/ambiguity check for
4213 // derived-to-base conversions is suppressed when we're
4214 // computing the implicit conversion sequence (C++
4215 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004216 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004217 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004218
Sebastian Redl4680bf22010-06-30 18:13:39 +00004219 // -- has a class type (i.e., T2 is a class type), where T1 is
4220 // not reference-related to T2, and can be implicitly
4221 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4222 // is reference-compatible with "cv3 T3" 92) (this
4223 // conversion is selected by enumerating the applicable
4224 // conversion functions (13.3.1.6) and choosing the best
4225 // one through overload resolution (13.3)),
4226 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004227 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004228 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004229 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4230 Init, T2, /*AllowRvalues=*/false,
4231 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004232 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004233 }
4234 }
4235
Sebastian Redl4680bf22010-06-30 18:13:39 +00004236 // -- Otherwise, the reference shall be an lvalue reference to a
4237 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004238 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004239 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004240 // We actually handle one oddity of C++ [over.ics.ref] at this
4241 // point, which is that, due to p2 (which short-circuits reference
4242 // binding by only attempting a simple conversion for non-direct
4243 // bindings) and p3's strange wording, we allow a const volatile
4244 // reference to bind to an rvalue. Hence the check for the presence
4245 // of "const" rather than checking for "const" being the only
4246 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004247 // This is also the point where rvalue references and lvalue inits no longer
4248 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004249 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004250 return ICS;
4251
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004252 // -- If the initializer expression
4253 //
4254 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004255 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004256 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4257 (InitCategory.isXValue() ||
4258 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4259 (InitCategory.isLValue() && T2->isFunctionType()))) {
4260 ICS.setStandard();
4261 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004262 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004263 : ObjCConversion? ICK_Compatible_Conversion
4264 : ICK_Identity;
4265 ICS.Standard.Third = ICK_Identity;
4266 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4267 ICS.Standard.setToType(0, T2);
4268 ICS.Standard.setToType(1, T1);
4269 ICS.Standard.setToType(2, T1);
4270 ICS.Standard.ReferenceBinding = true;
4271 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4272 // binding unless we're binding to a class prvalue.
4273 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4274 // allow the use of rvalue references in C++98/03 for the benefit of
4275 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004276 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004277 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004278 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004279 ICS.Standard.IsLvalueReference = !isRValRef;
4280 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004282 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004283 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004284 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004286 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004287
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004288 // -- has a class type (i.e., T2 is a class type), where T1 is not
4289 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004290 // an xvalue, class prvalue, or function lvalue of type
4291 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004292 // "cv3 T3",
4293 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004294 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004295 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004296 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004297 // class subobject).
4298 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004299 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004300 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4301 Init, T2, /*AllowRvalues=*/true,
4302 AllowExplicit)) {
4303 // In the second case, if the reference is an rvalue reference
4304 // and the second standard conversion sequence of the
4305 // user-defined conversion sequence includes an lvalue-to-rvalue
4306 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004307 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004308 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4309 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4310
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004311 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004313
Douglas Gregorabe183d2010-04-13 16:31:36 +00004314 // -- Otherwise, a temporary of type "cv1 T1" is created and
4315 // initialized from the initializer expression using the
4316 // rules for a non-reference copy initialization (8.5). The
4317 // reference is then bound to the temporary. If T1 is
4318 // reference-related to T2, cv1 must be the same
4319 // cv-qualification as, or greater cv-qualification than,
4320 // cv2; otherwise, the program is ill-formed.
4321 if (RefRelationship == Sema::Ref_Related) {
4322 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4323 // we would be reference-compatible or reference-compatible with
4324 // added qualification. But that wasn't the case, so the reference
4325 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004326 //
4327 // Note that we only want to check address spaces and cvr-qualifiers here.
4328 // ObjC GC and lifetime qualifiers aren't important.
4329 Qualifiers T1Quals = T1.getQualifiers();
4330 Qualifiers T2Quals = T2.getQualifiers();
4331 T1Quals.removeObjCGCAttr();
4332 T1Quals.removeObjCLifetime();
4333 T2Quals.removeObjCGCAttr();
4334 T2Quals.removeObjCLifetime();
4335 if (!T1Quals.compatiblyIncludes(T2Quals))
4336 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004337 }
4338
4339 // If at least one of the types is a class type, the types are not
4340 // related, and we aren't allowed any user conversions, the
4341 // reference binding fails. This case is important for breaking
4342 // recursion, since TryImplicitConversion below will attempt to
4343 // create a temporary through the use of a copy constructor.
4344 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4345 (T1->isRecordType() || T2->isRecordType()))
4346 return ICS;
4347
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004348 // If T1 is reference-related to T2 and the reference is an rvalue
4349 // reference, the initializer expression shall not be an lvalue.
4350 if (RefRelationship >= Sema::Ref_Related &&
4351 isRValRef && Init->Classify(S.Context).isLValue())
4352 return ICS;
4353
Douglas Gregorabe183d2010-04-13 16:31:36 +00004354 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004355 // When a parameter of reference type is not bound directly to
4356 // an argument expression, the conversion sequence is the one
4357 // required to convert the argument expression to the
4358 // underlying type of the reference according to
4359 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4360 // to copy-initializing a temporary of the underlying type with
4361 // the argument expression. Any difference in top-level
4362 // cv-qualification is subsumed by the initialization itself
4363 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004364 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4365 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004366 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004367 /*CStyle=*/false,
4368 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004369
4370 // Of course, that's still a reference binding.
4371 if (ICS.isStandard()) {
4372 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004373 ICS.Standard.IsLvalueReference = !isRValRef;
4374 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4375 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004376 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004377 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004378 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004379 // Don't allow rvalue references to bind to lvalues.
4380 if (DeclType->isRValueReferenceType()) {
4381 if (const ReferenceType *RefType
4382 = ICS.UserDefined.ConversionFunction->getResultType()
4383 ->getAs<LValueReferenceType>()) {
4384 if (!RefType->getPointeeType()->isFunctionType()) {
4385 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4386 DeclType);
4387 return ICS;
4388 }
4389 }
4390 }
4391
Douglas Gregorabe183d2010-04-13 16:31:36 +00004392 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004393 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4394 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4395 ICS.UserDefined.After.BindsToRvalue = true;
4396 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4397 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004398 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004399
Douglas Gregorabe183d2010-04-13 16:31:36 +00004400 return ICS;
4401}
4402
Sebastian Redl5405b812011-10-16 18:19:34 +00004403static ImplicitConversionSequence
4404TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4405 bool SuppressUserConversions,
4406 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004407 bool AllowObjCWritebackConversion,
4408 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004409
4410/// TryListConversion - Try to copy-initialize a value of type ToType from the
4411/// initializer list From.
4412static ImplicitConversionSequence
4413TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4414 bool SuppressUserConversions,
4415 bool InOverloadResolution,
4416 bool AllowObjCWritebackConversion) {
4417 // C++11 [over.ics.list]p1:
4418 // When an argument is an initializer list, it is not an expression and
4419 // special rules apply for converting it to a parameter type.
4420
4421 ImplicitConversionSequence Result;
4422 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004423 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004424
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004425 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004426 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004427 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004428 return Result;
4429
Sebastian Redl5405b812011-10-16 18:19:34 +00004430 // C++11 [over.ics.list]p2:
4431 // If the parameter type is std::initializer_list<X> or "array of X" and
4432 // all the elements can be implicitly converted to X, the implicit
4433 // conversion sequence is the worst conversion necessary to convert an
4434 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004435 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004436 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004437 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004438 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004439 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004440 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004441 if (!X.isNull()) {
4442 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4443 Expr *Init = From->getInit(i);
4444 ImplicitConversionSequence ICS =
4445 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4446 InOverloadResolution,
4447 AllowObjCWritebackConversion);
4448 // If a single element isn't convertible, fail.
4449 if (ICS.isBad()) {
4450 Result = ICS;
4451 break;
4452 }
4453 // Otherwise, look for the worst conversion.
4454 if (Result.isBad() ||
4455 CompareImplicitConversionSequences(S, ICS, Result) ==
4456 ImplicitConversionSequence::Worse)
4457 Result = ICS;
4458 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004459
4460 // For an empty list, we won't have computed any conversion sequence.
4461 // Introduce the identity conversion sequence.
4462 if (From->getNumInits() == 0) {
4463 Result.setStandard();
4464 Result.Standard.setAsIdentityConversion();
4465 Result.Standard.setFromType(ToType);
4466 Result.Standard.setAllToTypes(ToType);
4467 }
4468
Sebastian Redlfe592282012-01-17 22:49:48 +00004469 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004470 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004471 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004472 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004473
4474 // C++11 [over.ics.list]p3:
4475 // Otherwise, if the parameter is a non-aggregate class X and overload
4476 // resolution chooses a single best constructor [...] the implicit
4477 // conversion sequence is a user-defined conversion sequence. If multiple
4478 // constructors are viable but none is better than the others, the
4479 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004480 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4481 // This function can deal with initializer lists.
4482 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4483 /*AllowExplicit=*/false,
4484 InOverloadResolution, /*CStyle=*/false,
4485 AllowObjCWritebackConversion);
4486 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004487 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004488 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004489
4490 // C++11 [over.ics.list]p4:
4491 // Otherwise, if the parameter has an aggregate type which can be
4492 // initialized from the initializer list [...] the implicit conversion
4493 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004494 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004495 // Type is an aggregate, argument is an init list. At this point it comes
4496 // down to checking whether the initialization works.
4497 // FIXME: Find out whether this parameter is consumed or not.
4498 InitializedEntity Entity =
4499 InitializedEntity::InitializeParameter(S.Context, ToType,
4500 /*Consumed=*/false);
4501 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4502 Result.setUserDefined();
4503 Result.UserDefined.Before.setAsIdentityConversion();
4504 // Initializer lists don't have a type.
4505 Result.UserDefined.Before.setFromType(QualType());
4506 Result.UserDefined.Before.setAllToTypes(QualType());
4507
4508 Result.UserDefined.After.setAsIdentityConversion();
4509 Result.UserDefined.After.setFromType(ToType);
4510 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004511 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004512 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004513 return Result;
4514 }
4515
4516 // C++11 [over.ics.list]p5:
4517 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004518 if (ToType->isReferenceType()) {
4519 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4520 // mention initializer lists in any way. So we go by what list-
4521 // initialization would do and try to extrapolate from that.
4522
4523 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4524
4525 // If the initializer list has a single element that is reference-related
4526 // to the parameter type, we initialize the reference from that.
4527 if (From->getNumInits() == 1) {
4528 Expr *Init = From->getInit(0);
4529
4530 QualType T2 = Init->getType();
4531
4532 // If the initializer is the address of an overloaded function, try
4533 // to resolve the overloaded function. If all goes well, T2 is the
4534 // type of the resulting function.
4535 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4536 DeclAccessPair Found;
4537 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4538 Init, ToType, false, Found))
4539 T2 = Fn->getType();
4540 }
4541
4542 // Compute some basic properties of the types and the initializer.
4543 bool dummy1 = false;
4544 bool dummy2 = false;
4545 bool dummy3 = false;
4546 Sema::ReferenceCompareResult RefRelationship
4547 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4548 dummy2, dummy3);
4549
4550 if (RefRelationship >= Sema::Ref_Related)
4551 return TryReferenceInit(S, Init, ToType,
4552 /*FIXME:*/From->getLocStart(),
4553 SuppressUserConversions,
4554 /*AllowExplicit=*/false);
4555 }
4556
4557 // Otherwise, we bind the reference to a temporary created from the
4558 // initializer list.
4559 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4560 InOverloadResolution,
4561 AllowObjCWritebackConversion);
4562 if (Result.isFailure())
4563 return Result;
4564 assert(!Result.isEllipsis() &&
4565 "Sub-initialization cannot result in ellipsis conversion.");
4566
4567 // Can we even bind to a temporary?
4568 if (ToType->isRValueReferenceType() ||
4569 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4570 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4571 Result.UserDefined.After;
4572 SCS.ReferenceBinding = true;
4573 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4574 SCS.BindsToRvalue = true;
4575 SCS.BindsToFunctionLvalue = false;
4576 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4577 SCS.ObjCLifetimeConversionBinding = false;
4578 } else
4579 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4580 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004581 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004582 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004583
4584 // C++11 [over.ics.list]p6:
4585 // Otherwise, if the parameter type is not a class:
4586 if (!ToType->isRecordType()) {
4587 // - if the initializer list has one element, the implicit conversion
4588 // sequence is the one required to convert the element to the
4589 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004590 unsigned NumInits = From->getNumInits();
4591 if (NumInits == 1)
4592 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4593 SuppressUserConversions,
4594 InOverloadResolution,
4595 AllowObjCWritebackConversion);
4596 // - if the initializer list has no elements, the implicit conversion
4597 // sequence is the identity conversion.
4598 else if (NumInits == 0) {
4599 Result.setStandard();
4600 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004601 Result.Standard.setFromType(ToType);
4602 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004603 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004604 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004605 return Result;
4606 }
4607
4608 // C++11 [over.ics.list]p7:
4609 // In all cases other than those enumerated above, no conversion is possible
4610 return Result;
4611}
4612
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004613/// TryCopyInitialization - Try to copy-initialize a value of type
4614/// ToType from the expression From. Return the implicit conversion
4615/// sequence required to pass this argument, which may be a bad
4616/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004617/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004618/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004619static ImplicitConversionSequence
4620TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004621 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004622 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004623 bool AllowObjCWritebackConversion,
4624 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004625 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4626 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4627 InOverloadResolution,AllowObjCWritebackConversion);
4628
Douglas Gregorabe183d2010-04-13 16:31:36 +00004629 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004630 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004631 /*FIXME:*/From->getLocStart(),
4632 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004633 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004634
John McCall120d63c2010-08-24 20:38:10 +00004635 return TryImplicitConversion(S, From, ToType,
4636 SuppressUserConversions,
4637 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004638 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004639 /*CStyle=*/false,
4640 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004641}
4642
Anna Zaksf3546ee2011-07-28 19:46:48 +00004643static bool TryCopyInitialization(const CanQualType FromQTy,
4644 const CanQualType ToQTy,
4645 Sema &S,
4646 SourceLocation Loc,
4647 ExprValueKind FromVK) {
4648 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4649 ImplicitConversionSequence ICS =
4650 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4651
4652 return !ICS.isBad();
4653}
4654
Douglas Gregor96176b32008-11-18 23:14:02 +00004655/// TryObjectArgumentInitialization - Try to initialize the object
4656/// parameter of the given member function (@c Method) from the
4657/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004658static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004659TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004660 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004661 CXXMethodDecl *Method,
4662 CXXRecordDecl *ActingContext) {
4663 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004664 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4665 // const volatile object.
4666 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4667 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004668 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004669
4670 // Set up the conversion sequence as a "bad" conversion, to allow us
4671 // to exit early.
4672 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004673
4674 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004675 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004676 FromType = PT->getPointeeType();
4677
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004678 // When we had a pointer, it's implicitly dereferenced, so we
4679 // better have an lvalue.
4680 assert(FromClassification.isLValue());
4681 }
4682
Anders Carlssona552f7c2009-05-01 18:34:30 +00004683 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004684
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004685 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004686 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004687 // parameter is
4688 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004689 // - "lvalue reference to cv X" for functions declared without a
4690 // ref-qualifier or with the & ref-qualifier
4691 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004692 // ref-qualifier
4693 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004694 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004695 // cv-qualification on the member function declaration.
4696 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004697 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004698 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004699 // (C++ [over.match.funcs]p5). We perform a simplified version of
4700 // reference binding here, that allows class rvalues to bind to
4701 // non-constant references.
4702
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004703 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004704 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004705 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004706 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004707 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004708 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004709 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004710 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004711 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004712
4713 // Check that we have either the same type or a derived type. It
4714 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004715 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004716 ImplicitConversionKind SecondKind;
4717 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4718 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004719 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004720 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004721 else {
John McCallb1bdc622010-02-25 01:37:24 +00004722 ICS.setBad(BadConversionSequence::unrelated_class,
4723 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004724 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004725 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004726
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004727 // Check the ref-qualifier.
4728 switch (Method->getRefQualifier()) {
4729 case RQ_None:
4730 // Do nothing; we don't care about lvalueness or rvalueness.
4731 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004732
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004733 case RQ_LValue:
4734 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4735 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004736 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004737 ImplicitParamType);
4738 return ICS;
4739 }
4740 break;
4741
4742 case RQ_RValue:
4743 if (!FromClassification.isRValue()) {
4744 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004746 ImplicitParamType);
4747 return ICS;
4748 }
4749 break;
4750 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004751
Douglas Gregor96176b32008-11-18 23:14:02 +00004752 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004753 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004754 ICS.Standard.setAsIdentityConversion();
4755 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004756 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004757 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004758 ICS.Standard.ReferenceBinding = true;
4759 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004760 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004761 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004762 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4763 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4764 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004765 return ICS;
4766}
4767
4768/// PerformObjectArgumentInitialization - Perform initialization of
4769/// the implicit object parameter for the given Method with the given
4770/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004771ExprResult
4772Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004773 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004774 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004775 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004776 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004777 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004778 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004779
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004780 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004781 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004782 FromRecordType = PT->getPointeeType();
4783 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004784 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004785 } else {
4786 FromRecordType = From->getType();
4787 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004788 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004789 }
4790
John McCall701c89e2009-12-03 04:06:58 +00004791 // Note that we always use the true parent context when performing
4792 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004793 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004794 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4795 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004796 if (ICS.isBad()) {
4797 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4798 Qualifiers FromQs = FromRecordType.getQualifiers();
4799 Qualifiers ToQs = DestType.getQualifiers();
4800 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4801 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004802 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004803 diag::err_member_function_call_bad_cvr)
4804 << Method->getDeclName() << FromRecordType << (CVR - 1)
4805 << From->getSourceRange();
4806 Diag(Method->getLocation(), diag::note_previous_decl)
4807 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004808 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004809 }
4810 }
4811
Daniel Dunbar96a00142012-03-09 18:35:03 +00004812 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004813 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004814 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004815 }
Mike Stump1eb44332009-09-09 15:08:12 +00004816
John Wiegley429bb272011-04-08 18:41:53 +00004817 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4818 ExprResult FromRes =
4819 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4820 if (FromRes.isInvalid())
4821 return ExprError();
4822 From = FromRes.take();
4823 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004824
Douglas Gregor5fccd362010-03-03 23:55:11 +00004825 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004826 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004827 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004828 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004829}
4830
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004831/// TryContextuallyConvertToBool - Attempt to contextually convert the
4832/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004833static ImplicitConversionSequence
4834TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004835 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004836 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004837 // FIXME: Are these flags correct?
4838 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004839 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004840 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004841 /*CStyle=*/false,
4842 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004843}
4844
4845/// PerformContextuallyConvertToBool - Perform a contextual conversion
4846/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004847ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004848 if (checkPlaceholderForOverload(*this, From))
4849 return ExprError();
4850
John McCall120d63c2010-08-24 20:38:10 +00004851 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004852 if (!ICS.isBad())
4853 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004854
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004855 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004856 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004857 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004858 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004859 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004860}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004861
Richard Smith8ef7b202012-01-18 23:55:52 +00004862/// Check that the specified conversion is permitted in a converted constant
4863/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4864/// is acceptable.
4865static bool CheckConvertedConstantConversions(Sema &S,
4866 StandardConversionSequence &SCS) {
4867 // Since we know that the target type is an integral or unscoped enumeration
4868 // type, most conversion kinds are impossible. All possible First and Third
4869 // conversions are fine.
4870 switch (SCS.Second) {
4871 case ICK_Identity:
4872 case ICK_Integral_Promotion:
4873 case ICK_Integral_Conversion:
Guy Benyei6959acd2013-02-07 16:05:33 +00004874 case ICK_Zero_Event_Conversion:
Richard Smith8ef7b202012-01-18 23:55:52 +00004875 return true;
4876
4877 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004878 // Conversion from an integral or unscoped enumeration type to bool is
4879 // classified as ICK_Boolean_Conversion, but it's also an integral
4880 // conversion, so it's permitted in a converted constant expression.
4881 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4882 SCS.getToType(2)->isBooleanType();
4883
Richard Smith8ef7b202012-01-18 23:55:52 +00004884 case ICK_Floating_Integral:
4885 case ICK_Complex_Real:
4886 return false;
4887
4888 case ICK_Lvalue_To_Rvalue:
4889 case ICK_Array_To_Pointer:
4890 case ICK_Function_To_Pointer:
4891 case ICK_NoReturn_Adjustment:
4892 case ICK_Qualification:
4893 case ICK_Compatible_Conversion:
4894 case ICK_Vector_Conversion:
4895 case ICK_Vector_Splat:
4896 case ICK_Derived_To_Base:
4897 case ICK_Pointer_Conversion:
4898 case ICK_Pointer_Member:
4899 case ICK_Block_Pointer_Conversion:
4900 case ICK_Writeback_Conversion:
4901 case ICK_Floating_Promotion:
4902 case ICK_Complex_Promotion:
4903 case ICK_Complex_Conversion:
4904 case ICK_Floating_Conversion:
4905 case ICK_TransparentUnionConversion:
4906 llvm_unreachable("unexpected second conversion kind");
4907
4908 case ICK_Num_Conversion_Kinds:
4909 break;
4910 }
4911
4912 llvm_unreachable("unknown conversion kind");
4913}
4914
4915/// CheckConvertedConstantExpression - Check that the expression From is a
4916/// converted constant expression of type T, perform the conversion and produce
4917/// the converted expression, per C++11 [expr.const]p3.
4918ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4919 llvm::APSInt &Value,
4920 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004921 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004922 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4923
4924 if (checkPlaceholderForOverload(*this, From))
4925 return ExprError();
4926
4927 // C++11 [expr.const]p3 with proposed wording fixes:
4928 // A converted constant expression of type T is a core constant expression,
4929 // implicitly converted to a prvalue of type T, where the converted
4930 // expression is a literal constant expression and the implicit conversion
4931 // sequence contains only user-defined conversions, lvalue-to-rvalue
4932 // conversions, integral promotions, and integral conversions other than
4933 // narrowing conversions.
4934 ImplicitConversionSequence ICS =
4935 TryImplicitConversion(From, T,
4936 /*SuppressUserConversions=*/false,
4937 /*AllowExplicit=*/false,
4938 /*InOverloadResolution=*/false,
4939 /*CStyle=*/false,
4940 /*AllowObjcWritebackConversion=*/false);
4941 StandardConversionSequence *SCS = 0;
4942 switch (ICS.getKind()) {
4943 case ImplicitConversionSequence::StandardConversion:
4944 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004945 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004946 diag::err_typecheck_converted_constant_expression_disallowed)
4947 << From->getType() << From->getSourceRange() << T;
4948 SCS = &ICS.Standard;
4949 break;
4950 case ImplicitConversionSequence::UserDefinedConversion:
4951 // We are converting from class type to an integral or enumeration type, so
4952 // the Before sequence must be trivial.
4953 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004954 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004955 diag::err_typecheck_converted_constant_expression_disallowed)
4956 << From->getType() << From->getSourceRange() << T;
4957 SCS = &ICS.UserDefined.After;
4958 break;
4959 case ImplicitConversionSequence::AmbiguousConversion:
4960 case ImplicitConversionSequence::BadConversion:
4961 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004962 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004963 diag::err_typecheck_converted_constant_expression)
4964 << From->getType() << From->getSourceRange() << T;
4965 return ExprError();
4966
4967 case ImplicitConversionSequence::EllipsisConversion:
4968 llvm_unreachable("ellipsis conversion in converted constant expression");
4969 }
4970
4971 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4972 if (Result.isInvalid())
4973 return Result;
4974
4975 // Check for a narrowing implicit conversion.
4976 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004977 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004978 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4979 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004980 case NK_Variable_Narrowing:
4981 // Implicit conversion to a narrower type, and the value is not a constant
4982 // expression. We'll diagnose this in a moment.
4983 case NK_Not_Narrowing:
4984 break;
4985
4986 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004987 Diag(From->getLocStart(),
4988 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4989 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004990 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004991 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004992 break;
4993
4994 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004995 Diag(From->getLocStart(),
4996 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4997 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004998 << CCE << /*Constant*/0 << From->getType() << T;
4999 break;
5000 }
5001
5002 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005003 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00005004 Expr::EvalResult Eval;
5005 Eval.Diag = &Notes;
5006
Douglas Gregor484f6fa2013-04-08 23:24:07 +00005007 if (!Result.get()->EvaluateAsRValue(Eval, Context) || !Eval.Val.isInt()) {
Richard Smith8ef7b202012-01-18 23:55:52 +00005008 // The expression can't be folded, so we can't keep it at this position in
5009 // the AST.
5010 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005011 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005012 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005013
5014 if (Notes.empty()) {
5015 // It's a constant expression.
5016 return Result;
5017 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005018 }
5019
5020 // It's not a constant expression. Produce an appropriate diagnostic.
5021 if (Notes.size() == 1 &&
5022 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5023 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5024 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005025 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005026 << CCE << From->getSourceRange();
5027 for (unsigned I = 0; I < Notes.size(); ++I)
5028 Diag(Notes[I].first, Notes[I].second);
5029 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005030 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005031}
5032
John McCall0bcc9bc2011-09-09 06:11:02 +00005033/// dropPointerConversions - If the given standard conversion sequence
5034/// involves any pointer conversions, remove them. This may change
5035/// the result type of the conversion sequence.
5036static void dropPointerConversion(StandardConversionSequence &SCS) {
5037 if (SCS.Second == ICK_Pointer_Conversion) {
5038 SCS.Second = ICK_Identity;
5039 SCS.Third = ICK_Identity;
5040 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5041 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005042}
John McCall120d63c2010-08-24 20:38:10 +00005043
John McCall0bcc9bc2011-09-09 06:11:02 +00005044/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5045/// convert the expression From to an Objective-C pointer type.
5046static ImplicitConversionSequence
5047TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5048 // Do an implicit conversion to 'id'.
5049 QualType Ty = S.Context.getObjCIdType();
5050 ImplicitConversionSequence ICS
5051 = TryImplicitConversion(S, From, Ty,
5052 // FIXME: Are these flags correct?
5053 /*SuppressUserConversions=*/false,
5054 /*AllowExplicit=*/true,
5055 /*InOverloadResolution=*/false,
5056 /*CStyle=*/false,
5057 /*AllowObjCWritebackConversion=*/false);
5058
5059 // Strip off any final conversions to 'id'.
5060 switch (ICS.getKind()) {
5061 case ImplicitConversionSequence::BadConversion:
5062 case ImplicitConversionSequence::AmbiguousConversion:
5063 case ImplicitConversionSequence::EllipsisConversion:
5064 break;
5065
5066 case ImplicitConversionSequence::UserDefinedConversion:
5067 dropPointerConversion(ICS.UserDefined.After);
5068 break;
5069
5070 case ImplicitConversionSequence::StandardConversion:
5071 dropPointerConversion(ICS.Standard);
5072 break;
5073 }
5074
5075 return ICS;
5076}
5077
5078/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5079/// conversion of the expression From to an Objective-C pointer type.
5080ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005081 if (checkPlaceholderForOverload(*this, From))
5082 return ExprError();
5083
John McCallc12c5bb2010-05-15 11:32:37 +00005084 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005085 ImplicitConversionSequence ICS =
5086 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005087 if (!ICS.isBad())
5088 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005089 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005090}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005091
Richard Smithf39aec12012-02-04 07:07:42 +00005092/// Determine whether the provided type is an integral type, or an enumeration
5093/// type of a permitted flavor.
Richard Smith097e0a22013-05-21 19:05:48 +00005094bool Sema::ICEConvertDiagnoser::match(QualType T) {
5095 return AllowScopedEnumerations ? T->isIntegralOrEnumerationType()
5096 : T->isIntegralOrUnscopedEnumerationType();
Richard Smithf39aec12012-02-04 07:07:42 +00005097}
5098
Larisse Voufo50b60b32013-06-10 06:50:24 +00005099static ExprResult
5100diagnoseAmbiguousConversion(Sema &SemaRef, SourceLocation Loc, Expr *From,
5101 Sema::ContextualImplicitConverter &Converter,
5102 QualType T, UnresolvedSetImpl &ViableConversions) {
5103
5104 if (Converter.Suppress)
5105 return ExprError();
5106
5107 Converter.diagnoseAmbiguous(SemaRef, Loc, T) << From->getSourceRange();
5108 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5109 CXXConversionDecl *Conv =
5110 cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5111 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5112 Converter.noteAmbiguous(SemaRef, Conv, ConvTy);
5113 }
5114 return SemaRef.Owned(From);
5115}
5116
5117static bool
5118diagnoseNoViableConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5119 Sema::ContextualImplicitConverter &Converter,
5120 QualType T, bool HadMultipleCandidates,
5121 UnresolvedSetImpl &ExplicitConversions) {
5122 if (ExplicitConversions.size() == 1 && !Converter.Suppress) {
5123 DeclAccessPair Found = ExplicitConversions[0];
5124 CXXConversionDecl *Conversion =
5125 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5126
5127 // The user probably meant to invoke the given explicit
5128 // conversion; use it.
5129 QualType ConvTy = Conversion->getConversionType().getNonReferenceType();
5130 std::string TypeStr;
5131 ConvTy.getAsStringInternal(TypeStr, SemaRef.getPrintingPolicy());
5132
5133 Converter.diagnoseExplicitConv(SemaRef, Loc, T, ConvTy)
5134 << FixItHint::CreateInsertion(From->getLocStart(),
5135 "static_cast<" + TypeStr + ">(")
5136 << FixItHint::CreateInsertion(
5137 SemaRef.PP.getLocForEndOfToken(From->getLocEnd()), ")");
5138 Converter.noteExplicitConv(SemaRef, Conversion, ConvTy);
5139
5140 // If we aren't in a SFINAE context, build a call to the
5141 // explicit conversion function.
5142 if (SemaRef.isSFINAEContext())
5143 return true;
5144
5145 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5146 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5147 HadMultipleCandidates);
5148 if (Result.isInvalid())
5149 return true;
5150 // Record usage of conversion in an implicit cast.
5151 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5152 CK_UserDefinedConversion, Result.get(), 0,
5153 Result.get()->getValueKind());
5154 }
5155 return false;
5156}
5157
5158static bool recordConversion(Sema &SemaRef, SourceLocation Loc, Expr *&From,
5159 Sema::ContextualImplicitConverter &Converter,
5160 QualType T, bool HadMultipleCandidates,
5161 DeclAccessPair &Found) {
5162 CXXConversionDecl *Conversion =
5163 cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5164 SemaRef.CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
5165
5166 QualType ToType = Conversion->getConversionType().getNonReferenceType();
5167 if (!Converter.SuppressConversion) {
5168 if (SemaRef.isSFINAEContext())
5169 return true;
5170
5171 Converter.diagnoseConversion(SemaRef, Loc, T, ToType)
5172 << From->getSourceRange();
5173 }
5174
5175 ExprResult Result = SemaRef.BuildCXXMemberCallExpr(From, Found, Conversion,
5176 HadMultipleCandidates);
5177 if (Result.isInvalid())
5178 return true;
5179 // Record usage of conversion in an implicit cast.
5180 From = ImplicitCastExpr::Create(SemaRef.Context, Result.get()->getType(),
5181 CK_UserDefinedConversion, Result.get(), 0,
5182 Result.get()->getValueKind());
5183 return false;
5184}
5185
5186static ExprResult finishContextualImplicitConversion(
5187 Sema &SemaRef, SourceLocation Loc, Expr *From,
5188 Sema::ContextualImplicitConverter &Converter) {
5189 if (!Converter.match(From->getType()) && !Converter.Suppress)
5190 Converter.diagnoseNoMatch(SemaRef, Loc, From->getType())
5191 << From->getSourceRange();
5192
5193 return SemaRef.DefaultLvalueConversion(From);
5194}
5195
5196static void
5197collectViableConversionCandidates(Sema &SemaRef, Expr *From, QualType ToType,
5198 UnresolvedSetImpl &ViableConversions,
5199 OverloadCandidateSet &CandidateSet) {
5200 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5201 DeclAccessPair FoundDecl = ViableConversions[I];
5202 NamedDecl *D = FoundDecl.getDecl();
5203 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
5204 if (isa<UsingShadowDecl>(D))
5205 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5206
5207 CXXConversionDecl *Conv;
5208 FunctionTemplateDecl *ConvTemplate;
5209 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
5210 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5211 else
5212 Conv = cast<CXXConversionDecl>(D);
5213
5214 if (ConvTemplate)
5215 SemaRef.AddTemplateConversionCandidate(
5216 ConvTemplate, FoundDecl, ActingContext, From, ToType, CandidateSet);
5217 else
5218 SemaRef.AddConversionCandidate(Conv, FoundDecl, ActingContext, From,
5219 ToType, CandidateSet);
5220 }
5221}
5222
Richard Smith097e0a22013-05-21 19:05:48 +00005223/// \brief Attempt to convert the given expression to a type which is accepted
5224/// by the given converter.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005225///
Richard Smith097e0a22013-05-21 19:05:48 +00005226/// This routine will attempt to convert an expression of class type to a
5227/// type accepted by the specified converter. In C++11 and before, the class
5228/// must have a single non-explicit conversion function converting to a matching
5229/// type. In C++1y, there can be multiple such conversion functions, but only
5230/// one target type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005231///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005232/// \param Loc The source location of the construct that requires the
5233/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005234///
James Dennett40ae6662012-06-22 08:52:37 +00005235/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005236///
Richard Smith097e0a22013-05-21 19:05:48 +00005237/// \param Converter Used to control and diagnose the conversion process.
Richard Smithf39aec12012-02-04 07:07:42 +00005238///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005239/// \returns The expression, converted to an integral or enumeration type if
5240/// successful.
Richard Smith097e0a22013-05-21 19:05:48 +00005241ExprResult Sema::PerformContextualImplicitConversion(
5242 SourceLocation Loc, Expr *From, ContextualImplicitConverter &Converter) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005243 // We can't perform any more checking for type-dependent expressions.
5244 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005245 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005246
Eli Friedmanceccab92012-01-26 00:26:18 +00005247 // Process placeholders immediately.
5248 if (From->hasPlaceholderType()) {
5249 ExprResult result = CheckPlaceholderExpr(From);
Larisse Voufo50b60b32013-06-10 06:50:24 +00005250 if (result.isInvalid())
5251 return result;
Eli Friedmanceccab92012-01-26 00:26:18 +00005252 From = result.take();
5253 }
5254
Richard Smith097e0a22013-05-21 19:05:48 +00005255 // If the expression already has a matching type, we're golden.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005256 QualType T = From->getType();
Richard Smith097e0a22013-05-21 19:05:48 +00005257 if (Converter.match(T))
Eli Friedmanceccab92012-01-26 00:26:18 +00005258 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005259
5260 // FIXME: Check for missing '()' if T is a function type?
5261
Richard Smith097e0a22013-05-21 19:05:48 +00005262 // We can only perform contextual implicit conversions on objects of class
5263 // type.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005264 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005265 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith097e0a22013-05-21 19:05:48 +00005266 if (!Converter.Suppress)
5267 Converter.diagnoseNoMatch(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005268 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005269 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005270
Douglas Gregorc30614b2010-06-29 23:17:37 +00005271 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005272 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Richard Smith097e0a22013-05-21 19:05:48 +00005273 ContextualImplicitConverter &Converter;
Douglas Gregorab41fe92012-05-04 22:38:52 +00005274 Expr *From;
Richard Smith097e0a22013-05-21 19:05:48 +00005275
5276 TypeDiagnoserPartialDiag(ContextualImplicitConverter &Converter, Expr *From)
5277 : TypeDiagnoser(Converter.Suppress), Converter(Converter), From(From) {}
5278
Douglas Gregord10099e2012-05-04 16:32:21 +00005279 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Richard Smith097e0a22013-05-21 19:05:48 +00005280 Converter.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005281 }
Richard Smith097e0a22013-05-21 19:05:48 +00005282 } IncompleteDiagnoser(Converter, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005283
5284 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005285 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005286
Douglas Gregorc30614b2010-06-29 23:17:37 +00005287 // Look for a conversion to an integral or enumeration type.
Larisse Voufo50b60b32013-06-10 06:50:24 +00005288 UnresolvedSet<4>
5289 ViableConversions; // These are *potentially* viable in C++1y.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005290 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005291 std::pair<CXXRecordDecl::conversion_iterator,
Larisse Voufo50b60b32013-06-10 06:50:24 +00005292 CXXRecordDecl::conversion_iterator> Conversions =
5293 cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005294
Larisse Voufo50b60b32013-06-10 06:50:24 +00005295 bool HadMultipleCandidates =
5296 (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005297
Larisse Voufo50b60b32013-06-10 06:50:24 +00005298 // To check that there is only one target type, in C++1y:
5299 QualType ToType;
5300 bool HasUniqueTargetType = true;
5301
5302 // Collect explicit or viable (potentially in C++1y) conversions.
5303 for (CXXRecordDecl::conversion_iterator I = Conversions.first,
5304 E = Conversions.second;
5305 I != E; ++I) {
5306 NamedDecl *D = (*I)->getUnderlyingDecl();
5307 CXXConversionDecl *Conversion;
5308 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(D);
5309 if (ConvTemplate) {
5310 if (getLangOpts().CPlusPlus1y)
5311 Conversion = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
5312 else
5313 continue; // C++11 does not consider conversion operator templates(?).
5314 } else
5315 Conversion = cast<CXXConversionDecl>(D);
5316
5317 assert((!ConvTemplate || getLangOpts().CPlusPlus1y) &&
5318 "Conversion operator templates are considered potentially "
5319 "viable in C++1y");
5320
5321 QualType CurToType = Conversion->getConversionType().getNonReferenceType();
5322 if (Converter.match(CurToType) || ConvTemplate) {
5323
5324 if (Conversion->isExplicit()) {
5325 // FIXME: For C++1y, do we need this restriction?
5326 // cf. diagnoseNoViableConversion()
5327 if (!ConvTemplate)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005328 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
Larisse Voufo50b60b32013-06-10 06:50:24 +00005329 } else {
5330 if (!ConvTemplate && getLangOpts().CPlusPlus1y) {
5331 if (ToType.isNull())
5332 ToType = CurToType.getUnqualifiedType();
5333 else if (HasUniqueTargetType &&
5334 (CurToType.getUnqualifiedType() != ToType))
5335 HasUniqueTargetType = false;
5336 }
5337 ViableConversions.addDecl(I.getDecl(), I.getAccess());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005338 }
Richard Smithf39aec12012-02-04 07:07:42 +00005339 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005340 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005341
Larisse Voufo50b60b32013-06-10 06:50:24 +00005342 if (getLangOpts().CPlusPlus1y) {
5343 // C++1y [conv]p6:
5344 // ... An expression e of class type E appearing in such a context
5345 // is said to be contextually implicitly converted to a specified
5346 // type T and is well-formed if and only if e can be implicitly
5347 // converted to a type T that is determined as follows: E is searched
Larisse Voufo7acc5a62013-06-10 08:25:58 +00005348 // for conversion functions whose return type is cv T or reference to
5349 // cv T such that T is allowed by the context. There shall be
Larisse Voufo50b60b32013-06-10 06:50:24 +00005350 // exactly one such T.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005351
Larisse Voufo50b60b32013-06-10 06:50:24 +00005352 // If no unique T is found:
5353 if (ToType.isNull()) {
5354 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5355 HadMultipleCandidates,
5356 ExplicitConversions))
Douglas Gregorc30614b2010-06-29 23:17:37 +00005357 return ExprError();
Larisse Voufo50b60b32013-06-10 06:50:24 +00005358 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005359 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005360
Larisse Voufo50b60b32013-06-10 06:50:24 +00005361 // If more than one unique Ts are found:
5362 if (!HasUniqueTargetType)
5363 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5364 ViableConversions);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005365
Larisse Voufo50b60b32013-06-10 06:50:24 +00005366 // If one unique T is found:
5367 // First, build a candidate set from the previously recorded
5368 // potentially viable conversions.
5369 OverloadCandidateSet CandidateSet(Loc);
5370 collectViableConversionCandidates(*this, From, ToType, ViableConversions,
5371 CandidateSet);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005372
Larisse Voufo50b60b32013-06-10 06:50:24 +00005373 // Then, perform overload resolution over the candidate set.
5374 OverloadCandidateSet::iterator Best;
5375 switch (CandidateSet.BestViableFunction(*this, Loc, Best)) {
5376 case OR_Success: {
5377 // Apply this conversion.
5378 DeclAccessPair Found =
5379 DeclAccessPair::make(Best->Function, Best->FoundDecl.getAccess());
5380 if (recordConversion(*this, Loc, From, Converter, T,
5381 HadMultipleCandidates, Found))
5382 return ExprError();
5383 break;
5384 }
5385 case OR_Ambiguous:
5386 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5387 ViableConversions);
5388 case OR_No_Viable_Function:
5389 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5390 HadMultipleCandidates,
5391 ExplicitConversions))
5392 return ExprError();
5393 // fall through 'OR_Deleted' case.
5394 case OR_Deleted:
5395 // We'll complain below about a non-integral condition type.
5396 break;
5397 }
5398 } else {
5399 switch (ViableConversions.size()) {
5400 case 0: {
5401 if (diagnoseNoViableConversion(*this, Loc, From, Converter, T,
5402 HadMultipleCandidates,
5403 ExplicitConversions))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005404 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005405
Larisse Voufo50b60b32013-06-10 06:50:24 +00005406 // We'll complain below about a non-integral condition type.
5407 break;
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005408 }
Larisse Voufo50b60b32013-06-10 06:50:24 +00005409 case 1: {
5410 // Apply this conversion.
5411 DeclAccessPair Found = ViableConversions[0];
5412 if (recordConversion(*this, Loc, From, Converter, T,
5413 HadMultipleCandidates, Found))
5414 return ExprError();
5415 break;
5416 }
5417 default:
5418 return diagnoseAmbiguousConversion(*this, Loc, From, Converter, T,
5419 ViableConversions);
5420 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005422
Larisse Voufo50b60b32013-06-10 06:50:24 +00005423 return finishContextualImplicitConversion(*this, Loc, From, Converter);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005424}
5425
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005426/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005427/// candidate functions, using the given function call arguments. If
5428/// @p SuppressUserConversions, then don't allow user-defined
5429/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005430///
James Dennett699c9042012-06-15 07:13:21 +00005431/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005432/// based on an incomplete set of function arguments. This feature is used by
5433/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005434void
5435Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005436 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005437 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005438 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005439 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005440 bool PartialOverloading,
5441 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005442 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005443 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005444 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005445 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005446 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005447
Douglas Gregor88a35142008-12-22 05:46:06 +00005448 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005449 if (!isa<CXXConstructorDecl>(Method)) {
5450 // If we get here, it's because we're calling a member function
5451 // that is named without a member access expression (e.g.,
5452 // "this->f") that was either written explicitly or created
5453 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005454 // function, e.g., X::f(). We use an empty type for the implied
5455 // object argument (C++ [over.call.func]p3), and the acting context
5456 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005457 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005458 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005459 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005460 return;
5461 }
5462 // We treat a constructor like a non-member function, since its object
5463 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005464 }
5465
Douglas Gregorfd476482009-11-13 23:59:09 +00005466 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005467 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005468
Douglas Gregor7edfb692009-11-23 12:27:39 +00005469 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005470 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005471
Douglas Gregor66724ea2009-11-14 01:20:54 +00005472 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5473 // C++ [class.copy]p3:
5474 // A member function template is never instantiated to perform the copy
5475 // of a class object to an object of its class type.
5476 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005477 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005478 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005479 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5480 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005481 return;
5482 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005483
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005484 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005485 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005486 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005487 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005488 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005489 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005490 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005491 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005492
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005493 unsigned NumArgsInProto = Proto->getNumArgs();
5494
5495 // (C++ 13.3.2p2): A candidate function having fewer than m
5496 // parameters is viable only if it has an ellipsis in its parameter
5497 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005498 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005499 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005500 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005501 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005502 return;
5503 }
5504
5505 // (C++ 13.3.2p2): A candidate function having more than m parameters
5506 // is viable only if the (m+1)st parameter has a default argument
5507 // (8.3.6). For the purposes of overload resolution, the
5508 // parameter list is truncated on the right, so that there are
5509 // exactly m parameters.
5510 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005511 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005512 // Not enough arguments.
5513 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005514 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005515 return;
5516 }
5517
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005518 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005519 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005520 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5521 if (CheckCUDATarget(Caller, Function)) {
5522 Candidate.Viable = false;
5523 Candidate.FailureKind = ovl_fail_bad_target;
5524 return;
5525 }
5526
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005527 // Determine the implicit conversion sequences for each of the
5528 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005529 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005530 if (ArgIdx < NumArgsInProto) {
5531 // (C++ 13.3.2p3): for F to be a viable function, there shall
5532 // exist for each argument an implicit conversion sequence
5533 // (13.3.3.1) that converts that argument to the corresponding
5534 // parameter of F.
5535 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005536 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005537 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005538 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005539 /*InOverloadResolution=*/true,
5540 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005541 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005542 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005543 if (Candidate.Conversions[ArgIdx].isBad()) {
5544 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005545 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005546 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005547 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005548 } else {
5549 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5550 // argument for which there is no corresponding parameter is
5551 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005552 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005553 }
5554 }
5555}
5556
Douglas Gregor063daf62009-03-13 18:40:31 +00005557/// \brief Add all of the function declarations in the given function set to
5558/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005559void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005560 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005561 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005562 bool SuppressUserConversions,
5563 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005564 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005565 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5566 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005567 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005568 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005569 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005570 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005571 Args.slice(1), CandidateSet,
5572 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005573 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005574 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005575 SuppressUserConversions);
5576 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005577 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005578 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5579 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005580 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005581 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005582 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005583 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005584 Args[0]->Classify(Context), Args.slice(1),
5585 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005586 else
John McCall9aa472c2010-03-19 07:35:19 +00005587 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005588 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005589 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005590 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005591 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005592}
5593
John McCall314be4e2009-11-17 07:50:12 +00005594/// AddMethodCandidate - Adds a named decl (which is some kind of
5595/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005596void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005597 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005598 Expr::Classification ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005599 ArrayRef<Expr *> Args,
John McCall314be4e2009-11-17 07:50:12 +00005600 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005601 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005602 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005603 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005604
5605 if (isa<UsingShadowDecl>(Decl))
5606 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005607
John McCall314be4e2009-11-17 07:50:12 +00005608 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5609 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5610 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005611 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5612 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005613 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005614 Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005615 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005616 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005617 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005618 ObjectType, ObjectClassification,
Rafael Espindola548107e2013-04-29 19:29:25 +00005619 Args,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005620 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005621 }
5622}
5623
Douglas Gregor96176b32008-11-18 23:14:02 +00005624/// AddMethodCandidate - Adds the given C++ member function to the set
5625/// of candidate functions, using the given function call arguments
5626/// and the object argument (@c Object). For example, in a call
5627/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5628/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5629/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005630/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005631void
John McCall9aa472c2010-03-19 07:35:19 +00005632Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005633 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005634 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005635 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005636 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005637 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005638 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005639 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005640 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005641 assert(!isa<CXXConstructorDecl>(Method) &&
5642 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005643
Douglas Gregor3f396022009-09-28 04:47:19 +00005644 if (!CandidateSet.isNewCandidate(Method))
5645 return;
5646
Douglas Gregor7edfb692009-11-23 12:27:39 +00005647 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005648 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005649
Douglas Gregor96176b32008-11-18 23:14:02 +00005650 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005651 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005652 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005653 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005654 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005655 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005656 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005657
5658 unsigned NumArgsInProto = Proto->getNumArgs();
5659
5660 // (C++ 13.3.2p2): A candidate function having fewer than m
5661 // parameters is viable only if it has an ellipsis in its parameter
5662 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005663 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005664 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005665 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005666 return;
5667 }
5668
5669 // (C++ 13.3.2p2): A candidate function having more than m parameters
5670 // is viable only if the (m+1)st parameter has a default argument
5671 // (8.3.6). For the purposes of overload resolution, the
5672 // parameter list is truncated on the right, so that there are
5673 // exactly m parameters.
5674 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005675 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005676 // Not enough arguments.
5677 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005678 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005679 return;
5680 }
5681
5682 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005683
John McCall701c89e2009-12-03 04:06:58 +00005684 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005685 // The implicit object argument is ignored.
5686 Candidate.IgnoreObjectArgument = true;
5687 else {
5688 // Determine the implicit conversion sequence for the object
5689 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005690 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005691 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5692 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005693 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005694 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005695 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005696 return;
5697 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005698 }
5699
5700 // Determine the implicit conversion sequences for each of the
5701 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005702 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005703 if (ArgIdx < NumArgsInProto) {
5704 // (C++ 13.3.2p3): for F to be a viable function, there shall
5705 // exist for each argument an implicit conversion sequence
5706 // (13.3.3.1) that converts that argument to the corresponding
5707 // parameter of F.
5708 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005709 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005710 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005711 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005712 /*InOverloadResolution=*/true,
5713 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005714 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005715 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005716 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005717 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005718 break;
5719 }
5720 } else {
5721 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5722 // argument for which there is no corresponding parameter is
5723 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005724 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005725 }
5726 }
5727}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005728
Douglas Gregor6b906862009-08-21 00:16:32 +00005729/// \brief Add a C++ member function template as a candidate to the candidate
5730/// set, using template argument deduction to produce an appropriate member
5731/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005732void
Douglas Gregor6b906862009-08-21 00:16:32 +00005733Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005734 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005735 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005736 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005737 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005738 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005739 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005740 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005741 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005742 if (!CandidateSet.isNewCandidate(MethodTmpl))
5743 return;
5744
Douglas Gregor6b906862009-08-21 00:16:32 +00005745 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005746 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005747 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005748 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005749 // candidate functions in the usual way.113) A given name can refer to one
5750 // or more function templates and also to a set of overloaded non-template
5751 // functions. In such a case, the candidate functions generated from each
5752 // function template are combined with the set of non-template candidate
5753 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005754 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005755 FunctionDecl *Specialization = 0;
5756 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005757 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5758 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005759 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005760 Candidate.FoundDecl = FoundDecl;
5761 Candidate.Function = MethodTmpl->getTemplatedDecl();
5762 Candidate.Viable = false;
5763 Candidate.FailureKind = ovl_fail_bad_deduction;
5764 Candidate.IsSurrogate = false;
5765 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005766 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005767 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005768 Info);
5769 return;
5770 }
Mike Stump1eb44332009-09-09 15:08:12 +00005771
Douglas Gregor6b906862009-08-21 00:16:32 +00005772 // Add the function template specialization produced by template argument
5773 // deduction as a candidate.
5774 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005775 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005776 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005777 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005778 ActingContext, ObjectType, ObjectClassification, Args,
5779 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005780}
5781
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005782/// \brief Add a C++ function template specialization as a candidate
5783/// in the candidate set, using template argument deduction to produce
5784/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005785void
Douglas Gregore53060f2009-06-25 22:08:12 +00005786Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005787 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005788 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005789 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005790 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005791 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005792 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5793 return;
5794
Douglas Gregore53060f2009-06-25 22:08:12 +00005795 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005796 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005797 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005798 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005799 // candidate functions in the usual way.113) A given name can refer to one
5800 // or more function templates and also to a set of overloaded non-template
5801 // functions. In such a case, the candidate functions generated from each
5802 // function template are combined with the set of non-template candidate
5803 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005804 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005805 FunctionDecl *Specialization = 0;
5806 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005807 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5808 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005809 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005810 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005811 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5812 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005813 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005814 Candidate.IsSurrogate = false;
5815 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005816 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005817 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005818 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005819 return;
5820 }
Mike Stump1eb44332009-09-09 15:08:12 +00005821
Douglas Gregore53060f2009-06-25 22:08:12 +00005822 // Add the function template specialization produced by template argument
5823 // deduction as a candidate.
5824 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005825 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005826 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005827}
Mike Stump1eb44332009-09-09 15:08:12 +00005828
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005829/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005830/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005831/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005832/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005833/// (which may or may not be the same type as the type that the
5834/// conversion function produces).
5835void
5836Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005837 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005838 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005839 Expr *From, QualType ToType,
5840 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005841 assert(!Conversion->getDescribedFunctionTemplate() &&
5842 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005843 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005844 if (!CandidateSet.isNewCandidate(Conversion))
5845 return;
5846
Richard Smith60e141e2013-05-04 07:00:32 +00005847 // If the conversion function has an undeduced return type, trigger its
5848 // deduction now.
5849 if (getLangOpts().CPlusPlus1y && ConvType->isUndeducedType()) {
5850 if (DeduceReturnType(Conversion, From->getExprLoc()))
5851 return;
5852 ConvType = Conversion->getConversionType().getNonReferenceType();
5853 }
5854
Douglas Gregor7edfb692009-11-23 12:27:39 +00005855 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005856 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005857
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005858 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005859 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005860 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005861 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005862 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005863 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005864 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005865 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005866 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005867 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005868 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005869
Douglas Gregorbca39322010-08-19 15:37:02 +00005870 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005871 // For conversion functions, the function is considered to be a member of
5872 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005873 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005874 //
5875 // Determine the implicit conversion sequence for the implicit
5876 // object parameter.
5877 QualType ImplicitParamType = From->getType();
5878 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5879 ImplicitParamType = FromPtrType->getPointeeType();
5880 CXXRecordDecl *ConversionContext
5881 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005882
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005883 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005884 = TryObjectArgumentInitialization(*this, From->getType(),
5885 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005886 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005887
John McCall1d318332010-01-12 00:44:57 +00005888 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005889 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005890 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005891 return;
5892 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005893
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005894 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005895 // derived to base as such conversions are given Conversion Rank. They only
5896 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5897 QualType FromCanon
5898 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5899 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5900 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5901 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005902 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005903 return;
5904 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005905
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005906 // To determine what the conversion from the result of calling the
5907 // conversion function to the type we're eventually trying to
5908 // convert to (ToType), we need to synthesize a call to the
5909 // conversion function and attempt copy initialization from it. This
5910 // makes sure that we get the right semantics with respect to
5911 // lvalues/rvalues and the type. Fortunately, we can allocate this
5912 // call on the stack and we don't need its arguments to be
5913 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005914 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005915 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005916 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5917 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005918 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005919 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005920
Richard Smith87c1f1f2011-07-13 22:53:21 +00005921 QualType ConversionType = Conversion->getConversionType();
5922 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005923 Candidate.Viable = false;
5924 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5925 return;
5926 }
5927
Richard Smith87c1f1f2011-07-13 22:53:21 +00005928 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005929
Mike Stump1eb44332009-09-09 15:08:12 +00005930 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005931 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5932 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005933 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Dmitri Gribenko62ed8892013-05-05 20:40:26 +00005934 CallExpr Call(Context, &ConversionFn, None, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005935 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005936 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005937 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005938 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005939 /*InOverloadResolution=*/false,
5940 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005941
John McCall1d318332010-01-12 00:44:57 +00005942 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005943 case ImplicitConversionSequence::StandardConversion:
5944 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005945
Douglas Gregorc520c842010-04-12 23:42:09 +00005946 // C++ [over.ics.user]p3:
5947 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005948 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005949 // shall have exact match rank.
5950 if (Conversion->getPrimaryTemplate() &&
5951 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5952 Candidate.Viable = false;
5953 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5954 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005955
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005956 // C++0x [dcl.init.ref]p5:
5957 // In the second case, if the reference is an rvalue reference and
5958 // the second standard conversion sequence of the user-defined
5959 // conversion sequence includes an lvalue-to-rvalue conversion, the
5960 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005961 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005962 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5963 Candidate.Viable = false;
5964 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5965 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005966 break;
5967
5968 case ImplicitConversionSequence::BadConversion:
5969 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005970 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005971 break;
5972
5973 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005974 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005975 "Can only end up with a standard conversion sequence or failure");
5976 }
5977}
5978
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005979/// \brief Adds a conversion function template specialization
5980/// candidate to the overload set, using template argument deduction
5981/// to deduce the template arguments of the conversion function
5982/// template from the type that we are converting to (C++
5983/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005984void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005985Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005986 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005987 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005988 Expr *From, QualType ToType,
5989 OverloadCandidateSet &CandidateSet) {
5990 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5991 "Only conversion function templates permitted here");
5992
Douglas Gregor3f396022009-09-28 04:47:19 +00005993 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5994 return;
5995
Craig Topper93e45992012-09-19 02:26:47 +00005996 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005997 CXXConversionDecl *Specialization = 0;
5998 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005999 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006000 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006001 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00006002 Candidate.FoundDecl = FoundDecl;
6003 Candidate.Function = FunctionTemplate->getTemplatedDecl();
6004 Candidate.Viable = false;
6005 Candidate.FailureKind = ovl_fail_bad_deduction;
6006 Candidate.IsSurrogate = false;
6007 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006008 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006009 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00006010 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006011 return;
6012 }
Mike Stump1eb44332009-09-09 15:08:12 +00006013
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006014 // Add the conversion function template specialization produced by
6015 // template argument deduction as a candidate.
6016 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00006017 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00006018 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006019}
6020
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006021/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
6022/// converts the given @c Object to a function pointer via the
6023/// conversion function @c Conversion, and then attempts to call it
6024/// with the given arguments (C++ [over.call.object]p2-4). Proto is
6025/// the type of function that we'll eventually be calling.
6026void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00006027 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00006028 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00006029 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006030 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006031 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006032 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00006033 if (!CandidateSet.isNewCandidate(Conversion))
6034 return;
6035
Douglas Gregor7edfb692009-11-23 12:27:39 +00006036 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006037 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006038
Ahmed Charles13a140c2012-02-25 11:00:22 +00006039 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00006040 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006041 Candidate.Function = 0;
6042 Candidate.Surrogate = Conversion;
6043 Candidate.Viable = true;
6044 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00006045 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00006046 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006047
6048 // Determine the implicit conversion sequence for the implicit
6049 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00006050 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006051 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006052 Object->Classify(Context),
6053 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00006054 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006055 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006056 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00006057 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006058 return;
6059 }
6060
6061 // The first conversion is actually a user-defined conversion whose
6062 // first conversion is ObjectInit's standard conversion (which is
6063 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00006064 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006065 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00006066 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00006067 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006068 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00006069 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00006070 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006071 = Candidate.Conversions[0].UserDefined.Before;
6072 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
6073
Mike Stump1eb44332009-09-09 15:08:12 +00006074 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006075 unsigned NumArgsInProto = Proto->getNumArgs();
6076
6077 // (C++ 13.3.2p2): A candidate function having fewer than m
6078 // parameters is viable only if it has an ellipsis in its parameter
6079 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00006080 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006081 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006082 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006083 return;
6084 }
6085
6086 // Function types don't have any default arguments, so just check if
6087 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00006088 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006089 // Not enough arguments.
6090 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006091 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006092 return;
6093 }
6094
6095 // Determine the implicit conversion sequences for each of the
6096 // arguments.
Richard Smith958ba642013-05-05 15:51:06 +00006097 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006098 if (ArgIdx < NumArgsInProto) {
6099 // (C++ 13.3.2p3): for F to be a viable function, there shall
6100 // exist for each argument an implicit conversion sequence
6101 // (13.3.3.1) that converts that argument to the corresponding
6102 // parameter of F.
6103 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00006104 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006105 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00006106 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00006107 /*InOverloadResolution=*/false,
6108 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006109 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00006110 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006111 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006112 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006113 break;
6114 }
6115 } else {
6116 // (C++ 13.3.2p2): For the purposes of overload resolution, any
6117 // argument for which there is no corresponding parameter is
6118 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00006119 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006120 }
6121 }
6122}
6123
Douglas Gregor063daf62009-03-13 18:40:31 +00006124/// \brief Add overload candidates for overloaded operators that are
6125/// member functions.
6126///
6127/// Add the overloaded operator candidates that are member functions
6128/// for the operator Op that was used in an operator expression such
6129/// as "x Op y". , Args/NumArgs provides the operator arguments, and
6130/// CandidateSet will store the added overload candidates. (C++
6131/// [over.match.oper]).
6132void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
6133 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00006134 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00006135 OverloadCandidateSet& CandidateSet,
6136 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00006137 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6138
6139 // C++ [over.match.oper]p3:
6140 // For a unary operator @ with an operand of a type whose
6141 // cv-unqualified version is T1, and for a binary operator @ with
6142 // a left operand of a type whose cv-unqualified version is T1 and
6143 // a right operand of a type whose cv-unqualified version is T2,
6144 // three sets of candidate functions, designated member
6145 // candidates, non-member candidates and built-in candidates, are
6146 // constructed as follows:
6147 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00006148
Richard Smithe410be92013-04-20 12:41:22 +00006149 // -- If T1 is a complete class type or a class currently being
6150 // defined, the set of member candidates is the result of the
6151 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
6152 // the set of member candidates is empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00006153 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Richard Smithe410be92013-04-20 12:41:22 +00006154 // Complete the type if it can be completed.
6155 RequireCompleteType(OpLoc, T1, 0);
6156 // If the type is neither complete nor being defined, bail out now.
6157 if (!T1Rec->getDecl()->getDefinition())
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006158 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006159
John McCalla24dc2e2009-11-17 02:14:36 +00006160 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6161 LookupQualifiedName(Operators, T1Rec->getDecl());
6162 Operators.suppressDiagnostics();
6163
Mike Stump1eb44332009-09-09 15:08:12 +00006164 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006165 OperEnd = Operators.end();
6166 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006167 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006168 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Rafael Espindola548107e2013-04-29 19:29:25 +00006169 Args[0]->Classify(Context),
Richard Smith958ba642013-05-05 15:51:06 +00006170 Args.slice(1),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006171 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006172 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006173 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006174}
6175
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006176/// AddBuiltinCandidate - Add a candidate for a built-in
6177/// operator. ResultTy and ParamTys are the result and parameter types
6178/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006179/// arguments being passed to the candidate. IsAssignmentOperator
6180/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006181/// operator. NumContextualBoolArguments is the number of arguments
6182/// (at the beginning of the argument list) that will be contextually
6183/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006184void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Richard Smith958ba642013-05-05 15:51:06 +00006185 ArrayRef<Expr *> Args,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006186 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006187 bool IsAssignmentOperator,
6188 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006189 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006190 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006191
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006192 // Add this candidate
Richard Smith958ba642013-05-05 15:51:06 +00006193 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00006194 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006195 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006196 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006197 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006198 Candidate.BuiltinTypes.ResultTy = ResultTy;
Richard Smith958ba642013-05-05 15:51:06 +00006199 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006200 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6201
6202 // Determine the implicit conversion sequences for each of the
6203 // arguments.
6204 Candidate.Viable = true;
Richard Smith958ba642013-05-05 15:51:06 +00006205 Candidate.ExplicitCallArguments = Args.size();
6206 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006207 // C++ [over.match.oper]p4:
6208 // For the built-in assignment operators, conversions of the
6209 // left operand are restricted as follows:
6210 // -- no temporaries are introduced to hold the left operand, and
6211 // -- no user-defined conversions are applied to the left
6212 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006213 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006214 //
6215 // We block these conversions by turning off user-defined
6216 // conversions, since that is the only way that initialization of
6217 // a reference to a non-class type can occur from something that
6218 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006219 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006220 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006221 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006222 Candidate.Conversions[ArgIdx]
6223 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006224 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006225 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006226 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006227 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006228 /*InOverloadResolution=*/false,
6229 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006230 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006231 }
John McCall1d318332010-01-12 00:44:57 +00006232 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006233 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006234 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006235 break;
6236 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006237 }
6238}
6239
6240/// BuiltinCandidateTypeSet - A set of types that will be used for the
6241/// candidate operator functions for built-in operators (C++
6242/// [over.built]). The types are separated into pointer types and
6243/// enumeration types.
6244class BuiltinCandidateTypeSet {
6245 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006246 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006247
6248 /// PointerTypes - The set of pointer types that will be used in the
6249 /// built-in candidates.
6250 TypeSet PointerTypes;
6251
Sebastian Redl78eb8742009-04-19 21:53:20 +00006252 /// MemberPointerTypes - The set of member pointer types that will be
6253 /// used in the built-in candidates.
6254 TypeSet MemberPointerTypes;
6255
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006256 /// EnumerationTypes - The set of enumeration types that will be
6257 /// used in the built-in candidates.
6258 TypeSet EnumerationTypes;
6259
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006260 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006261 /// candidates.
6262 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006263
6264 /// \brief A flag indicating non-record types are viable candidates
6265 bool HasNonRecordTypes;
6266
6267 /// \brief A flag indicating whether either arithmetic or enumeration types
6268 /// were present in the candidate set.
6269 bool HasArithmeticOrEnumeralTypes;
6270
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006271 /// \brief A flag indicating whether the nullptr type was present in the
6272 /// candidate set.
6273 bool HasNullPtrType;
6274
Douglas Gregor5842ba92009-08-24 15:23:48 +00006275 /// Sema - The semantic analysis instance where we are building the
6276 /// candidate type set.
6277 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006278
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006279 /// Context - The AST context in which we will build the type sets.
6280 ASTContext &Context;
6281
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006282 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6283 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006284 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006285
6286public:
6287 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006288 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006289
Mike Stump1eb44332009-09-09 15:08:12 +00006290 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006291 : HasNonRecordTypes(false),
6292 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006293 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006294 SemaRef(SemaRef),
6295 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006296
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006297 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006298 SourceLocation Loc,
6299 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006300 bool AllowExplicitConversions,
6301 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006302
6303 /// pointer_begin - First pointer type found;
6304 iterator pointer_begin() { return PointerTypes.begin(); }
6305
Sebastian Redl78eb8742009-04-19 21:53:20 +00006306 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006307 iterator pointer_end() { return PointerTypes.end(); }
6308
Sebastian Redl78eb8742009-04-19 21:53:20 +00006309 /// member_pointer_begin - First member pointer type found;
6310 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6311
6312 /// member_pointer_end - Past the last member pointer type found;
6313 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6314
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006315 /// enumeration_begin - First enumeration type found;
6316 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6317
Sebastian Redl78eb8742009-04-19 21:53:20 +00006318 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006319 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006320
Douglas Gregor26bcf672010-05-19 03:21:00 +00006321 iterator vector_begin() { return VectorTypes.begin(); }
6322 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006323
6324 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6325 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006326 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006327};
6328
Sebastian Redl78eb8742009-04-19 21:53:20 +00006329/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006330/// the set of pointer types along with any more-qualified variants of
6331/// that type. For example, if @p Ty is "int const *", this routine
6332/// will add "int const *", "int const volatile *", "int const
6333/// restrict *", and "int const volatile restrict *" to the set of
6334/// pointer types. Returns true if the add of @p Ty itself succeeded,
6335/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006336///
6337/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006338bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006339BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6340 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006341
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006342 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006343 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006344 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006345
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006346 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006347 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006348 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006349 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006350 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6351 PointeeTy = PTy->getPointeeType();
6352 buildObjCPtr = true;
6353 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006354 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006355 }
6356
Sebastian Redla9efada2009-11-18 20:39:26 +00006357 // Don't add qualified variants of arrays. For one, they're not allowed
6358 // (the qualifier would sink to the element type), and for another, the
6359 // only overload situation where it matters is subscript or pointer +- int,
6360 // and those shouldn't have qualifier variants anyway.
6361 if (PointeeTy->isArrayType())
6362 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006363
John McCall0953e762009-09-24 19:53:00 +00006364 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006365 bool hasVolatile = VisibleQuals.hasVolatile();
6366 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006367
John McCall0953e762009-09-24 19:53:00 +00006368 // Iterate through all strict supersets of BaseCVR.
6369 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6370 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006371 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006372 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006373
6374 // Skip over restrict if no restrict found anywhere in the types, or if
6375 // the type cannot be restrict-qualified.
6376 if ((CVR & Qualifiers::Restrict) &&
6377 (!hasRestrict ||
6378 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6379 continue;
6380
6381 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006382 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006383
6384 // Build qualified pointer type.
6385 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006386 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006387 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006388 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006389 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6390
6391 // Insert qualified pointer type.
6392 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006393 }
6394
6395 return true;
6396}
6397
Sebastian Redl78eb8742009-04-19 21:53:20 +00006398/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6399/// to the set of pointer types along with any more-qualified variants of
6400/// that type. For example, if @p Ty is "int const *", this routine
6401/// will add "int const *", "int const volatile *", "int const
6402/// restrict *", and "int const volatile restrict *" to the set of
6403/// pointer types. Returns true if the add of @p Ty itself succeeded,
6404/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006405///
6406/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006407bool
6408BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6409 QualType Ty) {
6410 // Insert this type.
6411 if (!MemberPointerTypes.insert(Ty))
6412 return false;
6413
John McCall0953e762009-09-24 19:53:00 +00006414 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6415 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006416
John McCall0953e762009-09-24 19:53:00 +00006417 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006418 // Don't add qualified variants of arrays. For one, they're not allowed
6419 // (the qualifier would sink to the element type), and for another, the
6420 // only overload situation where it matters is subscript or pointer +- int,
6421 // and those shouldn't have qualifier variants anyway.
6422 if (PointeeTy->isArrayType())
6423 return true;
John McCall0953e762009-09-24 19:53:00 +00006424 const Type *ClassTy = PointerTy->getClass();
6425
6426 // Iterate through all strict supersets of the pointee type's CVR
6427 // qualifiers.
6428 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6429 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6430 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006431
John McCall0953e762009-09-24 19:53:00 +00006432 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006433 MemberPointerTypes.insert(
6434 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006435 }
6436
6437 return true;
6438}
6439
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006440/// AddTypesConvertedFrom - Add each of the types to which the type @p
6441/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006442/// primarily interested in pointer types and enumeration types. We also
6443/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006444/// AllowUserConversions is true if we should look at the conversion
6445/// functions of a class type, and AllowExplicitConversions if we
6446/// should also include the explicit conversion functions of a class
6447/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006448void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006449BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006450 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006451 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006452 bool AllowExplicitConversions,
6453 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006454 // Only deal with canonical types.
6455 Ty = Context.getCanonicalType(Ty);
6456
6457 // Look through reference types; they aren't part of the type of an
6458 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006459 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006460 Ty = RefTy->getPointeeType();
6461
John McCall3b657512011-01-19 10:06:00 +00006462 // If we're dealing with an array type, decay to the pointer.
6463 if (Ty->isArrayType())
6464 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6465
6466 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006467 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006468
Chandler Carruth6a577462010-12-13 01:44:01 +00006469 // Flag if we ever add a non-record type.
6470 const RecordType *TyRec = Ty->getAs<RecordType>();
6471 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6472
Chandler Carruth6a577462010-12-13 01:44:01 +00006473 // Flag if we encounter an arithmetic type.
6474 HasArithmeticOrEnumeralTypes =
6475 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6476
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006477 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6478 PointerTypes.insert(Ty);
6479 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006480 // Insert our type, and its more-qualified variants, into the set
6481 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006482 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006483 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006484 } else if (Ty->isMemberPointerType()) {
6485 // Member pointers are far easier, since the pointee can't be converted.
6486 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6487 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006488 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006489 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006490 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006491 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006492 // We treat vector types as arithmetic types in many contexts as an
6493 // extension.
6494 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006495 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006496 } else if (Ty->isNullPtrType()) {
6497 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006498 } else if (AllowUserConversions && TyRec) {
6499 // No conversion functions in incomplete types.
6500 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6501 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006502
Chandler Carruth6a577462010-12-13 01:44:01 +00006503 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006504 std::pair<CXXRecordDecl::conversion_iterator,
6505 CXXRecordDecl::conversion_iterator>
6506 Conversions = ClassDecl->getVisibleConversionFunctions();
6507 for (CXXRecordDecl::conversion_iterator
6508 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006509 NamedDecl *D = I.getDecl();
6510 if (isa<UsingShadowDecl>(D))
6511 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006512
Chandler Carruth6a577462010-12-13 01:44:01 +00006513 // Skip conversion function templates; they don't tell us anything
6514 // about which builtin types we can convert to.
6515 if (isa<FunctionTemplateDecl>(D))
6516 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006517
Chandler Carruth6a577462010-12-13 01:44:01 +00006518 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6519 if (AllowExplicitConversions || !Conv->isExplicit()) {
6520 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6521 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006522 }
6523 }
6524 }
6525}
6526
Douglas Gregor19b7b152009-08-24 13:43:27 +00006527/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6528/// the volatile- and non-volatile-qualified assignment operators for the
6529/// given type to the candidate set.
6530static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6531 QualType T,
Richard Smith958ba642013-05-05 15:51:06 +00006532 ArrayRef<Expr *> Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006533 OverloadCandidateSet &CandidateSet) {
6534 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006535
Douglas Gregor19b7b152009-08-24 13:43:27 +00006536 // T& operator=(T&, T)
6537 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6538 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006540 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006541
Douglas Gregor19b7b152009-08-24 13:43:27 +00006542 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6543 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006544 ParamTypes[0]
6545 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006546 ParamTypes[1] = T;
Richard Smith958ba642013-05-05 15:51:06 +00006547 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006548 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006549 }
6550}
Mike Stump1eb44332009-09-09 15:08:12 +00006551
Sebastian Redl9994a342009-10-25 17:03:50 +00006552/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6553/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006554static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6555 Qualifiers VRQuals;
6556 const RecordType *TyRec;
6557 if (const MemberPointerType *RHSMPType =
6558 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006559 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006560 else
6561 TyRec = ArgExpr->getType()->getAs<RecordType>();
6562 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006563 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006564 VRQuals.addVolatile();
6565 VRQuals.addRestrict();
6566 return VRQuals;
6567 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006568
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006569 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006570 if (!ClassDecl->hasDefinition())
6571 return VRQuals;
6572
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006573 std::pair<CXXRecordDecl::conversion_iterator,
6574 CXXRecordDecl::conversion_iterator>
6575 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006576
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006577 for (CXXRecordDecl::conversion_iterator
6578 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006579 NamedDecl *D = I.getDecl();
6580 if (isa<UsingShadowDecl>(D))
6581 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6582 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006583 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6584 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6585 CanTy = ResTypeRef->getPointeeType();
6586 // Need to go down the pointer/mempointer chain and add qualifiers
6587 // as see them.
6588 bool done = false;
6589 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006590 if (CanTy.isRestrictQualified())
6591 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006592 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6593 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006594 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006595 CanTy->getAs<MemberPointerType>())
6596 CanTy = ResTypeMPtr->getPointeeType();
6597 else
6598 done = true;
6599 if (CanTy.isVolatileQualified())
6600 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006601 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6602 return VRQuals;
6603 }
6604 }
6605 }
6606 return VRQuals;
6607}
John McCall00071ec2010-11-13 05:51:15 +00006608
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006609namespace {
John McCall00071ec2010-11-13 05:51:15 +00006610
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006611/// \brief Helper class to manage the addition of builtin operator overload
6612/// candidates. It provides shared state and utility methods used throughout
6613/// the process, as well as a helper method to add each group of builtin
6614/// operator overloads from the standard to a candidate set.
6615class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006616 // Common instance state available to all overload candidate addition methods.
6617 Sema &S;
Richard Smith958ba642013-05-05 15:51:06 +00006618 ArrayRef<Expr *> Args;
Chandler Carruth6d695582010-12-12 10:35:00 +00006619 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006620 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006621 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006622 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006623
Chandler Carruth6d695582010-12-12 10:35:00 +00006624 // Define some constants used to index and iterate over the arithemetic types
6625 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006626 // The "promoted arithmetic types" are the arithmetic
6627 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006628 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006629 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006630 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006631 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006632 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006633 LastPromotedArithmeticType = 11;
6634 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006635
Chandler Carruth6d695582010-12-12 10:35:00 +00006636 /// \brief Get the canonical type for a given arithmetic type index.
6637 CanQualType getArithmeticType(unsigned index) {
6638 assert(index < NumArithmeticTypes);
6639 static CanQualType ASTContext::* const
6640 ArithmeticTypes[NumArithmeticTypes] = {
6641 // Start of promoted types.
6642 &ASTContext::FloatTy,
6643 &ASTContext::DoubleTy,
6644 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006645
Chandler Carruth6d695582010-12-12 10:35:00 +00006646 // Start of integral types.
6647 &ASTContext::IntTy,
6648 &ASTContext::LongTy,
6649 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006650 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006651 &ASTContext::UnsignedIntTy,
6652 &ASTContext::UnsignedLongTy,
6653 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006654 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006655 // End of promoted types.
6656
6657 &ASTContext::BoolTy,
6658 &ASTContext::CharTy,
6659 &ASTContext::WCharTy,
6660 &ASTContext::Char16Ty,
6661 &ASTContext::Char32Ty,
6662 &ASTContext::SignedCharTy,
6663 &ASTContext::ShortTy,
6664 &ASTContext::UnsignedCharTy,
6665 &ASTContext::UnsignedShortTy,
6666 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006667 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006668 };
6669 return S.Context.*ArithmeticTypes[index];
6670 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006671
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006672 /// \brief Gets the canonical type resulting from the usual arithemetic
6673 /// converions for the given arithmetic types.
6674 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6675 // Accelerator table for performing the usual arithmetic conversions.
6676 // The rules are basically:
6677 // - if either is floating-point, use the wider floating-point
6678 // - if same signedness, use the higher rank
6679 // - if same size, use unsigned of the higher rank
6680 // - use the larger type
6681 // These rules, together with the axiom that higher ranks are
6682 // never smaller, are sufficient to precompute all of these results
6683 // *except* when dealing with signed types of higher rank.
6684 // (we could precompute SLL x UI for all known platforms, but it's
6685 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006686 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006687 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006688 Dep=-1,
6689 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006690 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006691 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006692 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006693/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6694/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6695/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6696/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6697/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6698/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6699/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6700/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6701/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6702/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6703/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006704 };
6705
6706 assert(L < LastPromotedArithmeticType);
6707 assert(R < LastPromotedArithmeticType);
6708 int Idx = ConversionsTable[L][R];
6709
6710 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006711 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006712
6713 // Slow path: we need to compare widths.
6714 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006715 CanQualType LT = getArithmeticType(L),
6716 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006717 unsigned LW = S.Context.getIntWidth(LT),
6718 RW = S.Context.getIntWidth(RT);
6719
6720 // If they're different widths, use the signed type.
6721 if (LW > RW) return LT;
6722 else if (LW < RW) return RT;
6723
6724 // Otherwise, use the unsigned type of the signed type's rank.
6725 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6726 assert(L == SLL || R == SLL);
6727 return S.Context.UnsignedLongLongTy;
6728 }
6729
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006730 /// \brief Helper method to factor out the common pattern of adding overloads
6731 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006732 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006733 bool HasVolatile,
6734 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006735 QualType ParamTypes[2] = {
6736 S.Context.getLValueReferenceType(CandidateTy),
6737 S.Context.IntTy
6738 };
6739
6740 // Non-volatile version.
Richard Smith958ba642013-05-05 15:51:06 +00006741 if (Args.size() == 1)
6742 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006743 else
Richard Smith958ba642013-05-05 15:51:06 +00006744 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006745
6746 // Use a heuristic to reduce number of builtin candidates in the set:
6747 // add volatile version only if there are conversions to a volatile type.
6748 if (HasVolatile) {
6749 ParamTypes[0] =
6750 S.Context.getLValueReferenceType(
6751 S.Context.getVolatileType(CandidateTy));
Richard Smith958ba642013-05-05 15:51:06 +00006752 if (Args.size() == 1)
6753 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006754 else
Richard Smith958ba642013-05-05 15:51:06 +00006755 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006756 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006757
6758 // Add restrict version only if there are conversions to a restrict type
6759 // and our candidate type is a non-restrict-qualified pointer.
6760 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6761 !CandidateTy.isRestrictQualified()) {
6762 ParamTypes[0]
6763 = S.Context.getLValueReferenceType(
6764 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
Richard Smith958ba642013-05-05 15:51:06 +00006765 if (Args.size() == 1)
6766 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006767 else
Richard Smith958ba642013-05-05 15:51:06 +00006768 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006769
6770 if (HasVolatile) {
6771 ParamTypes[0]
6772 = S.Context.getLValueReferenceType(
6773 S.Context.getCVRQualifiedType(CandidateTy,
6774 (Qualifiers::Volatile |
6775 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00006776 if (Args.size() == 1)
6777 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006778 else
Richard Smith958ba642013-05-05 15:51:06 +00006779 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, CandidateSet);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006780 }
6781 }
6782
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006783 }
6784
6785public:
6786 BuiltinOperatorOverloadBuilder(
Richard Smith958ba642013-05-05 15:51:06 +00006787 Sema &S, ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006788 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006789 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006790 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006791 OverloadCandidateSet &CandidateSet)
Richard Smith958ba642013-05-05 15:51:06 +00006792 : S(S), Args(Args),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006793 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006794 HasArithmeticOrEnumeralCandidateType(
6795 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006796 CandidateTypes(CandidateTypes),
6797 CandidateSet(CandidateSet) {
6798 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006799 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006800 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006801 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006802 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006803 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006804 assert(getArithmeticType(FirstPromotedArithmeticType)
6805 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006806 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006807 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006808 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006809 "Invalid last promoted arithmetic type");
6810 }
6811
6812 // C++ [over.built]p3:
6813 //
6814 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6815 // is either volatile or empty, there exist candidate operator
6816 // functions of the form
6817 //
6818 // VQ T& operator++(VQ T&);
6819 // T operator++(VQ T&, int);
6820 //
6821 // C++ [over.built]p4:
6822 //
6823 // For every pair (T, VQ), where T is an arithmetic type other
6824 // than bool, and VQ is either volatile or empty, there exist
6825 // candidate operator functions of the form
6826 //
6827 // VQ T& operator--(VQ T&);
6828 // T operator--(VQ T&, int);
6829 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006830 if (!HasArithmeticOrEnumeralCandidateType)
6831 return;
6832
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006833 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6834 Arith < NumArithmeticTypes; ++Arith) {
6835 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006836 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006837 VisibleTypeConversionsQuals.hasVolatile(),
6838 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006839 }
6840 }
6841
6842 // C++ [over.built]p5:
6843 //
6844 // For every pair (T, VQ), where T is a cv-qualified or
6845 // cv-unqualified object type, and VQ is either volatile or
6846 // empty, there exist candidate operator functions of the form
6847 //
6848 // T*VQ& operator++(T*VQ&);
6849 // T*VQ& operator--(T*VQ&);
6850 // T* operator++(T*VQ&, int);
6851 // T* operator--(T*VQ&, int);
6852 void addPlusPlusMinusMinusPointerOverloads() {
6853 for (BuiltinCandidateTypeSet::iterator
6854 Ptr = CandidateTypes[0].pointer_begin(),
6855 PtrEnd = CandidateTypes[0].pointer_end();
6856 Ptr != PtrEnd; ++Ptr) {
6857 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006858 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006859 continue;
6860
6861 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006862 (!(*Ptr).isVolatileQualified() &&
6863 VisibleTypeConversionsQuals.hasVolatile()),
6864 (!(*Ptr).isRestrictQualified() &&
6865 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006866 }
6867 }
6868
6869 // C++ [over.built]p6:
6870 // For every cv-qualified or cv-unqualified object type T, there
6871 // exist candidate operator functions of the form
6872 //
6873 // T& operator*(T*);
6874 //
6875 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006876 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006877 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006878 // T& operator*(T*);
6879 void addUnaryStarPointerOverloads() {
6880 for (BuiltinCandidateTypeSet::iterator
6881 Ptr = CandidateTypes[0].pointer_begin(),
6882 PtrEnd = CandidateTypes[0].pointer_end();
6883 Ptr != PtrEnd; ++Ptr) {
6884 QualType ParamTy = *Ptr;
6885 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006886 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6887 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006888
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006889 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6890 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6891 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006892
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006893 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
Richard Smith958ba642013-05-05 15:51:06 +00006894 &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006895 }
6896 }
6897
6898 // C++ [over.built]p9:
6899 // For every promoted arithmetic type T, there exist candidate
6900 // operator functions of the form
6901 //
6902 // T operator+(T);
6903 // T operator-(T);
6904 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006905 if (!HasArithmeticOrEnumeralCandidateType)
6906 return;
6907
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006908 for (unsigned Arith = FirstPromotedArithmeticType;
6909 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006910 QualType ArithTy = getArithmeticType(Arith);
Richard Smith958ba642013-05-05 15:51:06 +00006911 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006912 }
6913
6914 // Extension: We also add these operators for vector types.
6915 for (BuiltinCandidateTypeSet::iterator
6916 Vec = CandidateTypes[0].vector_begin(),
6917 VecEnd = CandidateTypes[0].vector_end();
6918 Vec != VecEnd; ++Vec) {
6919 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006920 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006921 }
6922 }
6923
6924 // C++ [over.built]p8:
6925 // For every type T, there exist candidate operator functions of
6926 // the form
6927 //
6928 // T* operator+(T*);
6929 void addUnaryPlusPointerOverloads() {
6930 for (BuiltinCandidateTypeSet::iterator
6931 Ptr = CandidateTypes[0].pointer_begin(),
6932 PtrEnd = CandidateTypes[0].pointer_end();
6933 Ptr != PtrEnd; ++Ptr) {
6934 QualType ParamTy = *Ptr;
Richard Smith958ba642013-05-05 15:51:06 +00006935 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006936 }
6937 }
6938
6939 // C++ [over.built]p10:
6940 // For every promoted integral type T, there exist candidate
6941 // operator functions of the form
6942 //
6943 // T operator~(T);
6944 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006945 if (!HasArithmeticOrEnumeralCandidateType)
6946 return;
6947
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006948 for (unsigned Int = FirstPromotedIntegralType;
6949 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006950 QualType IntTy = getArithmeticType(Int);
Richard Smith958ba642013-05-05 15:51:06 +00006951 S.AddBuiltinCandidate(IntTy, &IntTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006952 }
6953
6954 // Extension: We also add this operator for vector types.
6955 for (BuiltinCandidateTypeSet::iterator
6956 Vec = CandidateTypes[0].vector_begin(),
6957 VecEnd = CandidateTypes[0].vector_end();
6958 Vec != VecEnd; ++Vec) {
6959 QualType VecTy = *Vec;
Richard Smith958ba642013-05-05 15:51:06 +00006960 S.AddBuiltinCandidate(VecTy, &VecTy, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006961 }
6962 }
6963
6964 // C++ [over.match.oper]p16:
6965 // For every pointer to member type T, there exist candidate operator
6966 // functions of the form
6967 //
6968 // bool operator==(T,T);
6969 // bool operator!=(T,T);
6970 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6971 /// Set of (canonical) types that we've already handled.
6972 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6973
Richard Smith958ba642013-05-05 15:51:06 +00006974 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006975 for (BuiltinCandidateTypeSet::iterator
6976 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6977 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6978 MemPtr != MemPtrEnd;
6979 ++MemPtr) {
6980 // Don't add the same builtin candidate twice.
6981 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6982 continue;
6983
6984 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00006985 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006986 }
6987 }
6988 }
6989
6990 // C++ [over.built]p15:
6991 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006992 // For every T, where T is an enumeration type, a pointer type, or
6993 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006994 //
6995 // bool operator<(T, T);
6996 // bool operator>(T, T);
6997 // bool operator<=(T, T);
6998 // bool operator>=(T, T);
6999 // bool operator==(T, T);
7000 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007001 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00007002 // C++ [over.match.oper]p3:
7003 // [...]the built-in candidates include all of the candidate operator
7004 // functions defined in 13.6 that, compared to the given operator, [...]
7005 // do not have the same parameter-type-list as any non-template non-member
7006 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007007 //
Eli Friedman97c67392012-09-18 21:52:24 +00007008 // Note that in practice, this only affects enumeration types because there
7009 // aren't any built-in candidates of record type, and a user-defined operator
7010 // must have an operand of record or enumeration type. Also, the only other
7011 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007012 // cannot be overloaded for enumeration types, so this is the only place
7013 // where we must suppress candidates like this.
7014 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
7015 UserDefinedBinaryOperators;
7016
Richard Smith958ba642013-05-05 15:51:06 +00007017 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007018 if (CandidateTypes[ArgIdx].enumeration_begin() !=
7019 CandidateTypes[ArgIdx].enumeration_end()) {
7020 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
7021 CEnd = CandidateSet.end();
7022 C != CEnd; ++C) {
7023 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
7024 continue;
7025
Eli Friedman97c67392012-09-18 21:52:24 +00007026 if (C->Function->isFunctionTemplateSpecialization())
7027 continue;
7028
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007029 QualType FirstParamType =
7030 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
7031 QualType SecondParamType =
7032 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
7033
7034 // Skip if either parameter isn't of enumeral type.
7035 if (!FirstParamType->isEnumeralType() ||
7036 !SecondParamType->isEnumeralType())
7037 continue;
7038
7039 // Add this operator to the set of known user-defined operators.
7040 UserDefinedBinaryOperators.insert(
7041 std::make_pair(S.Context.getCanonicalType(FirstParamType),
7042 S.Context.getCanonicalType(SecondParamType)));
7043 }
7044 }
7045 }
7046
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007047 /// Set of (canonical) types that we've already handled.
7048 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7049
Richard Smith958ba642013-05-05 15:51:06 +00007050 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007051 for (BuiltinCandidateTypeSet::iterator
7052 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7053 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7054 Ptr != PtrEnd; ++Ptr) {
7055 // Don't add the same builtin candidate twice.
7056 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7057 continue;
7058
7059 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007060 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007061 }
7062 for (BuiltinCandidateTypeSet::iterator
7063 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7064 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7065 Enum != EnumEnd; ++Enum) {
7066 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
7067
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007068 // Don't add the same builtin candidate twice, or if a user defined
7069 // candidate exists.
7070 if (!AddedTypes.insert(CanonType) ||
7071 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
7072 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007073 continue;
7074
7075 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007076 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007077 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007078
7079 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
7080 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
7081 if (AddedTypes.insert(NullPtrTy) &&
Richard Smith958ba642013-05-05 15:51:06 +00007082 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007083 NullPtrTy))) {
7084 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
Richard Smith958ba642013-05-05 15:51:06 +00007085 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args,
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00007086 CandidateSet);
7087 }
7088 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007089 }
7090 }
7091
7092 // C++ [over.built]p13:
7093 //
7094 // For every cv-qualified or cv-unqualified object type T
7095 // there exist candidate operator functions of the form
7096 //
7097 // T* operator+(T*, ptrdiff_t);
7098 // T& operator[](T*, ptrdiff_t); [BELOW]
7099 // T* operator-(T*, ptrdiff_t);
7100 // T* operator+(ptrdiff_t, T*);
7101 // T& operator[](ptrdiff_t, T*); [BELOW]
7102 //
7103 // C++ [over.built]p14:
7104 //
7105 // For every T, where T is a pointer to object type, there
7106 // exist candidate operator functions of the form
7107 //
7108 // ptrdiff_t operator-(T, T);
7109 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
7110 /// Set of (canonical) types that we've already handled.
7111 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7112
7113 for (int Arg = 0; Arg < 2; ++Arg) {
7114 QualType AsymetricParamTypes[2] = {
7115 S.Context.getPointerDiffType(),
7116 S.Context.getPointerDiffType(),
7117 };
7118 for (BuiltinCandidateTypeSet::iterator
7119 Ptr = CandidateTypes[Arg].pointer_begin(),
7120 PtrEnd = CandidateTypes[Arg].pointer_end();
7121 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007122 QualType PointeeTy = (*Ptr)->getPointeeType();
7123 if (!PointeeTy->isObjectType())
7124 continue;
7125
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007126 AsymetricParamTypes[Arg] = *Ptr;
7127 if (Arg == 0 || Op == OO_Plus) {
7128 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
7129 // T* operator+(ptrdiff_t, T*);
Richard Smith958ba642013-05-05 15:51:06 +00007130 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007131 }
7132 if (Op == OO_Minus) {
7133 // ptrdiff_t operator-(T, T);
7134 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7135 continue;
7136
7137 QualType ParamTypes[2] = { *Ptr, *Ptr };
7138 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
Richard Smith958ba642013-05-05 15:51:06 +00007139 Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007140 }
7141 }
7142 }
7143 }
7144
7145 // C++ [over.built]p12:
7146 //
7147 // For every pair of promoted arithmetic types L and R, there
7148 // exist candidate operator functions of the form
7149 //
7150 // LR operator*(L, R);
7151 // LR operator/(L, R);
7152 // LR operator+(L, R);
7153 // LR operator-(L, R);
7154 // bool operator<(L, R);
7155 // bool operator>(L, R);
7156 // bool operator<=(L, R);
7157 // bool operator>=(L, R);
7158 // bool operator==(L, R);
7159 // bool operator!=(L, R);
7160 //
7161 // where LR is the result of the usual arithmetic conversions
7162 // between types L and R.
7163 //
7164 // C++ [over.built]p24:
7165 //
7166 // For every pair of promoted arithmetic types L and R, there exist
7167 // candidate operator functions of the form
7168 //
7169 // LR operator?(bool, L, R);
7170 //
7171 // where LR is the result of the usual arithmetic conversions
7172 // between types L and R.
7173 // Our candidates ignore the first parameter.
7174 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007175 if (!HasArithmeticOrEnumeralCandidateType)
7176 return;
7177
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007178 for (unsigned Left = FirstPromotedArithmeticType;
7179 Left < LastPromotedArithmeticType; ++Left) {
7180 for (unsigned Right = FirstPromotedArithmeticType;
7181 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007182 QualType LandR[2] = { getArithmeticType(Left),
7183 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007184 QualType Result =
7185 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007186 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007187 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007188 }
7189 }
7190
7191 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7192 // conditional operator for vector types.
7193 for (BuiltinCandidateTypeSet::iterator
7194 Vec1 = CandidateTypes[0].vector_begin(),
7195 Vec1End = CandidateTypes[0].vector_end();
7196 Vec1 != Vec1End; ++Vec1) {
7197 for (BuiltinCandidateTypeSet::iterator
7198 Vec2 = CandidateTypes[1].vector_begin(),
7199 Vec2End = CandidateTypes[1].vector_end();
7200 Vec2 != Vec2End; ++Vec2) {
7201 QualType LandR[2] = { *Vec1, *Vec2 };
7202 QualType Result = S.Context.BoolTy;
7203 if (!isComparison) {
7204 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7205 Result = *Vec1;
7206 else
7207 Result = *Vec2;
7208 }
7209
Richard Smith958ba642013-05-05 15:51:06 +00007210 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007211 }
7212 }
7213 }
7214
7215 // C++ [over.built]p17:
7216 //
7217 // For every pair of promoted integral types L and R, there
7218 // exist candidate operator functions of the form
7219 //
7220 // LR operator%(L, R);
7221 // LR operator&(L, R);
7222 // LR operator^(L, R);
7223 // LR operator|(L, R);
7224 // L operator<<(L, R);
7225 // L operator>>(L, R);
7226 //
7227 // where LR is the result of the usual arithmetic conversions
7228 // between types L and R.
7229 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007230 if (!HasArithmeticOrEnumeralCandidateType)
7231 return;
7232
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007233 for (unsigned Left = FirstPromotedIntegralType;
7234 Left < LastPromotedIntegralType; ++Left) {
7235 for (unsigned Right = FirstPromotedIntegralType;
7236 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007237 QualType LandR[2] = { getArithmeticType(Left),
7238 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007239 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7240 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007241 : getUsualArithmeticConversions(Left, Right);
Richard Smith958ba642013-05-05 15:51:06 +00007242 S.AddBuiltinCandidate(Result, LandR, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007243 }
7244 }
7245 }
7246
7247 // C++ [over.built]p20:
7248 //
7249 // For every pair (T, VQ), where T is an enumeration or
7250 // pointer to member type and VQ is either volatile or
7251 // empty, there exist candidate operator functions of the form
7252 //
7253 // VQ T& operator=(VQ T&, T);
7254 void addAssignmentMemberPointerOrEnumeralOverloads() {
7255 /// Set of (canonical) types that we've already handled.
7256 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7257
7258 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7259 for (BuiltinCandidateTypeSet::iterator
7260 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7261 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7262 Enum != EnumEnd; ++Enum) {
7263 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7264 continue;
7265
Richard Smith958ba642013-05-05 15:51:06 +00007266 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007267 }
7268
7269 for (BuiltinCandidateTypeSet::iterator
7270 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7271 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7272 MemPtr != MemPtrEnd; ++MemPtr) {
7273 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7274 continue;
7275
Richard Smith958ba642013-05-05 15:51:06 +00007276 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007277 }
7278 }
7279 }
7280
7281 // C++ [over.built]p19:
7282 //
7283 // For every pair (T, VQ), where T is any type and VQ is either
7284 // volatile or empty, there exist candidate operator functions
7285 // of the form
7286 //
7287 // T*VQ& operator=(T*VQ&, T*);
7288 //
7289 // C++ [over.built]p21:
7290 //
7291 // For every pair (T, VQ), where T is a cv-qualified or
7292 // cv-unqualified object type and VQ is either volatile or
7293 // empty, there exist candidate operator functions of the form
7294 //
7295 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7296 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7297 void addAssignmentPointerOverloads(bool isEqualOp) {
7298 /// Set of (canonical) types that we've already handled.
7299 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7300
7301 for (BuiltinCandidateTypeSet::iterator
7302 Ptr = CandidateTypes[0].pointer_begin(),
7303 PtrEnd = CandidateTypes[0].pointer_end();
7304 Ptr != PtrEnd; ++Ptr) {
7305 // If this is operator=, keep track of the builtin candidates we added.
7306 if (isEqualOp)
7307 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007308 else if (!(*Ptr)->getPointeeType()->isObjectType())
7309 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007310
7311 // non-volatile version
7312 QualType ParamTypes[2] = {
7313 S.Context.getLValueReferenceType(*Ptr),
7314 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7315 };
Richard Smith958ba642013-05-05 15:51:06 +00007316 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007317 /*IsAssigmentOperator=*/ isEqualOp);
7318
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007319 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7320 VisibleTypeConversionsQuals.hasVolatile();
7321 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007322 // volatile version
7323 ParamTypes[0] =
7324 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007325 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007326 /*IsAssigmentOperator=*/isEqualOp);
7327 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007328
7329 if (!(*Ptr).isRestrictQualified() &&
7330 VisibleTypeConversionsQuals.hasRestrict()) {
7331 // restrict version
7332 ParamTypes[0]
7333 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007334 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007335 /*IsAssigmentOperator=*/isEqualOp);
7336
7337 if (NeedVolatile) {
7338 // volatile restrict version
7339 ParamTypes[0]
7340 = S.Context.getLValueReferenceType(
7341 S.Context.getCVRQualifiedType(*Ptr,
7342 (Qualifiers::Volatile |
7343 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007344 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007345 /*IsAssigmentOperator=*/isEqualOp);
7346 }
7347 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007348 }
7349
7350 if (isEqualOp) {
7351 for (BuiltinCandidateTypeSet::iterator
7352 Ptr = CandidateTypes[1].pointer_begin(),
7353 PtrEnd = CandidateTypes[1].pointer_end();
7354 Ptr != PtrEnd; ++Ptr) {
7355 // Make sure we don't add the same candidate twice.
7356 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7357 continue;
7358
Chandler Carruth6df868e2010-12-12 08:17:55 +00007359 QualType ParamTypes[2] = {
7360 S.Context.getLValueReferenceType(*Ptr),
7361 *Ptr,
7362 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007363
7364 // non-volatile version
Richard Smith958ba642013-05-05 15:51:06 +00007365 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007366 /*IsAssigmentOperator=*/true);
7367
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007368 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7369 VisibleTypeConversionsQuals.hasVolatile();
7370 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007371 // volatile version
7372 ParamTypes[0] =
7373 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7375 /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007376 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007377
7378 if (!(*Ptr).isRestrictQualified() &&
7379 VisibleTypeConversionsQuals.hasRestrict()) {
7380 // restrict version
7381 ParamTypes[0]
7382 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
Richard Smith958ba642013-05-05 15:51:06 +00007383 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7384 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007385
7386 if (NeedVolatile) {
7387 // volatile restrict version
7388 ParamTypes[0]
7389 = S.Context.getLValueReferenceType(
7390 S.Context.getCVRQualifiedType(*Ptr,
7391 (Qualifiers::Volatile |
7392 Qualifiers::Restrict)));
Richard Smith958ba642013-05-05 15:51:06 +00007393 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
7394 /*IsAssigmentOperator=*/true);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007395 }
7396 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007397 }
7398 }
7399 }
7400
7401 // C++ [over.built]p18:
7402 //
7403 // For every triple (L, VQ, R), where L is an arithmetic type,
7404 // VQ is either volatile or empty, and R is a promoted
7405 // arithmetic type, there exist candidate operator functions of
7406 // the form
7407 //
7408 // VQ L& operator=(VQ L&, R);
7409 // VQ L& operator*=(VQ L&, R);
7410 // VQ L& operator/=(VQ L&, R);
7411 // VQ L& operator+=(VQ L&, R);
7412 // VQ L& operator-=(VQ L&, R);
7413 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007414 if (!HasArithmeticOrEnumeralCandidateType)
7415 return;
7416
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007417 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7418 for (unsigned Right = FirstPromotedArithmeticType;
7419 Right < LastPromotedArithmeticType; ++Right) {
7420 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007421 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007422
7423 // Add this built-in operator as a candidate (VQ is empty).
7424 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007425 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007426 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007427 /*IsAssigmentOperator=*/isEqualOp);
7428
7429 // Add this built-in operator as a candidate (VQ is 'volatile').
7430 if (VisibleTypeConversionsQuals.hasVolatile()) {
7431 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007432 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007433 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007435 /*IsAssigmentOperator=*/isEqualOp);
7436 }
7437 }
7438 }
7439
7440 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7441 for (BuiltinCandidateTypeSet::iterator
7442 Vec1 = CandidateTypes[0].vector_begin(),
7443 Vec1End = CandidateTypes[0].vector_end();
7444 Vec1 != Vec1End; ++Vec1) {
7445 for (BuiltinCandidateTypeSet::iterator
7446 Vec2 = CandidateTypes[1].vector_begin(),
7447 Vec2End = CandidateTypes[1].vector_end();
7448 Vec2 != Vec2End; ++Vec2) {
7449 QualType ParamTypes[2];
7450 ParamTypes[1] = *Vec2;
7451 // Add this built-in operator as a candidate (VQ is empty).
7452 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
Richard Smith958ba642013-05-05 15:51:06 +00007453 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007454 /*IsAssigmentOperator=*/isEqualOp);
7455
7456 // Add this built-in operator as a candidate (VQ is 'volatile').
7457 if (VisibleTypeConversionsQuals.hasVolatile()) {
7458 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7459 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007460 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007461 /*IsAssigmentOperator=*/isEqualOp);
7462 }
7463 }
7464 }
7465 }
7466
7467 // C++ [over.built]p22:
7468 //
7469 // For every triple (L, VQ, R), where L is an integral type, VQ
7470 // is either volatile or empty, and R is a promoted integral
7471 // type, there exist candidate operator functions of the form
7472 //
7473 // VQ L& operator%=(VQ L&, R);
7474 // VQ L& operator<<=(VQ L&, R);
7475 // VQ L& operator>>=(VQ L&, R);
7476 // VQ L& operator&=(VQ L&, R);
7477 // VQ L& operator^=(VQ L&, R);
7478 // VQ L& operator|=(VQ L&, R);
7479 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007480 if (!HasArithmeticOrEnumeralCandidateType)
7481 return;
7482
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007483 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7484 for (unsigned Right = FirstPromotedIntegralType;
7485 Right < LastPromotedIntegralType; ++Right) {
7486 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007487 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007488
7489 // Add this built-in operator as a candidate (VQ is empty).
7490 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007491 S.Context.getLValueReferenceType(getArithmeticType(Left));
Richard Smith958ba642013-05-05 15:51:06 +00007492 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007493 if (VisibleTypeConversionsQuals.hasVolatile()) {
7494 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007495 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007496 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7497 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Richard Smith958ba642013-05-05 15:51:06 +00007498 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007499 }
7500 }
7501 }
7502 }
7503
7504 // C++ [over.operator]p23:
7505 //
7506 // There also exist candidate operator functions of the form
7507 //
7508 // bool operator!(bool);
7509 // bool operator&&(bool, bool);
7510 // bool operator||(bool, bool);
7511 void addExclaimOverload() {
7512 QualType ParamTy = S.Context.BoolTy;
Richard Smith958ba642013-05-05 15:51:06 +00007513 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007514 /*IsAssignmentOperator=*/false,
7515 /*NumContextualBoolArguments=*/1);
7516 }
7517 void addAmpAmpOrPipePipeOverload() {
7518 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
Richard Smith958ba642013-05-05 15:51:06 +00007519 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007520 /*IsAssignmentOperator=*/false,
7521 /*NumContextualBoolArguments=*/2);
7522 }
7523
7524 // C++ [over.built]p13:
7525 //
7526 // For every cv-qualified or cv-unqualified object type T there
7527 // exist candidate operator functions of the form
7528 //
7529 // T* operator+(T*, ptrdiff_t); [ABOVE]
7530 // T& operator[](T*, ptrdiff_t);
7531 // T* operator-(T*, ptrdiff_t); [ABOVE]
7532 // T* operator+(ptrdiff_t, T*); [ABOVE]
7533 // T& operator[](ptrdiff_t, T*);
7534 void addSubscriptOverloads() {
7535 for (BuiltinCandidateTypeSet::iterator
7536 Ptr = CandidateTypes[0].pointer_begin(),
7537 PtrEnd = CandidateTypes[0].pointer_end();
7538 Ptr != PtrEnd; ++Ptr) {
7539 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7540 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007541 if (!PointeeType->isObjectType())
7542 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007543
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007544 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7545
7546 // T& operator[](T*, ptrdiff_t)
Richard Smith958ba642013-05-05 15:51:06 +00007547 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007548 }
7549
7550 for (BuiltinCandidateTypeSet::iterator
7551 Ptr = CandidateTypes[1].pointer_begin(),
7552 PtrEnd = CandidateTypes[1].pointer_end();
7553 Ptr != PtrEnd; ++Ptr) {
7554 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7555 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007556 if (!PointeeType->isObjectType())
7557 continue;
7558
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007559 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7560
7561 // T& operator[](ptrdiff_t, T*)
Richard Smith958ba642013-05-05 15:51:06 +00007562 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007563 }
7564 }
7565
7566 // C++ [over.built]p11:
7567 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7568 // C1 is the same type as C2 or is a derived class of C2, T is an object
7569 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7570 // there exist candidate operator functions of the form
7571 //
7572 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7573 //
7574 // where CV12 is the union of CV1 and CV2.
7575 void addArrowStarOverloads() {
7576 for (BuiltinCandidateTypeSet::iterator
7577 Ptr = CandidateTypes[0].pointer_begin(),
7578 PtrEnd = CandidateTypes[0].pointer_end();
7579 Ptr != PtrEnd; ++Ptr) {
7580 QualType C1Ty = (*Ptr);
7581 QualType C1;
7582 QualifierCollector Q1;
7583 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7584 if (!isa<RecordType>(C1))
7585 continue;
7586 // heuristic to reduce number of builtin candidates in the set.
7587 // Add volatile/restrict version only if there are conversions to a
7588 // volatile/restrict type.
7589 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7590 continue;
7591 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7592 continue;
7593 for (BuiltinCandidateTypeSet::iterator
7594 MemPtr = CandidateTypes[1].member_pointer_begin(),
7595 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7596 MemPtr != MemPtrEnd; ++MemPtr) {
7597 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7598 QualType C2 = QualType(mptr->getClass(), 0);
7599 C2 = C2.getUnqualifiedType();
7600 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7601 break;
7602 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7603 // build CV12 T&
7604 QualType T = mptr->getPointeeType();
7605 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7606 T.isVolatileQualified())
7607 continue;
7608 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7609 T.isRestrictQualified())
7610 continue;
7611 T = Q1.apply(S.Context, T);
7612 QualType ResultTy = S.Context.getLValueReferenceType(T);
Richard Smith958ba642013-05-05 15:51:06 +00007613 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007614 }
7615 }
7616 }
7617
7618 // Note that we don't consider the first argument, since it has been
7619 // contextually converted to bool long ago. The candidates below are
7620 // therefore added as binary.
7621 //
7622 // C++ [over.built]p25:
7623 // For every type T, where T is a pointer, pointer-to-member, or scoped
7624 // enumeration type, there exist candidate operator functions of the form
7625 //
7626 // T operator?(bool, T, T);
7627 //
7628 void addConditionalOperatorOverloads() {
7629 /// Set of (canonical) types that we've already handled.
7630 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7631
7632 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7633 for (BuiltinCandidateTypeSet::iterator
7634 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7635 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7636 Ptr != PtrEnd; ++Ptr) {
7637 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7638 continue;
7639
7640 QualType ParamTypes[2] = { *Ptr, *Ptr };
Richard Smith958ba642013-05-05 15:51:06 +00007641 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007642 }
7643
7644 for (BuiltinCandidateTypeSet::iterator
7645 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7646 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7647 MemPtr != MemPtrEnd; ++MemPtr) {
7648 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7649 continue;
7650
7651 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
Richard Smith958ba642013-05-05 15:51:06 +00007652 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007653 }
7654
Richard Smith80ad52f2013-01-02 11:42:31 +00007655 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007656 for (BuiltinCandidateTypeSet::iterator
7657 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7658 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7659 Enum != EnumEnd; ++Enum) {
7660 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7661 continue;
7662
7663 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7664 continue;
7665
7666 QualType ParamTypes[2] = { *Enum, *Enum };
Richard Smith958ba642013-05-05 15:51:06 +00007667 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007668 }
7669 }
7670 }
7671 }
7672};
7673
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007674} // end anonymous namespace
7675
7676/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7677/// operator overloads to the candidate set (C++ [over.built]), based
7678/// on the operator @p Op and the arguments given. For example, if the
7679/// operator is a binary '+', this routine might add "int
7680/// operator+(int, int)" to cover integer addition.
7681void
7682Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7683 SourceLocation OpLoc,
Richard Smith958ba642013-05-05 15:51:06 +00007684 llvm::ArrayRef<Expr *> Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007685 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007686 // Find all of the types that the arguments can convert to, but only
7687 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007688 // that make use of these types. Also record whether we encounter non-record
7689 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007690 Qualifiers VisibleTypeConversionsQuals;
7691 VisibleTypeConversionsQuals.addConst();
Richard Smith958ba642013-05-05 15:51:06 +00007692 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx)
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007693 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007694
7695 bool HasNonRecordCandidateType = false;
7696 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007697 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Richard Smith958ba642013-05-05 15:51:06 +00007698 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Douglas Gregorfec56e72010-11-03 17:00:07 +00007699 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7700 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7701 OpLoc,
7702 true,
7703 (Op == OO_Exclaim ||
7704 Op == OO_AmpAmp ||
7705 Op == OO_PipePipe),
7706 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007707 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7708 CandidateTypes[ArgIdx].hasNonRecordTypes();
7709 HasArithmeticOrEnumeralCandidateType =
7710 HasArithmeticOrEnumeralCandidateType ||
7711 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007712 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007713
Chandler Carruth6a577462010-12-13 01:44:01 +00007714 // Exit early when no non-record types have been added to the candidate set
7715 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007716 //
7717 // We can't exit early for !, ||, or &&, since there we have always have
7718 // 'bool' overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007719 if (!HasNonRecordCandidateType &&
Douglas Gregor25aaff92011-10-10 14:05:31 +00007720 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007721 return;
7722
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007723 // Setup an object to manage the common state for building overloads.
Richard Smith958ba642013-05-05 15:51:06 +00007724 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007725 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007726 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007727 CandidateTypes, CandidateSet);
7728
7729 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007730 switch (Op) {
7731 case OO_None:
7732 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007733 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007734
Chandler Carruthabb71842010-12-12 08:51:33 +00007735 case OO_New:
7736 case OO_Delete:
7737 case OO_Array_New:
7738 case OO_Array_Delete:
7739 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007740 llvm_unreachable(
7741 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007742
7743 case OO_Comma:
7744 case OO_Arrow:
7745 // C++ [over.match.oper]p3:
7746 // -- For the operator ',', the unary operator '&', or the
7747 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007748 break;
7749
7750 case OO_Plus: // '+' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007751 if (Args.size() == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007752 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007753 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007754
7755 case OO_Minus: // '-' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007756 if (Args.size() == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007757 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007758 } else {
7759 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7760 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7761 }
Douglas Gregor74253732008-11-19 15:42:04 +00007762 break;
7763
Chandler Carruthabb71842010-12-12 08:51:33 +00007764 case OO_Star: // '*' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007765 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007766 OpBuilder.addUnaryStarPointerOverloads();
7767 else
7768 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7769 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007770
Chandler Carruthabb71842010-12-12 08:51:33 +00007771 case OO_Slash:
7772 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007773 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007774
7775 case OO_PlusPlus:
7776 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007777 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7778 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007779 break;
7780
Douglas Gregor19b7b152009-08-24 13:43:27 +00007781 case OO_EqualEqual:
7782 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007783 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007784 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007785
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007786 case OO_Less:
7787 case OO_Greater:
7788 case OO_LessEqual:
7789 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007790 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007791 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7792 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007793
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007794 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007795 case OO_Caret:
7796 case OO_Pipe:
7797 case OO_LessLess:
7798 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007799 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007800 break;
7801
Chandler Carruthabb71842010-12-12 08:51:33 +00007802 case OO_Amp: // '&' is either unary or binary
Richard Smith958ba642013-05-05 15:51:06 +00007803 if (Args.size() == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007804 // C++ [over.match.oper]p3:
7805 // -- For the operator ',', the unary operator '&', or the
7806 // operator '->', the built-in candidates set is empty.
7807 break;
7808
7809 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7810 break;
7811
7812 case OO_Tilde:
7813 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7814 break;
7815
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007816 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007817 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007818 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007819
7820 case OO_PlusEqual:
7821 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007822 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007823 // Fall through.
7824
7825 case OO_StarEqual:
7826 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007827 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007828 break;
7829
7830 case OO_PercentEqual:
7831 case OO_LessLessEqual:
7832 case OO_GreaterGreaterEqual:
7833 case OO_AmpEqual:
7834 case OO_CaretEqual:
7835 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007836 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007837 break;
7838
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007839 case OO_Exclaim:
7840 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007841 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007842
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007843 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007844 case OO_PipePipe:
7845 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007846 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007847
7848 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007849 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007850 break;
7851
7852 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007853 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007854 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007855
7856 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007857 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007858 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7859 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007860 }
7861}
7862
Douglas Gregorfa047642009-02-04 00:32:51 +00007863/// \brief Add function candidates found via argument-dependent lookup
7864/// to the set of overloading candidates.
7865///
7866/// This routine performs argument-dependent name lookup based on the
7867/// given function name (which may also be an operator name) and adds
7868/// all of the overload candidates found by ADL to the overload
7869/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007870void
Douglas Gregorfa047642009-02-04 00:32:51 +00007871Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007872 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007873 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007874 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007875 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007876 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007877 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007878
John McCalla113e722010-01-26 06:04:06 +00007879 // FIXME: This approach for uniquing ADL results (and removing
7880 // redundant candidates from the set) relies on pointer-equality,
7881 // which means we need to key off the canonical decl. However,
7882 // always going back to the canonical decl might not get us the
7883 // right set of default arguments. What default arguments are
7884 // we supposed to consider on ADL candidates, anyway?
7885
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007886 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007887 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007888
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007889 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007890 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7891 CandEnd = CandidateSet.end();
7892 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007893 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007894 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007895 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007896 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007897 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007898
7899 // For each of the ADL candidates we found, add it to the overload
7900 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007901 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007902 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007903 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007904 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007905 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007906
Ahmed Charles13a140c2012-02-25 11:00:22 +00007907 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7908 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007909 } else
John McCall6e266892010-01-26 03:27:55 +00007910 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007911 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007912 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007913 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007914}
7915
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007916/// isBetterOverloadCandidate - Determines whether the first overload
7917/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007918bool
John McCall120d63c2010-08-24 20:38:10 +00007919isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007920 const OverloadCandidate &Cand1,
7921 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007922 SourceLocation Loc,
7923 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007924 // Define viable functions to be better candidates than non-viable
7925 // functions.
7926 if (!Cand2.Viable)
7927 return Cand1.Viable;
7928 else if (!Cand1.Viable)
7929 return false;
7930
Douglas Gregor88a35142008-12-22 05:46:06 +00007931 // C++ [over.match.best]p1:
7932 //
7933 // -- if F is a static member function, ICS1(F) is defined such
7934 // that ICS1(F) is neither better nor worse than ICS1(G) for
7935 // any function G, and, symmetrically, ICS1(G) is neither
7936 // better nor worse than ICS1(F).
7937 unsigned StartArg = 0;
7938 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7939 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007940
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007941 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007942 // A viable function F1 is defined to be a better function than another
7943 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007944 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007945 unsigned NumArgs = Cand1.NumConversions;
7946 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007947 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007948 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007949 switch (CompareImplicitConversionSequences(S,
7950 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007951 Cand2.Conversions[ArgIdx])) {
7952 case ImplicitConversionSequence::Better:
7953 // Cand1 has a better conversion sequence.
7954 HasBetterConversion = true;
7955 break;
7956
7957 case ImplicitConversionSequence::Worse:
7958 // Cand1 can't be better than Cand2.
7959 return false;
7960
7961 case ImplicitConversionSequence::Indistinguishable:
7962 // Do nothing.
7963 break;
7964 }
7965 }
7966
Mike Stump1eb44332009-09-09 15:08:12 +00007967 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007968 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007969 if (HasBetterConversion)
7970 return true;
7971
Mike Stump1eb44332009-09-09 15:08:12 +00007972 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007973 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007974 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007975 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7976 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007977
7978 // -- F1 and F2 are function template specializations, and the function
7979 // template for F1 is more specialized than the template for F2
7980 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007981 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007982 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007983 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007984 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007985 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7986 Cand2.Function->getPrimaryTemplate(),
7987 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007988 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007989 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007990 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007991 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007992 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007993
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007994 // -- the context is an initialization by user-defined conversion
7995 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7996 // from the return type of F1 to the destination type (i.e.,
7997 // the type of the entity being initialized) is a better
7998 // conversion sequence than the standard conversion sequence
7999 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008000 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00008001 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008002 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00008003 // First check whether we prefer one of the conversion functions over the
8004 // other. This only distinguishes the results in non-standard, extension
8005 // cases such as the conversion from a lambda closure type to a function
8006 // pointer or block.
8007 ImplicitConversionSequence::CompareKind FuncResult
8008 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
8009 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
8010 return FuncResult;
8011
John McCall120d63c2010-08-24 20:38:10 +00008012 switch (CompareStandardConversionSequences(S,
8013 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00008014 Cand2.FinalConversion)) {
8015 case ImplicitConversionSequence::Better:
8016 // Cand1 has a better conversion sequence.
8017 return true;
8018
8019 case ImplicitConversionSequence::Worse:
8020 // Cand1 can't be better than Cand2.
8021 return false;
8022
8023 case ImplicitConversionSequence::Indistinguishable:
8024 // Do nothing
8025 break;
8026 }
8027 }
8028
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008029 return false;
8030}
8031
Mike Stump1eb44332009-09-09 15:08:12 +00008032/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00008033/// within an overload candidate set.
8034///
James Dennettefce31f2012-06-22 08:10:18 +00008035/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00008036/// which overload resolution occurs.
8037///
James Dennettefce31f2012-06-22 08:10:18 +00008038/// \param Best If overload resolution was successful or found a deleted
8039/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00008040///
8041/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00008042OverloadingResult
8043OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00008044 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00008045 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008046 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00008047 Best = end();
8048 for (iterator Cand = begin(); Cand != end(); ++Cand) {
8049 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008050 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008051 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008052 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008053 }
8054
8055 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00008056 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008057 return OR_No_Viable_Function;
8058
8059 // Make sure that this function is better than every other viable
8060 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00008061 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00008062 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008063 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008064 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00008065 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00008066 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008067 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008068 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008069 }
Mike Stump1eb44332009-09-09 15:08:12 +00008070
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008071 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008072 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008073 (Best->Function->isDeleted() ||
8074 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008075 return OR_Deleted;
8076
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008077 return OR_Success;
8078}
8079
John McCall3c80f572010-01-12 02:15:36 +00008080namespace {
8081
8082enum OverloadCandidateKind {
8083 oc_function,
8084 oc_method,
8085 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00008086 oc_function_template,
8087 oc_method_template,
8088 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00008089 oc_implicit_default_constructor,
8090 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00008091 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008092 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00008093 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00008094 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00008095};
8096
John McCall220ccbf2010-01-13 00:25:19 +00008097OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
8098 FunctionDecl *Fn,
8099 std::string &Description) {
8100 bool isTemplate = false;
8101
8102 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
8103 isTemplate = true;
8104 Description = S.getTemplateArgumentBindingsText(
8105 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
8106 }
John McCallb1622a12010-01-06 09:43:14 +00008107
8108 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00008109 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008110 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008111
Sebastian Redlf677ea32011-02-05 19:23:19 +00008112 if (Ctor->getInheritedConstructor())
8113 return oc_implicit_inherited_constructor;
8114
Sean Hunt82713172011-05-25 23:16:36 +00008115 if (Ctor->isDefaultConstructor())
8116 return oc_implicit_default_constructor;
8117
8118 if (Ctor->isMoveConstructor())
8119 return oc_implicit_move_constructor;
8120
8121 assert(Ctor->isCopyConstructor() &&
8122 "unexpected sort of implicit constructor");
8123 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00008124 }
8125
8126 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
8127 // This actually gets spelled 'candidate function' for now, but
8128 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00008129 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00008130 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00008131
Sean Hunt82713172011-05-25 23:16:36 +00008132 if (Meth->isMoveAssignmentOperator())
8133 return oc_implicit_move_assignment;
8134
Douglas Gregoref7d78b2012-02-10 08:36:38 +00008135 if (Meth->isCopyAssignmentOperator())
8136 return oc_implicit_copy_assignment;
8137
8138 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
8139 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00008140 }
8141
John McCall220ccbf2010-01-13 00:25:19 +00008142 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00008143}
8144
Sebastian Redlf677ea32011-02-05 19:23:19 +00008145void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
8146 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8147 if (!Ctor) return;
8148
8149 Ctor = Ctor->getInheritedConstructor();
8150 if (!Ctor) return;
8151
8152 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8153}
8154
John McCall3c80f572010-01-12 02:15:36 +00008155} // end anonymous namespace
8156
8157// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008158void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008159 std::string FnDesc;
8160 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008161 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8162 << (unsigned) K << FnDesc;
8163 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8164 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008165 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008166}
8167
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008168//Notes the location of all overload candidates designated through
8169// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008170void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008171 assert(OverloadedExpr->getType() == Context.OverloadTy);
8172
8173 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8174 OverloadExpr *OvlExpr = Ovl.Expression;
8175
8176 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8177 IEnd = OvlExpr->decls_end();
8178 I != IEnd; ++I) {
8179 if (FunctionTemplateDecl *FunTmpl =
8180 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008181 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008182 } else if (FunctionDecl *Fun
8183 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008184 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008185 }
8186 }
8187}
8188
John McCall1d318332010-01-12 00:44:57 +00008189/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8190/// "lead" diagnostic; it will be given two arguments, the source and
8191/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008192void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8193 Sema &S,
8194 SourceLocation CaretLoc,
8195 const PartialDiagnostic &PDiag) const {
8196 S.Diag(CaretLoc, PDiag)
8197 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008198 // FIXME: The note limiting machinery is borrowed from
8199 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8200 // refactoring here.
8201 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8202 unsigned CandsShown = 0;
8203 AmbiguousConversionSequence::const_iterator I, E;
8204 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8205 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8206 break;
8207 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008208 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008209 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008210 if (I != E)
8211 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008212}
8213
John McCall1d318332010-01-12 00:44:57 +00008214namespace {
8215
John McCalladbb8f82010-01-13 09:16:55 +00008216void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8217 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8218 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008219 assert(Cand->Function && "for now, candidate must be a function");
8220 FunctionDecl *Fn = Cand->Function;
8221
8222 // There's a conversion slot for the object argument if this is a
8223 // non-constructor method. Note that 'I' corresponds the
8224 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008225 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008226 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008227 if (I == 0)
8228 isObjectArgument = true;
8229 else
8230 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008231 }
8232
John McCall220ccbf2010-01-13 00:25:19 +00008233 std::string FnDesc;
8234 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8235
John McCalladbb8f82010-01-13 09:16:55 +00008236 Expr *FromExpr = Conv.Bad.FromExpr;
8237 QualType FromTy = Conv.Bad.getFromType();
8238 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008239
John McCall5920dbb2010-02-02 02:42:52 +00008240 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008241 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008242 Expr *E = FromExpr->IgnoreParens();
8243 if (isa<UnaryOperator>(E))
8244 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008245 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008246
8247 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8248 << (unsigned) FnKind << FnDesc
8249 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8250 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008251 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008252 return;
8253 }
8254
John McCall258b2032010-01-23 08:10:49 +00008255 // Do some hand-waving analysis to see if the non-viability is due
8256 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008257 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8258 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8259 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8260 CToTy = RT->getPointeeType();
8261 else {
8262 // TODO: detect and diagnose the full richness of const mismatches.
8263 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8264 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8265 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8266 }
8267
8268 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8269 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008270 Qualifiers FromQs = CFromTy.getQualifiers();
8271 Qualifiers ToQs = CToTy.getQualifiers();
8272
8273 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8274 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8275 << (unsigned) FnKind << FnDesc
8276 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8277 << FromTy
8278 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8279 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008280 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008281 return;
8282 }
8283
John McCallf85e1932011-06-15 23:02:42 +00008284 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008285 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008286 << (unsigned) FnKind << FnDesc
8287 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8288 << FromTy
8289 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8290 << (unsigned) isObjectArgument << I+1;
8291 MaybeEmitInheritedConstructorNote(S, Fn);
8292 return;
8293 }
8294
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008295 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8297 << (unsigned) FnKind << FnDesc
8298 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8299 << FromTy
8300 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8301 << (unsigned) isObjectArgument << I+1;
8302 MaybeEmitInheritedConstructorNote(S, Fn);
8303 return;
8304 }
8305
John McCall651f3ee2010-01-14 03:28:57 +00008306 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8307 assert(CVR && "unexpected qualifiers mismatch");
8308
8309 if (isObjectArgument) {
8310 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8311 << (unsigned) FnKind << FnDesc
8312 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8313 << FromTy << (CVR - 1);
8314 } else {
8315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8316 << (unsigned) FnKind << FnDesc
8317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8318 << FromTy << (CVR - 1) << I+1;
8319 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008320 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008321 return;
8322 }
8323
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008324 // Special diagnostic for failure to convert an initializer list, since
8325 // telling the user that it has type void is not useful.
8326 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8327 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8328 << (unsigned) FnKind << FnDesc
8329 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8330 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8331 MaybeEmitInheritedConstructorNote(S, Fn);
8332 return;
8333 }
8334
John McCall258b2032010-01-23 08:10:49 +00008335 // Diagnose references or pointers to incomplete types differently,
8336 // since it's far from impossible that the incompleteness triggered
8337 // the failure.
8338 QualType TempFromTy = FromTy.getNonReferenceType();
8339 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8340 TempFromTy = PTy->getPointeeType();
8341 if (TempFromTy->isIncompleteType()) {
8342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8343 << (unsigned) FnKind << FnDesc
8344 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8345 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008346 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008347 return;
8348 }
8349
Douglas Gregor85789812010-06-30 23:01:39 +00008350 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008351 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008352 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8353 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8354 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8355 FromPtrTy->getPointeeType()) &&
8356 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8357 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008358 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008359 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008360 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008361 }
8362 } else if (const ObjCObjectPointerType *FromPtrTy
8363 = FromTy->getAs<ObjCObjectPointerType>()) {
8364 if (const ObjCObjectPointerType *ToPtrTy
8365 = ToTy->getAs<ObjCObjectPointerType>())
8366 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8367 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8368 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8369 FromPtrTy->getPointeeType()) &&
8370 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008371 BaseToDerivedConversion = 2;
8372 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008373 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8374 !FromTy->isIncompleteType() &&
8375 !ToRefTy->getPointeeType()->isIncompleteType() &&
8376 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8377 BaseToDerivedConversion = 3;
8378 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8379 ToTy.getNonReferenceType().getCanonicalType() ==
8380 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008381 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8382 << (unsigned) FnKind << FnDesc
8383 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8384 << (unsigned) isObjectArgument << I + 1;
8385 MaybeEmitInheritedConstructorNote(S, Fn);
8386 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008387 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008389
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008390 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008391 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008392 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008393 << (unsigned) FnKind << FnDesc
8394 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008395 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008396 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008397 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008398 return;
8399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008400
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008401 if (isa<ObjCObjectPointerType>(CFromTy) &&
8402 isa<PointerType>(CToTy)) {
8403 Qualifiers FromQs = CFromTy.getQualifiers();
8404 Qualifiers ToQs = CToTy.getQualifiers();
8405 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8406 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8407 << (unsigned) FnKind << FnDesc
8408 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8409 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8410 MaybeEmitInheritedConstructorNote(S, Fn);
8411 return;
8412 }
8413 }
8414
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008415 // Emit the generic diagnostic and, optionally, add the hints to it.
8416 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8417 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008418 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008419 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8420 << (unsigned) (Cand->Fix.Kind);
8421
8422 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008423 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8424 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008425 FDiag << *HI;
8426 S.Diag(Fn->getLocation(), FDiag);
8427
Sebastian Redlf677ea32011-02-05 19:23:19 +00008428 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008429}
8430
8431void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8432 unsigned NumFormalArgs) {
8433 // TODO: treat calls to a missing default constructor as a special case
8434
8435 FunctionDecl *Fn = Cand->Function;
8436 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8437
8438 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008439
Douglas Gregor439d3c32011-05-05 00:13:13 +00008440 // With invalid overloaded operators, it's possible that we think we
8441 // have an arity mismatch when it fact it looks like we have the
8442 // right number of arguments, because only overloaded operators have
8443 // the weird behavior of overloading member and non-member functions.
8444 // Just don't report anything.
8445 if (Fn->isInvalidDecl() &&
8446 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8447 return;
8448
John McCalladbb8f82010-01-13 09:16:55 +00008449 // at least / at most / exactly
8450 unsigned mode, modeCount;
8451 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008452 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8453 (Cand->FailureKind == ovl_fail_bad_deduction &&
8454 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008455 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008456 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008457 mode = 0; // "at least"
8458 else
8459 mode = 2; // "exactly"
8460 modeCount = MinParams;
8461 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008462 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8463 (Cand->FailureKind == ovl_fail_bad_deduction &&
8464 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008465 if (MinParams != FnTy->getNumArgs())
8466 mode = 1; // "at most"
8467 else
8468 mode = 2; // "exactly"
8469 modeCount = FnTy->getNumArgs();
8470 }
8471
8472 std::string Description;
8473 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8474
Richard Smithf7b80562012-05-11 05:16:41 +00008475 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8476 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8477 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8478 << Fn->getParamDecl(0) << NumFormalArgs;
8479 else
8480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8481 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8482 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008483 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008484}
8485
John McCall342fec42010-02-01 18:53:26 +00008486/// Diagnose a failed template-argument deduction.
8487void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008488 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008489 FunctionDecl *Fn = Cand->Function; // pattern
8490
Douglas Gregora9333192010-05-08 17:41:32 +00008491 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008492 NamedDecl *ParamD;
8493 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8494 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8495 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008496 switch (Cand->DeductionFailure.Result) {
8497 case Sema::TDK_Success:
8498 llvm_unreachable("TDK_success while diagnosing bad deduction");
8499
8500 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008501 assert(ParamD && "no parameter found for incomplete deduction result");
8502 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8503 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008504 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008505 return;
8506 }
8507
John McCall57e97782010-08-05 09:05:08 +00008508 case Sema::TDK_Underqualified: {
8509 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8510 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8511
8512 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8513
8514 // Param will have been canonicalized, but it should just be a
8515 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008516 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008517 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008518 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008519 assert(S.Context.hasSameType(Param, NonCanonParam));
8520
8521 // Arg has also been canonicalized, but there's nothing we can do
8522 // about that. It also doesn't matter as much, because it won't
8523 // have any template parameters in it (because deduction isn't
8524 // done on dependent types).
8525 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8526
8527 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8528 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008529 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008530 return;
8531 }
8532
8533 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008534 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008535 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008536 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008537 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008538 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008539 which = 1;
8540 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008541 which = 2;
8542 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008543
Douglas Gregora9333192010-05-08 17:41:32 +00008544 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008545 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008546 << *Cand->DeductionFailure.getFirstArg()
8547 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008548 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008549 return;
8550 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008551
Douglas Gregorf1a84452010-05-08 19:15:54 +00008552 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008553 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008554 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008555 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008556 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8557 << ParamD->getDeclName();
8558 else {
8559 int index = 0;
8560 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8561 index = TTP->getIndex();
8562 else if (NonTypeTemplateParmDecl *NTTP
8563 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8564 index = NTTP->getIndex();
8565 else
8566 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008567 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008568 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8569 << (index + 1);
8570 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008571 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008572 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008573
Douglas Gregora18592e2010-05-08 18:13:28 +00008574 case Sema::TDK_TooManyArguments:
8575 case Sema::TDK_TooFewArguments:
8576 DiagnoseArityMismatch(S, Cand, NumArgs);
8577 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008578
8579 case Sema::TDK_InstantiationDepth:
8580 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008581 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008582 return;
8583
8584 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008585 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008586 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008587 if (TemplateArgumentList *Args =
8588 Cand->DeductionFailure.getTemplateArgumentList()) {
8589 TemplateArgString = " ";
8590 TemplateArgString += S.getTemplateArgumentBindingsText(
8591 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8592 }
8593
Richard Smith4493c0a2012-05-09 05:17:00 +00008594 // If this candidate was disabled by enable_if, say so.
8595 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8596 if (PDiag && PDiag->second.getDiagID() ==
8597 diag::err_typename_nested_not_found_enable_if) {
8598 // FIXME: Use the source range of the condition, and the fully-qualified
8599 // name of the enable_if template. These are both present in PDiag.
8600 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8601 << "'enable_if'" << TemplateArgString;
8602 return;
8603 }
8604
Richard Smithb8590f32012-05-07 09:03:25 +00008605 // Format the SFINAE diagnostic into the argument string.
8606 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8607 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008608 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008609 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008610 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008611 SFINAEArgString = ": ";
8612 R = SourceRange(PDiag->first, PDiag->first);
8613 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8614 }
8615
Douglas Gregorec20f462010-05-08 20:07:26 +00008616 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008617 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008618 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008619 return;
8620 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008621
Richard Smith0efa62f2013-01-31 04:03:12 +00008622 case Sema::TDK_FailedOverloadResolution: {
8623 OverloadExpr::FindResult R =
8624 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8625 S.Diag(Fn->getLocation(),
8626 diag::note_ovl_candidate_failed_overload_resolution)
8627 << R.Expression->getName();
8628 return;
8629 }
8630
Richard Trieueef35f82013-04-08 21:11:40 +00008631 case Sema::TDK_NonDeducedMismatch: {
Richard Smith29805ca2013-01-31 05:19:49 +00008632 // FIXME: Provide a source location to indicate what we couldn't match.
Richard Trieueef35f82013-04-08 21:11:40 +00008633 TemplateArgument FirstTA = *Cand->DeductionFailure.getFirstArg();
8634 TemplateArgument SecondTA = *Cand->DeductionFailure.getSecondArg();
8635 if (FirstTA.getKind() == TemplateArgument::Template &&
8636 SecondTA.getKind() == TemplateArgument::Template) {
8637 TemplateName FirstTN = FirstTA.getAsTemplate();
8638 TemplateName SecondTN = SecondTA.getAsTemplate();
8639 if (FirstTN.getKind() == TemplateName::Template &&
8640 SecondTN.getKind() == TemplateName::Template) {
8641 if (FirstTN.getAsTemplateDecl()->getName() ==
8642 SecondTN.getAsTemplateDecl()->getName()) {
8643 // FIXME: This fixes a bad diagnostic where both templates are named
8644 // the same. This particular case is a bit difficult since:
8645 // 1) It is passed as a string to the diagnostic printer.
8646 // 2) The diagnostic printer only attempts to find a better
8647 // name for types, not decls.
8648 // Ideally, this should folded into the diagnostic printer.
8649 S.Diag(Fn->getLocation(),
8650 diag::note_ovl_candidate_non_deduced_mismatch_qualified)
8651 << FirstTN.getAsTemplateDecl() << SecondTN.getAsTemplateDecl();
8652 return;
8653 }
8654 }
8655 }
Richard Smith29805ca2013-01-31 05:19:49 +00008656 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
Richard Trieueef35f82013-04-08 21:11:40 +00008657 << FirstTA << SecondTA;
Richard Smith29805ca2013-01-31 05:19:49 +00008658 return;
Richard Trieueef35f82013-04-08 21:11:40 +00008659 }
John McCall342fec42010-02-01 18:53:26 +00008660 // TODO: diagnose these individually, then kill off
8661 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008662 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008663 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008664 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008665 return;
8666 }
8667}
8668
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008669/// CUDA: diagnose an invalid call across targets.
8670void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8671 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8672 FunctionDecl *Callee = Cand->Function;
8673
8674 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8675 CalleeTarget = S.IdentifyCUDATarget(Callee);
8676
8677 std::string FnDesc;
8678 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8679
8680 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8681 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8682}
8683
John McCall342fec42010-02-01 18:53:26 +00008684/// Generates a 'note' diagnostic for an overload candidate. We've
8685/// already generated a primary error at the call site.
8686///
8687/// It really does need to be a single diagnostic with its caret
8688/// pointed at the candidate declaration. Yes, this creates some
8689/// major challenges of technical writing. Yes, this makes pointing
8690/// out problems with specific arguments quite awkward. It's still
8691/// better than generating twenty screens of text for every failed
8692/// overload.
8693///
8694/// It would be great to be able to express per-candidate problems
8695/// more richly for those diagnostic clients that cared, but we'd
8696/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008697void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008698 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008699 FunctionDecl *Fn = Cand->Function;
8700
John McCall81201622010-01-08 04:41:39 +00008701 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008702 if (Cand->Viable && (Fn->isDeleted() ||
8703 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008704 std::string FnDesc;
8705 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008706
8707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008708 << FnKind << FnDesc
8709 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008710 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008711 return;
John McCall81201622010-01-08 04:41:39 +00008712 }
8713
John McCall220ccbf2010-01-13 00:25:19 +00008714 // We don't really have anything else to say about viable candidates.
8715 if (Cand->Viable) {
8716 S.NoteOverloadCandidate(Fn);
8717 return;
8718 }
John McCall1d318332010-01-12 00:44:57 +00008719
John McCalladbb8f82010-01-13 09:16:55 +00008720 switch (Cand->FailureKind) {
8721 case ovl_fail_too_many_arguments:
8722 case ovl_fail_too_few_arguments:
8723 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008724
John McCalladbb8f82010-01-13 09:16:55 +00008725 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008726 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008727
John McCall717e8912010-01-23 05:17:32 +00008728 case ovl_fail_trivial_conversion:
8729 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008730 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008731 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008732
John McCallb1bdc622010-02-25 01:37:24 +00008733 case ovl_fail_bad_conversion: {
8734 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008735 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008736 if (Cand->Conversions[I].isBad())
8737 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008738
John McCalladbb8f82010-01-13 09:16:55 +00008739 // FIXME: this currently happens when we're called from SemaInit
8740 // when user-conversion overload fails. Figure out how to handle
8741 // those conditions and diagnose them well.
8742 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008743 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008744
8745 case ovl_fail_bad_target:
8746 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008747 }
John McCalla1d7d622010-01-08 00:58:21 +00008748}
8749
8750void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8751 // Desugar the type of the surrogate down to a function type,
8752 // retaining as many typedefs as possible while still showing
8753 // the function type (and, therefore, its parameter types).
8754 QualType FnType = Cand->Surrogate->getConversionType();
8755 bool isLValueReference = false;
8756 bool isRValueReference = false;
8757 bool isPointer = false;
8758 if (const LValueReferenceType *FnTypeRef =
8759 FnType->getAs<LValueReferenceType>()) {
8760 FnType = FnTypeRef->getPointeeType();
8761 isLValueReference = true;
8762 } else if (const RValueReferenceType *FnTypeRef =
8763 FnType->getAs<RValueReferenceType>()) {
8764 FnType = FnTypeRef->getPointeeType();
8765 isRValueReference = true;
8766 }
8767 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8768 FnType = FnTypePtr->getPointeeType();
8769 isPointer = true;
8770 }
8771 // Desugar down to a function type.
8772 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8773 // Reconstruct the pointer/reference as appropriate.
8774 if (isPointer) FnType = S.Context.getPointerType(FnType);
8775 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8776 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8777
8778 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8779 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008780 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008781}
8782
8783void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008784 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008785 SourceLocation OpLoc,
8786 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008787 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008788 std::string TypeStr("operator");
8789 TypeStr += Opc;
8790 TypeStr += "(";
8791 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008792 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008793 TypeStr += ")";
8794 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8795 } else {
8796 TypeStr += ", ";
8797 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8798 TypeStr += ")";
8799 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8800 }
8801}
8802
8803void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8804 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008805 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008806 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8807 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008808 if (ICS.isBad()) break; // all meaningless after first invalid
8809 if (!ICS.isAmbiguous()) continue;
8810
John McCall120d63c2010-08-24 20:38:10 +00008811 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008812 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008813 }
8814}
8815
John McCall1b77e732010-01-15 23:32:50 +00008816SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8817 if (Cand->Function)
8818 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008819 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008820 return Cand->Surrogate->getLocation();
8821 return SourceLocation();
8822}
8823
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008824static unsigned
8825RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008826 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008827 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008828 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008829
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008830 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008831 case Sema::TDK_Incomplete:
8832 return 1;
8833
8834 case Sema::TDK_Underqualified:
8835 case Sema::TDK_Inconsistent:
8836 return 2;
8837
8838 case Sema::TDK_SubstitutionFailure:
8839 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008840 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008841 return 3;
8842
8843 case Sema::TDK_InstantiationDepth:
8844 case Sema::TDK_FailedOverloadResolution:
8845 return 4;
8846
8847 case Sema::TDK_InvalidExplicitArguments:
8848 return 5;
8849
8850 case Sema::TDK_TooManyArguments:
8851 case Sema::TDK_TooFewArguments:
8852 return 6;
8853 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008854 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008855}
8856
John McCallbf65c0b2010-01-12 00:48:53 +00008857struct CompareOverloadCandidatesForDisplay {
8858 Sema &S;
8859 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008860
8861 bool operator()(const OverloadCandidate *L,
8862 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008863 // Fast-path this check.
8864 if (L == R) return false;
8865
John McCall81201622010-01-08 04:41:39 +00008866 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008867 if (L->Viable) {
8868 if (!R->Viable) return true;
8869
8870 // TODO: introduce a tri-valued comparison for overload
8871 // candidates. Would be more worthwhile if we had a sort
8872 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008873 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8874 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008875 } else if (R->Viable)
8876 return false;
John McCall81201622010-01-08 04:41:39 +00008877
John McCall1b77e732010-01-15 23:32:50 +00008878 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008879
John McCall1b77e732010-01-15 23:32:50 +00008880 // Criteria by which we can sort non-viable candidates:
8881 if (!L->Viable) {
8882 // 1. Arity mismatches come after other candidates.
8883 if (L->FailureKind == ovl_fail_too_many_arguments ||
8884 L->FailureKind == ovl_fail_too_few_arguments)
8885 return false;
8886 if (R->FailureKind == ovl_fail_too_many_arguments ||
8887 R->FailureKind == ovl_fail_too_few_arguments)
8888 return true;
John McCall81201622010-01-08 04:41:39 +00008889
John McCall717e8912010-01-23 05:17:32 +00008890 // 2. Bad conversions come first and are ordered by the number
8891 // of bad conversions and quality of good conversions.
8892 if (L->FailureKind == ovl_fail_bad_conversion) {
8893 if (R->FailureKind != ovl_fail_bad_conversion)
8894 return true;
8895
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008896 // The conversion that can be fixed with a smaller number of changes,
8897 // comes first.
8898 unsigned numLFixes = L->Fix.NumConversionsFixed;
8899 unsigned numRFixes = R->Fix.NumConversionsFixed;
8900 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8901 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008902 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008903 if (numLFixes < numRFixes)
8904 return true;
8905 else
8906 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008907 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008908
John McCall717e8912010-01-23 05:17:32 +00008909 // If there's any ordering between the defined conversions...
8910 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008911 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008912
8913 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008914 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008915 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008916 switch (CompareImplicitConversionSequences(S,
8917 L->Conversions[I],
8918 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008919 case ImplicitConversionSequence::Better:
8920 leftBetter++;
8921 break;
8922
8923 case ImplicitConversionSequence::Worse:
8924 leftBetter--;
8925 break;
8926
8927 case ImplicitConversionSequence::Indistinguishable:
8928 break;
8929 }
8930 }
8931 if (leftBetter > 0) return true;
8932 if (leftBetter < 0) return false;
8933
8934 } else if (R->FailureKind == ovl_fail_bad_conversion)
8935 return false;
8936
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008937 if (L->FailureKind == ovl_fail_bad_deduction) {
8938 if (R->FailureKind != ovl_fail_bad_deduction)
8939 return true;
8940
8941 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8942 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008943 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008944 } else if (R->FailureKind == ovl_fail_bad_deduction)
8945 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008946
John McCall1b77e732010-01-15 23:32:50 +00008947 // TODO: others?
8948 }
8949
8950 // Sort everything else by location.
8951 SourceLocation LLoc = GetLocationForCandidate(L);
8952 SourceLocation RLoc = GetLocationForCandidate(R);
8953
8954 // Put candidates without locations (e.g. builtins) at the end.
8955 if (LLoc.isInvalid()) return false;
8956 if (RLoc.isInvalid()) return true;
8957
8958 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008959 }
8960};
8961
John McCall717e8912010-01-23 05:17:32 +00008962/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008963/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008964void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008965 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008966 assert(!Cand->Viable);
8967
8968 // Don't do anything on failures other than bad conversion.
8969 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8970
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008971 // We only want the FixIts if all the arguments can be corrected.
8972 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008973 // Use a implicit copy initialization to check conversion fixes.
8974 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008975
John McCall717e8912010-01-23 05:17:32 +00008976 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008977 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008978 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008979 while (true) {
8980 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8981 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008982 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008983 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008984 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008985 }
John McCall717e8912010-01-23 05:17:32 +00008986 }
8987
8988 if (ConvIdx == ConvCount)
8989 return;
8990
John McCallb1bdc622010-02-25 01:37:24 +00008991 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8992 "remaining conversion is initialized?");
8993
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008994 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008995 // operation somehow.
8996 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008997
8998 const FunctionProtoType* Proto;
8999 unsigned ArgIdx = ConvIdx;
9000
9001 if (Cand->IsSurrogate) {
9002 QualType ConvType
9003 = Cand->Surrogate->getConversionType().getNonReferenceType();
9004 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9005 ConvType = ConvPtrType->getPointeeType();
9006 Proto = ConvType->getAs<FunctionProtoType>();
9007 ArgIdx--;
9008 } else if (Cand->Function) {
9009 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
9010 if (isa<CXXMethodDecl>(Cand->Function) &&
9011 !isa<CXXConstructorDecl>(Cand->Function))
9012 ArgIdx--;
9013 } else {
9014 // Builtin binary operator with a bad first conversion.
9015 assert(ConvCount <= 3);
9016 for (; ConvIdx != ConvCount; ++ConvIdx)
9017 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009018 = TryCopyInitialization(S, Args[ConvIdx],
9019 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009020 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009021 /*InOverloadResolution*/ true,
9022 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009023 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00009024 return;
9025 }
9026
9027 // Fill in the rest of the conversions.
9028 unsigned NumArgsInProto = Proto->getNumArgs();
9029 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009030 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00009031 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00009032 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009033 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00009034 /*InOverloadResolution=*/true,
9035 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00009036 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009037 // Store the FixIt in the candidate if it exists.
9038 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00009039 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00009040 }
John McCall717e8912010-01-23 05:17:32 +00009041 else
9042 Cand->Conversions[ConvIdx].setEllipsis();
9043 }
9044}
9045
John McCalla1d7d622010-01-08 00:58:21 +00009046} // end anonymous namespace
9047
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009048/// PrintOverloadCandidates - When overload resolution fails, prints
9049/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00009050/// set.
John McCall120d63c2010-08-24 20:38:10 +00009051void OverloadCandidateSet::NoteCandidates(Sema &S,
9052 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009053 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00009054 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00009055 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00009056 // Sort the candidates by viability and position. Sorting directly would
9057 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00009058 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00009059 if (OCD == OCD_AllCandidates) Cands.reserve(size());
9060 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00009061 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00009062 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00009063 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00009064 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009065 if (Cand->Function || Cand->IsSurrogate)
9066 Cands.push_back(Cand);
9067 // Otherwise, this a non-viable builtin candidate. We do not, in general,
9068 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00009069 }
9070 }
9071
John McCallbf65c0b2010-01-12 00:48:53 +00009072 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00009073 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009074
John McCall1d318332010-01-12 00:44:57 +00009075 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00009076
Chris Lattner5f9e2722011-07-23 10:55:15 +00009077 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00009078 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009079 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00009080 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
9081 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00009082
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009083 // Set an arbitrary limit on the number of candidate functions we'll spam
9084 // the user with. FIXME: This limit should depend on details of the
9085 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00009086 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009087 break;
9088 }
9089 ++CandsShown;
9090
John McCalla1d7d622010-01-08 00:58:21 +00009091 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009092 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00009093 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00009094 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009095 else {
9096 assert(Cand->Viable &&
9097 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00009098 // Generally we only see ambiguities including viable builtin
9099 // operators if overload resolution got screwed up by an
9100 // ambiguous user-defined conversion.
9101 //
9102 // FIXME: It's quite possible for different conversions to see
9103 // different ambiguities, though.
9104 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00009105 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00009106 ReportedAmbiguousConversions = true;
9107 }
John McCalla1d7d622010-01-08 00:58:21 +00009108
John McCall1d318332010-01-12 00:44:57 +00009109 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00009110 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00009111 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009112 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00009113
9114 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00009115 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00009116}
9117
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009118// [PossiblyAFunctionType] --> [Return]
9119// NonFunctionType --> NonFunctionType
9120// R (A) --> R(A)
9121// R (*)(A) --> R (A)
9122// R (&)(A) --> R (A)
9123// R (S::*)(A) --> R (A)
9124QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
9125 QualType Ret = PossiblyAFunctionType;
9126 if (const PointerType *ToTypePtr =
9127 PossiblyAFunctionType->getAs<PointerType>())
9128 Ret = ToTypePtr->getPointeeType();
9129 else if (const ReferenceType *ToTypeRef =
9130 PossiblyAFunctionType->getAs<ReferenceType>())
9131 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00009132 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009133 PossiblyAFunctionType->getAs<MemberPointerType>())
9134 Ret = MemTypePtr->getPointeeType();
9135 Ret =
9136 Context.getCanonicalType(Ret).getUnqualifiedType();
9137 return Ret;
9138}
Douglas Gregor904eed32008-11-10 20:40:00 +00009139
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009140// A helper class to help with address of function resolution
9141// - allows us to avoid passing around all those ugly parameters
9142class AddressOfFunctionResolver
9143{
9144 Sema& S;
9145 Expr* SourceExpr;
9146 const QualType& TargetType;
9147 QualType TargetFunctionType; // Extracted function type from target type
9148
9149 bool Complain;
9150 //DeclAccessPair& ResultFunctionAccessPair;
9151 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009152
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009153 bool TargetTypeIsNonStaticMemberFunction;
9154 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009155
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009156 OverloadExpr::FindResult OvlExprInfo;
9157 OverloadExpr *OvlExpr;
9158 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00009159 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009160
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009161public:
9162 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
9163 const QualType& TargetType, bool Complain)
9164 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
9165 Complain(Complain), Context(S.getASTContext()),
9166 TargetTypeIsNonStaticMemberFunction(
9167 !!TargetType->getAs<MemberPointerType>()),
9168 FoundNonTemplateFunction(false),
9169 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9170 OvlExpr(OvlExprInfo.Expression)
9171 {
9172 ExtractUnqualifiedFunctionTypeFromTargetType();
9173
9174 if (!TargetFunctionType->isFunctionType()) {
9175 if (OvlExpr->hasExplicitTemplateArgs()) {
9176 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009177 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009178 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009179
9180 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9181 if (!Method->isStatic()) {
9182 // If the target type is a non-function type and the function
9183 // found is a non-static member function, pretend as if that was
9184 // the target, it's the only possible type to end up with.
9185 TargetTypeIsNonStaticMemberFunction = true;
9186
9187 // And skip adding the function if its not in the proper form.
9188 // We'll diagnose this due to an empty set of functions.
9189 if (!OvlExprInfo.HasFormOfMemberPointer)
9190 return;
9191 }
9192 }
9193
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009194 Matches.push_back(std::make_pair(dap,Fn));
9195 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009196 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009197 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009198 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009199
9200 if (OvlExpr->hasExplicitTemplateArgs())
9201 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009202
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009203 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9204 // C++ [over.over]p4:
9205 // If more than one function is selected, [...]
9206 if (Matches.size() > 1) {
9207 if (FoundNonTemplateFunction)
9208 EliminateAllTemplateMatches();
9209 else
9210 EliminateAllExceptMostSpecializedTemplate();
9211 }
9212 }
9213 }
9214
9215private:
9216 bool isTargetTypeAFunction() const {
9217 return TargetFunctionType->isFunctionType();
9218 }
9219
9220 // [ToType] [Return]
9221
9222 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9223 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9224 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9225 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9226 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9227 }
9228
9229 // return true if any matching specializations were found
9230 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9231 const DeclAccessPair& CurAccessFunPair) {
9232 if (CXXMethodDecl *Method
9233 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9234 // Skip non-static function templates when converting to pointer, and
9235 // static when converting to member pointer.
9236 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9237 return false;
9238 }
9239 else if (TargetTypeIsNonStaticMemberFunction)
9240 return false;
9241
9242 // C++ [over.over]p2:
9243 // If the name is a function template, template argument deduction is
9244 // done (14.8.2.2), and if the argument deduction succeeds, the
9245 // resulting template argument list is used to generate a single
9246 // function template specialization, which is added to the set of
9247 // overloaded functions considered.
9248 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009249 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009250 if (Sema::TemplateDeductionResult Result
9251 = S.DeduceTemplateArguments(FunctionTemplate,
9252 &OvlExplicitTemplateArgs,
9253 TargetFunctionType, Specialization,
Douglas Gregor092140a2013-04-17 08:45:07 +00009254 Info, /*InOverloadResolution=*/true)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009255 // FIXME: make a note of the failed deduction for diagnostics.
9256 (void)Result;
9257 return false;
9258 }
9259
Douglas Gregor092140a2013-04-17 08:45:07 +00009260 // Template argument deduction ensures that we have an exact match or
9261 // compatible pointer-to-function arguments that would be adjusted by ICS.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009262 // This function template specicalization works.
9263 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Douglas Gregor092140a2013-04-17 08:45:07 +00009264 assert(S.isSameOrCompatibleFunctionType(
9265 Context.getCanonicalType(Specialization->getType()),
9266 Context.getCanonicalType(TargetFunctionType)));
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009267 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9268 return true;
9269 }
9270
9271 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9272 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009273 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009274 // Skip non-static functions when converting to pointer, and static
9275 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009276 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9277 return false;
9278 }
9279 else if (TargetTypeIsNonStaticMemberFunction)
9280 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009281
Chandler Carruthbd647292009-12-29 06:17:27 +00009282 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009283 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009284 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9285 if (S.CheckCUDATarget(Caller, FunDecl))
9286 return false;
9287
Richard Smith60e141e2013-05-04 07:00:32 +00009288 // If any candidate has a placeholder return type, trigger its deduction
9289 // now.
9290 if (S.getLangOpts().CPlusPlus1y &&
9291 FunDecl->getResultType()->isUndeducedType() &&
9292 S.DeduceReturnType(FunDecl, SourceExpr->getLocStart(), Complain))
9293 return false;
9294
Douglas Gregor43c79c22009-12-09 00:47:37 +00009295 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009296 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9297 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009298 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9299 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009300 Matches.push_back(std::make_pair(CurAccessFunPair,
9301 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009302 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009303 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009304 }
Mike Stump1eb44332009-09-09 15:08:12 +00009305 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009306
9307 return false;
9308 }
9309
9310 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9311 bool Ret = false;
9312
9313 // If the overload expression doesn't have the form of a pointer to
9314 // member, don't try to convert it to a pointer-to-member type.
9315 if (IsInvalidFormOfPointerToMemberFunction())
9316 return false;
9317
9318 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9319 E = OvlExpr->decls_end();
9320 I != E; ++I) {
9321 // Look through any using declarations to find the underlying function.
9322 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9323
9324 // C++ [over.over]p3:
9325 // Non-member functions and static member functions match
9326 // targets of type "pointer-to-function" or "reference-to-function."
9327 // Nonstatic member functions match targets of
9328 // type "pointer-to-member-function."
9329 // Note that according to DR 247, the containing class does not matter.
9330 if (FunctionTemplateDecl *FunctionTemplate
9331 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9332 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9333 Ret = true;
9334 }
9335 // If we have explicit template arguments supplied, skip non-templates.
9336 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9337 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9338 Ret = true;
9339 }
9340 assert(Ret || Matches.empty());
9341 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009342 }
9343
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009344 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009345 // [...] and any given function template specialization F1 is
9346 // eliminated if the set contains a second function template
9347 // specialization whose function template is more specialized
9348 // than the function template of F1 according to the partial
9349 // ordering rules of 14.5.5.2.
9350
9351 // The algorithm specified above is quadratic. We instead use a
9352 // two-pass algorithm (similar to the one used to identify the
9353 // best viable function in an overload set) that identifies the
9354 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009355
9356 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9357 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9358 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009359
John McCallc373d482010-01-27 01:50:18 +00009360 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009361 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9362 TPOC_Other, 0, SourceExpr->getLocStart(),
9363 S.PDiag(),
9364 S.PDiag(diag::err_addr_ovl_ambiguous)
9365 << Matches[0].second->getDeclName(),
9366 S.PDiag(diag::note_ovl_candidate)
9367 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009368 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009369
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009370 if (Result != MatchesCopy.end()) {
9371 // Make it the first and only element
9372 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9373 Matches[0].second = cast<FunctionDecl>(*Result);
9374 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009375 }
9376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009377
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009378 void EliminateAllTemplateMatches() {
9379 // [...] any function template specializations in the set are
9380 // eliminated if the set also contains a non-template function, [...]
9381 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9382 if (Matches[I].second->getPrimaryTemplate() == 0)
9383 ++I;
9384 else {
9385 Matches[I] = Matches[--N];
9386 Matches.set_size(N);
9387 }
9388 }
9389 }
9390
9391public:
9392 void ComplainNoMatchesFound() const {
9393 assert(Matches.empty());
9394 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9395 << OvlExpr->getName() << TargetFunctionType
9396 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009397 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009398 }
9399
9400 bool IsInvalidFormOfPointerToMemberFunction() const {
9401 return TargetTypeIsNonStaticMemberFunction &&
9402 !OvlExprInfo.HasFormOfMemberPointer;
9403 }
9404
9405 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9406 // TODO: Should we condition this on whether any functions might
9407 // have matched, or is it more appropriate to do that in callers?
9408 // TODO: a fixit wouldn't hurt.
9409 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9410 << TargetType << OvlExpr->getSourceRange();
9411 }
9412
9413 void ComplainOfInvalidConversion() const {
9414 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9415 << OvlExpr->getName() << TargetType;
9416 }
9417
9418 void ComplainMultipleMatchesFound() const {
9419 assert(Matches.size() > 1);
9420 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9421 << OvlExpr->getName()
9422 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009423 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009424 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009425
9426 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9427
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009428 int getNumMatches() const { return Matches.size(); }
9429
9430 FunctionDecl* getMatchingFunctionDecl() const {
9431 if (Matches.size() != 1) return 0;
9432 return Matches[0].second;
9433 }
9434
9435 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9436 if (Matches.size() != 1) return 0;
9437 return &Matches[0].first;
9438 }
9439};
9440
9441/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9442/// an overloaded function (C++ [over.over]), where @p From is an
9443/// expression with overloaded function type and @p ToType is the type
9444/// we're trying to resolve to. For example:
9445///
9446/// @code
9447/// int f(double);
9448/// int f(int);
9449///
9450/// int (*pfd)(double) = f; // selects f(double)
9451/// @endcode
9452///
9453/// This routine returns the resulting FunctionDecl if it could be
9454/// resolved, and NULL otherwise. When @p Complain is true, this
9455/// routine will emit diagnostics if there is an error.
9456FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009457Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9458 QualType TargetType,
9459 bool Complain,
9460 DeclAccessPair &FoundResult,
9461 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009462 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009463
9464 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9465 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009466 int NumMatches = Resolver.getNumMatches();
9467 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009468 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009469 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9470 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9471 else
9472 Resolver.ComplainNoMatchesFound();
9473 }
9474 else if (NumMatches > 1 && Complain)
9475 Resolver.ComplainMultipleMatchesFound();
9476 else if (NumMatches == 1) {
9477 Fn = Resolver.getMatchingFunctionDecl();
9478 assert(Fn);
9479 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009480 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009481 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009482 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009483
9484 if (pHadMultipleCandidates)
9485 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009486 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009487}
9488
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009489/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009490/// resolve that overloaded function expression down to a single function.
9491///
9492/// This routine can only resolve template-ids that refer to a single function
9493/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009494/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009495/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009496FunctionDecl *
9497Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9498 bool Complain,
9499 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009500 // C++ [over.over]p1:
9501 // [...] [Note: any redundant set of parentheses surrounding the
9502 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009503 // C++ [over.over]p1:
9504 // [...] The overloaded function name can be preceded by the &
9505 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009506
Douglas Gregor4b52e252009-12-21 23:17:24 +00009507 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009508 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009509 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009510
9511 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009512 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009513
Douglas Gregor4b52e252009-12-21 23:17:24 +00009514 // Look through all of the overloaded functions, searching for one
9515 // whose type matches exactly.
9516 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009517 for (UnresolvedSetIterator I = ovl->decls_begin(),
9518 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009519 // C++0x [temp.arg.explicit]p3:
9520 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009521 // where deduction is not done, if a template argument list is
9522 // specified and it, along with any default template arguments,
9523 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009524 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009525 FunctionTemplateDecl *FunctionTemplate
9526 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009527
Douglas Gregor4b52e252009-12-21 23:17:24 +00009528 // C++ [over.over]p2:
9529 // If the name is a function template, template argument deduction is
9530 // done (14.8.2.2), and if the argument deduction succeeds, the
9531 // resulting template argument list is used to generate a single
9532 // function template specialization, which is added to the set of
9533 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009534 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009535 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009536 if (TemplateDeductionResult Result
9537 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
Douglas Gregor092140a2013-04-17 08:45:07 +00009538 Specialization, Info,
9539 /*InOverloadResolution=*/true)) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009540 // FIXME: make a note of the failed deduction for diagnostics.
9541 (void)Result;
9542 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009543 }
9544
John McCall864c0412011-04-26 20:42:42 +00009545 assert(Specialization && "no specialization and no error?");
9546
Douglas Gregor4b52e252009-12-21 23:17:24 +00009547 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009548 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009549 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009550 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9551 << ovl->getName();
9552 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009553 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009554 return 0;
John McCall864c0412011-04-26 20:42:42 +00009555 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009556
John McCall864c0412011-04-26 20:42:42 +00009557 Matched = Specialization;
9558 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009559 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009560
Richard Smith60e141e2013-05-04 07:00:32 +00009561 if (Matched && getLangOpts().CPlusPlus1y &&
9562 Matched->getResultType()->isUndeducedType() &&
9563 DeduceReturnType(Matched, ovl->getExprLoc(), Complain))
9564 return 0;
9565
Douglas Gregor4b52e252009-12-21 23:17:24 +00009566 return Matched;
9567}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009568
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009569
9570
9571
John McCall6dbba4f2011-10-11 23:14:30 +00009572// Resolve and fix an overloaded expression that can be resolved
9573// because it identifies a single function template specialization.
9574//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009575// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009576//
9577// Return true if it was logically possible to so resolve the
9578// expression, regardless of whether or not it succeeded. Always
9579// returns true if 'complain' is set.
9580bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9581 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9582 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009583 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009584 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009585 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009586
John McCall6dbba4f2011-10-11 23:14:30 +00009587 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009588
John McCall864c0412011-04-26 20:42:42 +00009589 DeclAccessPair found;
9590 ExprResult SingleFunctionExpression;
9591 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9592 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009593 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009594 SrcExpr = ExprError();
9595 return true;
9596 }
John McCall864c0412011-04-26 20:42:42 +00009597
9598 // It is only correct to resolve to an instance method if we're
9599 // resolving a form that's permitted to be a pointer to member.
9600 // Otherwise we'll end up making a bound member expression, which
9601 // is illegal in all the contexts we resolve like this.
9602 if (!ovl.HasFormOfMemberPointer &&
9603 isa<CXXMethodDecl>(fn) &&
9604 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009605 if (!complain) return false;
9606
9607 Diag(ovl.Expression->getExprLoc(),
9608 diag::err_bound_member_function)
9609 << 0 << ovl.Expression->getSourceRange();
9610
9611 // TODO: I believe we only end up here if there's a mix of
9612 // static and non-static candidates (otherwise the expression
9613 // would have 'bound member' type, not 'overload' type).
9614 // Ideally we would note which candidate was chosen and why
9615 // the static candidates were rejected.
9616 SrcExpr = ExprError();
9617 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009618 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009619
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009620 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009621 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009622 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009623
9624 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009625 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009626 SingleFunctionExpression =
9627 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009628 if (SingleFunctionExpression.isInvalid()) {
9629 SrcExpr = ExprError();
9630 return true;
9631 }
9632 }
John McCall864c0412011-04-26 20:42:42 +00009633 }
9634
9635 if (!SingleFunctionExpression.isUsable()) {
9636 if (complain) {
9637 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9638 << ovl.Expression->getName()
9639 << DestTypeForComplaining
9640 << OpRangeForComplaining
9641 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009642 NoteAllOverloadCandidates(SrcExpr.get());
9643
9644 SrcExpr = ExprError();
9645 return true;
9646 }
9647
9648 return false;
John McCall864c0412011-04-26 20:42:42 +00009649 }
9650
John McCall6dbba4f2011-10-11 23:14:30 +00009651 SrcExpr = SingleFunctionExpression;
9652 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009653}
9654
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009655/// \brief Add a single candidate to the overload set.
9656static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009657 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009658 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009659 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009660 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009661 bool PartialOverloading,
9662 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009663 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009664 if (isa<UsingShadowDecl>(Callee))
9665 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9666
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009667 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009668 if (ExplicitTemplateArgs) {
9669 assert(!KnownValid && "Explicit template arguments?");
9670 return;
9671 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009672 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9673 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009674 return;
John McCallba135432009-11-21 08:51:07 +00009675 }
9676
9677 if (FunctionTemplateDecl *FuncTemplate
9678 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009679 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009680 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009681 return;
9682 }
9683
Richard Smith2ced0442011-06-26 22:19:54 +00009684 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009685}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009686
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009687/// \brief Add the overload candidates named by callee and/or found by argument
9688/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009689void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009690 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009691 OverloadCandidateSet &CandidateSet,
9692 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009693
9694#ifndef NDEBUG
9695 // Verify that ArgumentDependentLookup is consistent with the rules
9696 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009697 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009698 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9699 // and let Y be the lookup set produced by argument dependent
9700 // lookup (defined as follows). If X contains
9701 //
9702 // -- a declaration of a class member, or
9703 //
9704 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009705 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009706 //
9707 // -- a declaration that is neither a function or a function
9708 // template
9709 //
9710 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009711
John McCall3b4294e2009-12-16 12:17:52 +00009712 if (ULE->requiresADL()) {
9713 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9714 E = ULE->decls_end(); I != E; ++I) {
9715 assert(!(*I)->getDeclContext()->isRecord());
9716 assert(isa<UsingShadowDecl>(*I) ||
9717 !(*I)->getDeclContext()->isFunctionOrMethod());
9718 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009719 }
9720 }
9721#endif
9722
John McCall3b4294e2009-12-16 12:17:52 +00009723 // It would be nice to avoid this copy.
9724 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009725 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009726 if (ULE->hasExplicitTemplateArgs()) {
9727 ULE->copyTemplateArgumentsInto(TABuffer);
9728 ExplicitTemplateArgs = &TABuffer;
9729 }
9730
9731 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9732 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009733 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9734 CandidateSet, PartialOverloading,
9735 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009736
John McCall3b4294e2009-12-16 12:17:52 +00009737 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009738 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009739 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009740 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009741 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009742}
John McCall578b69b2009-12-16 08:11:27 +00009743
Richard Smithd3ff3252013-06-12 22:56:54 +00009744/// Determine whether a declaration with the specified name could be moved into
9745/// a different namespace.
9746static bool canBeDeclaredInNamespace(const DeclarationName &Name) {
9747 switch (Name.getCXXOverloadedOperator()) {
9748 case OO_New: case OO_Array_New:
9749 case OO_Delete: case OO_Array_Delete:
9750 return false;
9751
9752 default:
9753 return true;
9754 }
9755}
9756
Richard Smithf50e88a2011-06-05 22:42:48 +00009757/// Attempt to recover from an ill-formed use of a non-dependent name in a
9758/// template, where the non-dependent name was declared after the template
9759/// was defined. This is common in code written for a compilers which do not
9760/// correctly implement two-stage name lookup.
9761///
9762/// Returns true if a viable candidate was found and a diagnostic was issued.
9763static bool
9764DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9765 const CXXScopeSpec &SS, LookupResult &R,
9766 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009767 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009768 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9769 return false;
9770
9771 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009772 if (DC->isTransparentContext())
9773 continue;
9774
Richard Smithf50e88a2011-06-05 22:42:48 +00009775 SemaRef.LookupQualifiedName(R, DC);
9776
9777 if (!R.empty()) {
9778 R.suppressDiagnostics();
9779
9780 if (isa<CXXRecordDecl>(DC)) {
9781 // Don't diagnose names we find in classes; we get much better
9782 // diagnostics for these from DiagnoseEmptyLookup.
9783 R.clear();
9784 return false;
9785 }
9786
9787 OverloadCandidateSet Candidates(FnLoc);
9788 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9789 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009790 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009791 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009792
9793 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009794 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009795 // No viable functions. Don't bother the user with notes for functions
9796 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009797 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009798 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009799 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009800
9801 // Find the namespaces where ADL would have looked, and suggest
9802 // declaring the function there instead.
9803 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9804 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009805 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009806 AssociatedNamespaces,
9807 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009808 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithd3ff3252013-06-12 22:56:54 +00009809 if (canBeDeclaredInNamespace(R.getLookupName())) {
9810 DeclContext *Std = SemaRef.getStdNamespace();
9811 for (Sema::AssociatedNamespaceSet::iterator
9812 it = AssociatedNamespaces.begin(),
9813 end = AssociatedNamespaces.end(); it != end; ++it) {
9814 // Never suggest declaring a function within namespace 'std'.
9815 if (Std && Std->Encloses(*it))
9816 continue;
Richard Smith19e0d952012-12-22 02:46:14 +00009817
Richard Smithd3ff3252013-06-12 22:56:54 +00009818 // Never suggest declaring a function within a namespace with a
9819 // reserved name, like __gnu_cxx.
9820 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9821 if (NS &&
9822 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9823 continue;
9824
9825 SuggestedNamespaces.insert(*it);
9826 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009827 }
9828
9829 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9830 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009831 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009832 SemaRef.Diag(Best->Function->getLocation(),
9833 diag::note_not_found_by_two_phase_lookup)
9834 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009835 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009836 SemaRef.Diag(Best->Function->getLocation(),
9837 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009838 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009839 } else {
9840 // FIXME: It would be useful to list the associated namespaces here,
9841 // but the diagnostics infrastructure doesn't provide a way to produce
9842 // a localized representation of a list of items.
9843 SemaRef.Diag(Best->Function->getLocation(),
9844 diag::note_not_found_by_two_phase_lookup)
9845 << R.getLookupName() << 2;
9846 }
9847
9848 // Try to recover by calling this function.
9849 return true;
9850 }
9851
9852 R.clear();
9853 }
9854
9855 return false;
9856}
9857
9858/// Attempt to recover from ill-formed use of a non-dependent operator in a
9859/// template, where the non-dependent operator was declared after the template
9860/// was defined.
9861///
9862/// Returns true if a viable candidate was found and a diagnostic was issued.
9863static bool
9864DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9865 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009866 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009867 DeclarationName OpName =
9868 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9869 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9870 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009871 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009872}
9873
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009874namespace {
9875// Callback to limit the allowed keywords and to only accept typo corrections
9876// that are keywords or whose decls refer to functions (or template functions)
9877// that accept the given number of arguments.
9878class RecoveryCallCCC : public CorrectionCandidateCallback {
9879 public:
9880 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9881 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009882 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009883 WantRemainingKeywords = false;
9884 }
9885
9886 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9887 if (!candidate.getCorrectionDecl())
9888 return candidate.isKeyword();
9889
9890 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9891 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9892 FunctionDecl *FD = 0;
9893 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9894 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9895 FD = FTD->getTemplatedDecl();
9896 if (!HasExplicitTemplateArgs && !FD) {
9897 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9898 // If the Decl is neither a function nor a template function,
9899 // determine if it is a pointer or reference to a function. If so,
9900 // check against the number of arguments expected for the pointee.
9901 QualType ValType = cast<ValueDecl>(ND)->getType();
9902 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9903 ValType = ValType->getPointeeType();
9904 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9905 if (FPT->getNumArgs() == NumArgs)
9906 return true;
9907 }
9908 }
9909 if (FD && FD->getNumParams() >= NumArgs &&
9910 FD->getMinRequiredArguments() <= NumArgs)
9911 return true;
9912 }
9913 return false;
9914 }
9915
9916 private:
9917 unsigned NumArgs;
9918 bool HasExplicitTemplateArgs;
9919};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009920
9921// Callback that effectively disabled typo correction
9922class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9923 public:
9924 NoTypoCorrectionCCC() {
9925 WantTypeSpecifiers = false;
9926 WantExpressionKeywords = false;
9927 WantCXXNamedCasts = false;
9928 WantRemainingKeywords = false;
9929 }
9930
9931 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9932 return false;
9933 }
9934};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009935
9936class BuildRecoveryCallExprRAII {
9937 Sema &SemaRef;
9938public:
9939 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9940 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9941 SemaRef.IsBuildingRecoveryCallExpr = true;
9942 }
9943
9944 ~BuildRecoveryCallExprRAII() {
9945 SemaRef.IsBuildingRecoveryCallExpr = false;
9946 }
9947};
9948
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009949}
9950
John McCall578b69b2009-12-16 08:11:27 +00009951/// Attempts to recover from a call where no functions were found.
9952///
9953/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009954static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009955BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009956 UnresolvedLookupExpr *ULE,
9957 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009958 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009959 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009960 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009961 // Do not try to recover if it is already building a recovery call.
9962 // This stops infinite loops for template instantiations like
9963 //
9964 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9965 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9966 //
9967 if (SemaRef.IsBuildingRecoveryCallExpr)
9968 return ExprError();
9969 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009970
9971 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009972 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009973 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009974
John McCall3b4294e2009-12-16 12:17:52 +00009975 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009976 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009977 if (ULE->hasExplicitTemplateArgs()) {
9978 ULE->copyTemplateArgumentsInto(TABuffer);
9979 ExplicitTemplateArgs = &TABuffer;
9980 }
9981
John McCall578b69b2009-12-16 08:11:27 +00009982 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9983 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009984 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009985 NoTypoCorrectionCCC RejectAll;
9986 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9987 (CorrectionCandidateCallback*)&Validator :
9988 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009989 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009990 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009991 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009992 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009993 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009994 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009995
John McCall3b4294e2009-12-16 12:17:52 +00009996 assert(!R.empty() && "lookup results empty despite recovery");
9997
9998 // Build an implicit member call if appropriate. Just drop the
9999 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +000010000 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010001 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010002 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
10003 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010004 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +000010005 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +000010006 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +000010007 else
10008 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
10009
10010 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +000010011 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +000010012
10013 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +000010014 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +000010015 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +000010016 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010017 MultiExprArg(Args.data(), Args.size()),
10018 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +000010019}
Douglas Gregord7a95972010-06-08 17:35:15 +000010020
Sam Panzere1715b62012-08-21 00:52:01 +000010021/// \brief Constructs and populates an OverloadedCandidateSet from
10022/// the given function.
10023/// \returns true when an the ExprResult output parameter has been set.
10024bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
10025 UnresolvedLookupExpr *ULE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010026 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010027 SourceLocation RParenLoc,
10028 OverloadCandidateSet *CandidateSet,
10029 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +000010030#ifndef NDEBUG
10031 if (ULE->requiresADL()) {
10032 // To do ADL, we must have found an unqualified name.
10033 assert(!ULE->getQualifier() && "qualified name with ADL");
10034
10035 // We don't perform ADL for implicit declarations of builtins.
10036 // Verify that this was correctly set up.
10037 FunctionDecl *F;
10038 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
10039 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
10040 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +000010041 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010042
John McCall3b4294e2009-12-16 12:17:52 +000010043 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +000010044 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +000010045 }
John McCall3b4294e2009-12-16 12:17:52 +000010046#endif
10047
John McCall5acb0c92011-10-17 18:40:02 +000010048 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010049 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts)) {
Sam Panzere1715b62012-08-21 00:52:01 +000010050 *Result = ExprError();
10051 return true;
10052 }
Douglas Gregor17330012009-02-04 15:01:18 +000010053
John McCall3b4294e2009-12-16 12:17:52 +000010054 // Add the functions denoted by the callee to the set of candidate
10055 // functions, including those from argument-dependent lookup.
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010056 AddOverloadedCallCandidates(ULE, Args, *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +000010057
10058 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +000010059 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
10060 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +000010061 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +000010062 // In Microsoft mode, if we are inside a template class member function then
10063 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010064 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +000010065 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +000010066 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +000010067 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010068 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010069 Context.DependentTy, VK_RValue,
10070 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +000010071 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +000010072 *Result = Owned(CE);
10073 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +000010074 }
Sam Panzere1715b62012-08-21 00:52:01 +000010075 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +000010076 }
John McCall578b69b2009-12-16 08:11:27 +000010077
John McCall5acb0c92011-10-17 18:40:02 +000010078 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +000010079 return false;
10080}
John McCall5acb0c92011-10-17 18:40:02 +000010081
Sam Panzere1715b62012-08-21 00:52:01 +000010082/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
10083/// the completed call expression. If overload resolution fails, emits
10084/// diagnostics and returns ExprError()
10085static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
10086 UnresolvedLookupExpr *ULE,
10087 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010088 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010089 SourceLocation RParenLoc,
10090 Expr *ExecConfig,
10091 OverloadCandidateSet *CandidateSet,
10092 OverloadCandidateSet::iterator *Best,
10093 OverloadingResult OverloadResult,
10094 bool AllowTypoCorrection) {
10095 if (CandidateSet->empty())
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010096 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010097 RParenLoc, /*EmptyLookup=*/true,
10098 AllowTypoCorrection);
10099
10100 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +000010101 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +000010102 FunctionDecl *FDecl = (*Best)->Function;
Sam Panzere1715b62012-08-21 00:52:01 +000010103 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010104 if (SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc()))
10105 return ExprError();
Sam Panzere1715b62012-08-21 00:52:01 +000010106 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010107 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10108 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +000010109 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010110
Richard Smithf50e88a2011-06-05 22:42:48 +000010111 case OR_No_Viable_Function: {
10112 // Try to recover by looking for viable functions which the user might
10113 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +000010114 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010115 Args, RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +000010116 /*EmptyLookup=*/false,
10117 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +000010118 if (!Recovery.isInvalid())
10119 return Recovery;
10120
Sam Panzere1715b62012-08-21 00:52:01 +000010121 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +000010122 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +000010123 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010124 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010125 break;
Richard Smithf50e88a2011-06-05 22:42:48 +000010126 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010127
10128 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +000010129 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +000010130 << ULE->getName() << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010131 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates, Args);
Douglas Gregorf6b89692008-11-26 05:54:23 +000010132 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010133
Sam Panzere1715b62012-08-21 00:52:01 +000010134 case OR_Deleted: {
10135 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
10136 << (*Best)->Function->isDeleted()
10137 << ULE->getName()
10138 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
10139 << Fn->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010140 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates, Args);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +000010141
Sam Panzere1715b62012-08-21 00:52:01 +000010142 // We emitted an error for the unvailable/deleted function call but keep
10143 // the call in the AST.
10144 FunctionDecl *FDecl = (*Best)->Function;
10145 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010146 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, RParenLoc,
10147 ExecConfig);
Sam Panzere1715b62012-08-21 00:52:01 +000010148 }
Douglas Gregorf6b89692008-11-26 05:54:23 +000010149 }
10150
Douglas Gregorff331c12010-07-25 18:17:45 +000010151 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +000010152 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +000010153}
10154
Sam Panzere1715b62012-08-21 00:52:01 +000010155/// BuildOverloadedCallExpr - Given the call expression that calls Fn
10156/// (which eventually refers to the declaration Func) and the call
10157/// arguments Args/NumArgs, attempt to resolve the function call down
10158/// to a specific function. If overload resolution succeeds, returns
10159/// the call expression produced by overload resolution.
10160/// Otherwise, emits diagnostics and returns ExprError.
10161ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
10162 UnresolvedLookupExpr *ULE,
10163 SourceLocation LParenLoc,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010164 MultiExprArg Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010165 SourceLocation RParenLoc,
10166 Expr *ExecConfig,
10167 bool AllowTypoCorrection) {
10168 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
10169 ExprResult result;
10170
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010171 if (buildOverloadedCallSet(S, Fn, ULE, Args, LParenLoc, &CandidateSet,
10172 &result))
Sam Panzere1715b62012-08-21 00:52:01 +000010173 return result;
10174
10175 OverloadCandidateSet::iterator Best;
10176 OverloadingResult OverloadResult =
10177 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
10178
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010179 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args,
Sam Panzere1715b62012-08-21 00:52:01 +000010180 RParenLoc, ExecConfig, &CandidateSet,
10181 &Best, OverloadResult,
10182 AllowTypoCorrection);
10183}
10184
John McCall6e266892010-01-26 03:27:55 +000010185static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +000010186 return Functions.size() > 1 ||
10187 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
10188}
10189
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010190/// \brief Create a unary operation that may resolve to an overloaded
10191/// operator.
10192///
10193/// \param OpLoc The location of the operator itself (e.g., '*').
10194///
10195/// \param OpcIn The UnaryOperator::Opcode that describes this
10196/// operator.
10197///
James Dennett40ae6662012-06-22 08:52:37 +000010198/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010199/// considered by overload resolution. The caller needs to build this
10200/// set based on the context using, e.g.,
10201/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10202/// set should not contain any member functions; those will be added
10203/// by CreateOverloadedUnaryOp().
10204///
James Dennett8da16872012-06-22 10:32:46 +000010205/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010206ExprResult
John McCall6e266892010-01-26 03:27:55 +000010207Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10208 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010209 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010210 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010211
10212 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10213 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10214 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010215 // TODO: provide better source location info.
10216 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010217
John McCall5acb0c92011-10-17 18:40:02 +000010218 if (checkPlaceholderForOverload(*this, Input))
10219 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010220
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010221 Expr *Args[2] = { Input, 0 };
10222 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010223
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010224 // For post-increment and post-decrement, add the implicit '0' as
10225 // the second argument, so that we know this is a post-increment or
10226 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010227 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010228 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010229 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10230 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010231 NumArgs = 2;
10232 }
10233
Richard Smith958ba642013-05-05 15:51:06 +000010234 ArrayRef<Expr *> ArgsArray(Args, NumArgs);
10235
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010236 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010237 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010238 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010239 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010240 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010241 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010242 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010243
John McCallc373d482010-01-27 01:50:18 +000010244 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010245 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010246 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010247 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010248 /*ADL*/ true, IsOverloaded(Fns),
10249 Fns.begin(), Fns.end());
Richard Smith958ba642013-05-05 15:51:06 +000010250 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, ArgsArray,
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010251 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010252 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010253 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010254 }
10255
10256 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010257 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010258
10259 // Add the candidates from the given function set.
Richard Smith958ba642013-05-05 15:51:06 +000010260 AddFunctionCandidates(Fns, ArgsArray, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010261
10262 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010263 AddMemberOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010264
John McCall6e266892010-01-26 03:27:55 +000010265 // Add candidates from ADL.
Richard Smith958ba642013-05-05 15:51:06 +000010266 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true, OpLoc,
10267 ArgsArray, /*ExplicitTemplateArgs*/ 0,
John McCall6e266892010-01-26 03:27:55 +000010268 CandidateSet);
10269
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010270 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010271 AddBuiltinOperatorCandidates(Op, OpLoc, ArgsArray, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010272
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010273 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10274
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010275 // Perform overload resolution.
10276 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010277 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010278 case OR_Success: {
10279 // We found a built-in operator or an overloaded operator.
10280 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010281
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010282 if (FnDecl) {
10283 // We matched an overloaded operator. Build a call to that
10284 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010285
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010286 // Convert the arguments.
10287 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010288 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010289
John Wiegley429bb272011-04-08 18:41:53 +000010290 ExprResult InputRes =
10291 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10292 Best->FoundDecl, Method);
10293 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010294 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010295 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010296 } else {
10297 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010298 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010299 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010300 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010301 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010302 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010303 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010304 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010305 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010306 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010307 }
10308
John McCallf89e55a2010-11-18 06:31:45 +000010309 // Determine the result type.
10310 QualType ResultTy = FnDecl->getResultType();
10311 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10312 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010313
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010314 // Build the actual expression node.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010315 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010316 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010317 if (FnExpr.isInvalid())
10318 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010319
Eli Friedman4c3b8962009-11-18 03:58:17 +000010320 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010321 CallExpr *TheCall =
Richard Smith958ba642013-05-05 15:51:06 +000010322 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(), ArgsArray,
Lang Hamesbe9af122012-10-02 04:45:10 +000010323 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010324
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010325 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010326 FnDecl))
10327 return ExprError();
10328
John McCall9ae2f072010-08-23 23:25:46 +000010329 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010330 } else {
10331 // We matched a built-in operator. Convert the arguments, then
10332 // break out so that we will build the appropriate built-in
10333 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010334 ExprResult InputRes =
10335 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10336 Best->Conversions[0], AA_Passing);
10337 if (InputRes.isInvalid())
10338 return ExprError();
10339 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010340 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010341 }
John Wiegley429bb272011-04-08 18:41:53 +000010342 }
10343
10344 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010345 // This is an erroneous use of an operator which can be overloaded by
10346 // a non-member function. Check for non-member operators which were
10347 // defined too late to be candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010348 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, ArgsArray))
Richard Smithf50e88a2011-06-05 22:42:48 +000010349 // FIXME: Recover by calling the found function.
10350 return ExprError();
10351
John Wiegley429bb272011-04-08 18:41:53 +000010352 // No viable function; fall through to handling this as a
10353 // built-in operator, which will produce an error message for us.
10354 break;
10355
10356 case OR_Ambiguous:
10357 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10358 << UnaryOperator::getOpcodeStr(Opc)
10359 << Input->getType()
10360 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010361 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, ArgsArray,
John Wiegley429bb272011-04-08 18:41:53 +000010362 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10363 return ExprError();
10364
10365 case OR_Deleted:
10366 Diag(OpLoc, diag::err_ovl_deleted_oper)
10367 << Best->Function->isDeleted()
10368 << UnaryOperator::getOpcodeStr(Opc)
10369 << getDeletedOrUnavailableSuffix(Best->Function)
10370 << Input->getSourceRange();
Richard Smith958ba642013-05-05 15:51:06 +000010371 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, ArgsArray,
Eli Friedman1795d372011-08-26 19:46:22 +000010372 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010373 return ExprError();
10374 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010375
10376 // Either we found no viable overloaded operator or we matched a
10377 // built-in operator. In either case, fall through to trying to
10378 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010379 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010380}
10381
Douglas Gregor063daf62009-03-13 18:40:31 +000010382/// \brief Create a binary operation that may resolve to an overloaded
10383/// operator.
10384///
10385/// \param OpLoc The location of the operator itself (e.g., '+').
10386///
10387/// \param OpcIn The BinaryOperator::Opcode that describes this
10388/// operator.
10389///
James Dennett40ae6662012-06-22 08:52:37 +000010390/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010391/// considered by overload resolution. The caller needs to build this
10392/// set based on the context using, e.g.,
10393/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10394/// set should not contain any member functions; those will be added
10395/// by CreateOverloadedBinOp().
10396///
10397/// \param LHS Left-hand argument.
10398/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010399ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010400Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010401 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010402 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010403 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010404 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010405 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010406
10407 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10408 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10409 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10410
10411 // If either side is type-dependent, create an appropriate dependent
10412 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010413 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010414 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010415 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010416 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010417 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010418 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010419 Context.DependentTy,
10420 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010421 OpLoc,
10422 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010423
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010424 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10425 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010426 VK_LValue,
10427 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010428 Context.DependentTy,
10429 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010430 OpLoc,
10431 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010432 }
John McCall6e266892010-01-26 03:27:55 +000010433
10434 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010435 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010436 // TODO: provide better source location info in DNLoc component.
10437 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010438 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010439 = UnresolvedLookupExpr::Create(Context, NamingClass,
10440 NestedNameSpecifierLoc(), OpNameInfo,
10441 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010442 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010443 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10444 Context.DependentTy, VK_RValue,
10445 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010446 }
10447
John McCall5acb0c92011-10-17 18:40:02 +000010448 // Always do placeholder-like conversions on the RHS.
10449 if (checkPlaceholderForOverload(*this, Args[1]))
10450 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010451
John McCall3c3b7f92011-10-25 17:37:35 +000010452 // Do placeholder-like conversion on the LHS; note that we should
10453 // not get here with a PseudoObject LHS.
10454 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010455 if (checkPlaceholderForOverload(*this, Args[0]))
10456 return ExprError();
10457
Sebastian Redl275c2b42009-11-18 23:10:33 +000010458 // If this is the assignment operator, we only perform overload resolution
10459 // if the left-hand side is a class or enumeration type. This is actually
10460 // a hack. The standard requires that we do overload resolution between the
10461 // various built-in candidates, but as DR507 points out, this can lead to
10462 // problems. So we do it this way, which pretty much follows what GCC does.
10463 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010464 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010465 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010466
John McCall0e800c92010-12-04 08:14:53 +000010467 // If this is the .* operator, which is not overloadable, just
10468 // create a built-in binary operator.
10469 if (Opc == BO_PtrMemD)
10470 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10471
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010472 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010473 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010474
10475 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010476 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010477
10478 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010479 AddMemberOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010480
John McCall6e266892010-01-26 03:27:55 +000010481 // Add candidates from ADL.
10482 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010483 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010484 /*ExplicitTemplateArgs*/ 0,
10485 CandidateSet);
10486
Douglas Gregor063daf62009-03-13 18:40:31 +000010487 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010488 AddBuiltinOperatorCandidates(Op, OpLoc, Args, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010489
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010490 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10491
Douglas Gregor063daf62009-03-13 18:40:31 +000010492 // Perform overload resolution.
10493 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010494 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010495 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010496 // We found a built-in operator or an overloaded operator.
10497 FunctionDecl *FnDecl = Best->Function;
10498
10499 if (FnDecl) {
10500 // We matched an overloaded operator. Build a call to that
10501 // operator.
10502
10503 // Convert the arguments.
10504 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010505 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010506 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010507
Chandler Carruth6df868e2010-12-12 08:17:55 +000010508 ExprResult Arg1 =
10509 PerformCopyInitialization(
10510 InitializedEntity::InitializeParameter(Context,
10511 FnDecl->getParamDecl(0)),
10512 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010513 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010514 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010515
John Wiegley429bb272011-04-08 18:41:53 +000010516 ExprResult Arg0 =
10517 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10518 Best->FoundDecl, Method);
10519 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010520 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010521 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010522 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010523 } else {
10524 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010525 ExprResult Arg0 = PerformCopyInitialization(
10526 InitializedEntity::InitializeParameter(Context,
10527 FnDecl->getParamDecl(0)),
10528 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010529 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010530 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010531
Chandler Carruth6df868e2010-12-12 08:17:55 +000010532 ExprResult Arg1 =
10533 PerformCopyInitialization(
10534 InitializedEntity::InitializeParameter(Context,
10535 FnDecl->getParamDecl(1)),
10536 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010537 if (Arg1.isInvalid())
10538 return ExprError();
10539 Args[0] = LHS = Arg0.takeAs<Expr>();
10540 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010541 }
10542
John McCallf89e55a2010-11-18 06:31:45 +000010543 // Determine the result type.
10544 QualType ResultTy = FnDecl->getResultType();
10545 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10546 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010547
10548 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010549 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010550 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010551 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010552 if (FnExpr.isInvalid())
10553 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010554
John McCall9ae2f072010-08-23 23:25:46 +000010555 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010556 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010557 Args, ResultTy, VK, OpLoc,
10558 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010559
10560 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010561 FnDecl))
10562 return ExprError();
10563
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010564 ArrayRef<const Expr *> ArgsArray(Args, 2);
10565 // Cut off the implicit 'this'.
10566 if (isa<CXXMethodDecl>(FnDecl))
10567 ArgsArray = ArgsArray.slice(1);
10568 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10569 TheCall->getSourceRange(), VariadicDoesNotApply);
10570
John McCall9ae2f072010-08-23 23:25:46 +000010571 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010572 } else {
10573 // We matched a built-in operator. Convert the arguments, then
10574 // break out so that we will build the appropriate built-in
10575 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010576 ExprResult ArgsRes0 =
10577 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10578 Best->Conversions[0], AA_Passing);
10579 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010580 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010581 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010582
John Wiegley429bb272011-04-08 18:41:53 +000010583 ExprResult ArgsRes1 =
10584 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10585 Best->Conversions[1], AA_Passing);
10586 if (ArgsRes1.isInvalid())
10587 return ExprError();
10588 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010589 break;
10590 }
10591 }
10592
Douglas Gregor33074752009-09-30 21:46:01 +000010593 case OR_No_Viable_Function: {
10594 // C++ [over.match.oper]p9:
10595 // If the operator is the operator , [...] and there are no
10596 // viable functions, then the operator is assumed to be the
10597 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010598 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010599 break;
10600
Chandler Carruth6df868e2010-12-12 08:17:55 +000010601 // For class as left operand for assignment or compound assigment
10602 // operator do not fall through to handling in built-in, but report that
10603 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010604 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010605 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010606 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010607 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10608 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010609 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010610 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010611 // This is an erroneous use of an operator which can be overloaded by
10612 // a non-member function. Check for non-member operators which were
10613 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010614 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010615 // FIXME: Recover by calling the found function.
10616 return ExprError();
10617
Douglas Gregor33074752009-09-30 21:46:01 +000010618 // No viable function; try to create a built-in operation, which will
10619 // produce an error. Then, show the non-viable candidates.
10620 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010621 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010622 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010623 "C++ binary operator overloading is missing candidates!");
10624 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010625 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010626 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010627 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010628 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010629
10630 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010631 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010632 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010633 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010634 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010635 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010636 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010637 return ExprError();
10638
10639 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010640 if (isImplicitlyDeleted(Best->Function)) {
10641 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10642 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010643 << Context.getRecordType(Method->getParent())
10644 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010645
Richard Smith0f46e642012-12-28 12:23:24 +000010646 // The user probably meant to call this special member. Just
10647 // explain why it's deleted.
10648 NoteDeletedFunction(Method);
10649 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010650 } else {
10651 Diag(OpLoc, diag::err_ovl_deleted_oper)
10652 << Best->Function->isDeleted()
10653 << BinaryOperator::getOpcodeStr(Opc)
10654 << getDeletedOrUnavailableSuffix(Best->Function)
10655 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10656 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010657 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010658 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010659 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010660 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010661
Douglas Gregor33074752009-09-30 21:46:01 +000010662 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010663 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010664}
10665
John McCall60d7b3a2010-08-24 06:29:42 +000010666ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010667Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10668 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010669 Expr *Base, Expr *Idx) {
10670 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010671 DeclarationName OpName =
10672 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10673
10674 // If either side is type-dependent, create an appropriate dependent
10675 // expression.
10676 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10677
John McCallc373d482010-01-27 01:50:18 +000010678 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010679 // CHECKME: no 'operator' keyword?
10680 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10681 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010682 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010683 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010684 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010685 /*ADL*/ true, /*Overloaded*/ false,
10686 UnresolvedSetIterator(),
10687 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010688 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010689
Sebastian Redlf322ed62009-10-29 20:17:01 +000010690 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010691 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010692 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010693 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010694 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010695 }
10696
John McCall5acb0c92011-10-17 18:40:02 +000010697 // Handle placeholders on both operands.
10698 if (checkPlaceholderForOverload(*this, Args[0]))
10699 return ExprError();
10700 if (checkPlaceholderForOverload(*this, Args[1]))
10701 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010702
Sebastian Redlf322ed62009-10-29 20:17:01 +000010703 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010704 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010705
10706 // Subscript can only be overloaded as a member function.
10707
10708 // Add operator candidates that are member functions.
Richard Smith958ba642013-05-05 15:51:06 +000010709 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010710
10711 // Add builtin operator candidates.
Richard Smith958ba642013-05-05 15:51:06 +000010712 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, CandidateSet);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010713
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010714 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10715
Sebastian Redlf322ed62009-10-29 20:17:01 +000010716 // Perform overload resolution.
10717 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010718 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010719 case OR_Success: {
10720 // We found a built-in operator or an overloaded operator.
10721 FunctionDecl *FnDecl = Best->Function;
10722
10723 if (FnDecl) {
10724 // We matched an overloaded operator. Build a call to that
10725 // operator.
10726
John McCall9aa472c2010-03-19 07:35:19 +000010727 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallc373d482010-01-27 01:50:18 +000010728
Sebastian Redlf322ed62009-10-29 20:17:01 +000010729 // Convert the arguments.
10730 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010731 ExprResult Arg0 =
10732 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10733 Best->FoundDecl, Method);
10734 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010735 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010736 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010737
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010738 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010739 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010740 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010741 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010742 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010743 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010744 Owned(Args[1]));
10745 if (InputInit.isInvalid())
10746 return ExprError();
10747
10748 Args[1] = InputInit.takeAs<Expr>();
10749
Sebastian Redlf322ed62009-10-29 20:17:01 +000010750 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010751 QualType ResultTy = FnDecl->getResultType();
10752 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10753 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010754
10755 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010756 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10757 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010758 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000010759 Best->FoundDecl,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010760 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010761 OpLocInfo.getLoc(),
10762 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010763 if (FnExpr.isInvalid())
10764 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010765
John McCall9ae2f072010-08-23 23:25:46 +000010766 CXXOperatorCallExpr *TheCall =
10767 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010768 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010769 ResultTy, VK, RLoc,
10770 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010771
John McCall9ae2f072010-08-23 23:25:46 +000010772 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010773 FnDecl))
10774 return ExprError();
10775
John McCall9ae2f072010-08-23 23:25:46 +000010776 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010777 } else {
10778 // We matched a built-in operator. Convert the arguments, then
10779 // break out so that we will build the appropriate built-in
10780 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010781 ExprResult ArgsRes0 =
10782 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10783 Best->Conversions[0], AA_Passing);
10784 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010785 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010786 Args[0] = ArgsRes0.take();
10787
10788 ExprResult ArgsRes1 =
10789 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10790 Best->Conversions[1], AA_Passing);
10791 if (ArgsRes1.isInvalid())
10792 return ExprError();
10793 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010794
10795 break;
10796 }
10797 }
10798
10799 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010800 if (CandidateSet.empty())
10801 Diag(LLoc, diag::err_ovl_no_oper)
10802 << Args[0]->getType() << /*subscript*/ 0
10803 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10804 else
10805 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10806 << Args[0]->getType()
10807 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010808 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010809 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010810 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010811 }
10812
10813 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010814 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010815 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010816 << Args[0]->getType() << Args[1]->getType()
10817 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010818 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010819 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010820 return ExprError();
10821
10822 case OR_Deleted:
10823 Diag(LLoc, diag::err_ovl_deleted_oper)
10824 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010825 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010826 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010827 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010828 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010829 return ExprError();
10830 }
10831
10832 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010833 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010834}
10835
Douglas Gregor88a35142008-12-22 05:46:06 +000010836/// BuildCallToMemberFunction - Build a call to a member
10837/// function. MemExpr is the expression that refers to the member
10838/// function (and includes the object parameter), Args/NumArgs are the
10839/// arguments to the function call (not including the object
10840/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010841/// expression refers to a non-static member function or an overloaded
10842/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010843ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010844Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010845 SourceLocation LParenLoc,
10846 MultiExprArg Args,
10847 SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010848 assert(MemExprE->getType() == Context.BoundMemberTy ||
10849 MemExprE->getType() == Context.OverloadTy);
10850
Douglas Gregor88a35142008-12-22 05:46:06 +000010851 // Dig out the member expression. This holds both the object
10852 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010853 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010854
John McCall864c0412011-04-26 20:42:42 +000010855 // Determine whether this is a call to a pointer-to-member function.
10856 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10857 assert(op->getType() == Context.BoundMemberTy);
10858 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10859
10860 QualType fnType =
10861 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10862
10863 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10864 QualType resultType = proto->getCallResultType(Context);
10865 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10866
10867 // Check that the object type isn't more qualified than the
10868 // member function we're calling.
10869 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10870
10871 QualType objectType = op->getLHS()->getType();
10872 if (op->getOpcode() == BO_PtrMemI)
10873 objectType = objectType->castAs<PointerType>()->getPointeeType();
10874 Qualifiers objectQuals = objectType.getQualifiers();
10875
10876 Qualifiers difference = objectQuals - funcQuals;
10877 difference.removeObjCGCAttr();
10878 difference.removeAddressSpace();
10879 if (difference) {
10880 std::string qualsString = difference.getAsString();
10881 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10882 << fnType.getUnqualifiedType()
10883 << qualsString
10884 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10885 }
10886
10887 CXXMemberCallExpr *call
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010888 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCall864c0412011-04-26 20:42:42 +000010889 resultType, valueKind, RParenLoc);
10890
10891 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010892 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010893 call, 0))
10894 return ExprError();
10895
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010896 if (ConvertArgumentsForCall(call, op, 0, proto, Args, RParenLoc))
John McCall864c0412011-04-26 20:42:42 +000010897 return ExprError();
10898
Richard Trieue2a90b82013-06-22 02:30:38 +000010899 if (CheckOtherCall(call, proto))
10900 return ExprError();
10901
John McCall864c0412011-04-26 20:42:42 +000010902 return MaybeBindToTemporary(call);
10903 }
10904
John McCall5acb0c92011-10-17 18:40:02 +000010905 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010906 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000010907 return ExprError();
10908
John McCall129e2df2009-11-30 22:42:35 +000010909 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010910 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010911 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010912 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010913 if (isa<MemberExpr>(NakedMemExpr)) {
10914 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010915 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010916 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010917 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010918 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010919 } else {
10920 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010921 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010922
John McCall701c89e2009-12-03 04:06:58 +000010923 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010924 Expr::Classification ObjectClassification
10925 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10926 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010927
Douglas Gregor88a35142008-12-22 05:46:06 +000010928 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010929 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010930
John McCallaa81e162009-12-01 22:10:20 +000010931 // FIXME: avoid copy.
10932 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10933 if (UnresExpr->hasExplicitTemplateArgs()) {
10934 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10935 TemplateArgs = &TemplateArgsBuffer;
10936 }
10937
John McCall129e2df2009-11-30 22:42:35 +000010938 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10939 E = UnresExpr->decls_end(); I != E; ++I) {
10940
John McCall701c89e2009-12-03 04:06:58 +000010941 NamedDecl *Func = *I;
10942 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10943 if (isa<UsingShadowDecl>(Func))
10944 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10945
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010946
Francois Pichetdbee3412011-01-18 05:04:39 +000010947 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010948 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010949 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010950 Args, CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010951 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010952 // If explicit template arguments were provided, we can't call a
10953 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010954 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010955 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010956
John McCall9aa472c2010-03-19 07:35:19 +000010957 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010958 ObjectClassification, Args, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010959 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010960 } else {
John McCall129e2df2009-11-30 22:42:35 +000010961 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010962 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010963 ObjectType, ObjectClassification,
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010964 Args, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010965 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010966 }
Douglas Gregordec06662009-08-21 18:42:58 +000010967 }
Mike Stump1eb44332009-09-09 15:08:12 +000010968
John McCall129e2df2009-11-30 22:42:35 +000010969 DeclarationName DeclName = UnresExpr->getMemberName();
10970
John McCall5acb0c92011-10-17 18:40:02 +000010971 UnbridgedCasts.restore();
10972
Douglas Gregor88a35142008-12-22 05:46:06 +000010973 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010974 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010975 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010976 case OR_Success:
10977 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +000010978 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010979 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000010980 if (DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc()))
10981 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000010982 // If FoundDecl is different from Method (such as if one is a template
10983 // and the other a specialization), make sure DiagnoseUseOfDecl is
10984 // called on both.
10985 // FIXME: This would be more comprehensively addressed by modifying
10986 // DiagnoseUseOfDecl to accept both the FoundDecl and the decl
10987 // being used.
10988 if (Method != FoundDecl.getDecl() &&
10989 DiagnoseUseOfDecl(Method, UnresExpr->getNameLoc()))
10990 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010991 break;
10992
10993 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010994 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010995 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010996 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000010997 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000010998 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010999 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011000
11001 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000011002 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000011003 << DeclName << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011004 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor88a35142008-12-22 05:46:06 +000011005 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011006 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011007
11008 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000011009 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011010 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011011 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011012 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011013 << MemExprE->getSourceRange();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011014 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011015 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000011016 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011017 }
11018
John McCall6bb80172010-03-30 21:47:33 +000011019 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000011020
John McCallaa81e162009-12-01 22:10:20 +000011021 // If overload resolution picked a static member, build a
11022 // non-member call based on that function.
11023 if (Method->isStatic()) {
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011024 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc, Args,
11025 RParenLoc);
John McCallaa81e162009-12-01 22:10:20 +000011026 }
11027
John McCall129e2df2009-11-30 22:42:35 +000011028 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000011029 }
11030
John McCallf89e55a2010-11-18 06:31:45 +000011031 QualType ResultType = Method->getResultType();
11032 ExprValueKind VK = Expr::getValueKindForType(ResultType);
11033 ResultType = ResultType.getNonLValueExprType(Context);
11034
Douglas Gregor88a35142008-12-22 05:46:06 +000011035 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011036 CXXMemberCallExpr *TheCall =
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011037 new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
John McCallf89e55a2010-11-18 06:31:45 +000011038 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000011039
Anders Carlssoneed3e692009-10-10 00:06:20 +000011040 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011041 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000011042 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000011043 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011044
Douglas Gregor88a35142008-12-22 05:46:06 +000011045 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000011046 // We only need to do this if there was actually an overload; otherwise
11047 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000011048 if (!Method->isStatic()) {
11049 ExprResult ObjectArg =
11050 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
11051 FoundDecl, Method);
11052 if (ObjectArg.isInvalid())
11053 return ExprError();
11054 MemExpr->setBase(ObjectArg.take());
11055 }
Douglas Gregor88a35142008-12-22 05:46:06 +000011056
11057 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000011058 const FunctionProtoType *Proto =
11059 Method->getType()->getAs<FunctionProtoType>();
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011060 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args,
Douglas Gregor88a35142008-12-22 05:46:06 +000011061 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000011062 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000011063
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011064 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011065
Richard Smith831421f2012-06-25 20:30:08 +000011066 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000011067 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000011068
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011069 if ((isa<CXXConstructorDecl>(CurContext) ||
11070 isa<CXXDestructorDecl>(CurContext)) &&
11071 TheCall->getMethodDecl()->isPure()) {
11072 const CXXMethodDecl *MD = TheCall->getMethodDecl();
11073
Chandler Carruthae198062011-06-27 08:31:58 +000011074 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011075 Diag(MemExpr->getLocStart(),
11076 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
11077 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
11078 << MD->getParent()->getDeclName();
11079
11080 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000011081 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000011082 }
John McCall9ae2f072010-08-23 23:25:46 +000011083 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000011084}
11085
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011086/// BuildCallToObjectOfClassType - Build a call to an object of class
11087/// type (C++ [over.call.object]), which can end up invoking an
11088/// overloaded function call operator (@c operator()) or performing a
11089/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000011090ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000011091Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000011092 SourceLocation LParenLoc,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011093 MultiExprArg Args,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011094 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000011095 if (checkPlaceholderForOverload(*this, Obj))
11096 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011097 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000011098
11099 UnbridgedCastsSet UnbridgedCasts;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011100 if (checkArgPlaceholdersForOverload(*this, Args, UnbridgedCasts))
John McCall5acb0c92011-10-17 18:40:02 +000011101 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011102
John Wiegley429bb272011-04-08 18:41:53 +000011103 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
11104 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000011105
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011106 // C++ [over.call.object]p1:
11107 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000011108 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011109 // candidate functions includes at least the function call
11110 // operators of T. The function call operators of T are obtained by
11111 // ordinary lookup of the name operator() in the context of
11112 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000011113 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000011114 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000011115
John Wiegley429bb272011-04-08 18:41:53 +000011116 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011117 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000011118 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011119
John McCalla24dc2e2009-11-17 02:14:36 +000011120 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
11121 LookupQualifiedName(R, Record->getDecl());
11122 R.suppressDiagnostics();
11123
Douglas Gregor593564b2009-11-15 07:48:03 +000011124 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000011125 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000011126 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011127 Object.get()->Classify(Context),
11128 Args, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000011129 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000011130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011131
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011132 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011133 // In addition, for each (non-explicit in C++0x) conversion function
11134 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011135 //
11136 // operator conversion-type-id () cv-qualifier;
11137 //
11138 // where cv-qualifier is the same cv-qualification as, or a
11139 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000011140 // denotes the type "pointer to function of (P1,...,Pn) returning
11141 // R", or the type "reference to pointer to function of
11142 // (P1,...,Pn) returning R", or the type "reference to function
11143 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011144 // is also considered as a candidate function. Similarly,
11145 // surrogate call functions are added to the set of candidate
11146 // functions for each conversion function declared in an
11147 // accessible base class provided the function is not hidden
11148 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011149 std::pair<CXXRecordDecl::conversion_iterator,
11150 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000011151 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000011152 for (CXXRecordDecl::conversion_iterator
11153 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000011154 NamedDecl *D = *I;
11155 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
11156 if (isa<UsingShadowDecl>(D))
11157 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011158
Douglas Gregor4a27d702009-10-21 06:18:39 +000011159 // Skip over templated conversion functions; they aren't
11160 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000011161 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000011162 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000011163
John McCall701c89e2009-12-03 04:06:58 +000011164 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011165 if (!Conv->isExplicit()) {
11166 // Strip the reference type (if any) and then the pointer type (if
11167 // any) to get down to what might be a function type.
11168 QualType ConvType = Conv->getConversionType().getNonReferenceType();
11169 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
11170 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000011171
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011172 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
11173 {
11174 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011175 Object.get(), Args, CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000011176 }
11177 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011178 }
Mike Stump1eb44332009-09-09 15:08:12 +000011179
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011180 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11181
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011182 // Perform overload resolution.
11183 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011184 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011185 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011186 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011187 // Overload resolution succeeded; we'll build the appropriate call
11188 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011189 break;
11190
11191 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011192 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011193 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011194 << Object.get()->getType() << /*call*/ 1
11195 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011196 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011197 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011198 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011199 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011200 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011201 break;
11202
11203 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011204 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011205 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011206 << Object.get()->getType() << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011207 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011208 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011209
11210 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011211 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011212 diag::err_ovl_deleted_object_call)
11213 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011214 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011215 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011216 << Object.get()->getSourceRange();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011217 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011218 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011219 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011220
Douglas Gregorff331c12010-07-25 18:17:45 +000011221 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011222 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011223
John McCall5acb0c92011-10-17 18:40:02 +000011224 UnbridgedCasts.restore();
11225
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011226 if (Best->Function == 0) {
11227 // Since there is no function declaration, this is one of the
11228 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011229 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011230 = cast<CXXConversionDecl>(
11231 Best->Conversions[0].UserDefined.ConversionFunction);
11232
John Wiegley429bb272011-04-08 18:41:53 +000011233 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
Richard Smith82f145d2013-05-04 06:44:46 +000011234 if (DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc))
11235 return ExprError();
Faisal Valid570a922013-06-15 11:54:37 +000011236 assert(Conv == Best->FoundDecl.getDecl() &&
11237 "Found Decl & conversion-to-functionptr should be same, right?!");
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011238 // We selected one of the surrogate functions that converts the
11239 // object parameter to a function pointer. Perform the conversion
11240 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011241
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011242 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011243 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011244 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11245 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011246 if (Call.isInvalid())
11247 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011248 // Record usage of conversion in an implicit cast.
11249 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11250 CK_UserDefinedConversion,
11251 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011252
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011253 return ActOnCallExpr(S, Call.get(), LParenLoc, Args, RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011254 }
11255
John Wiegley429bb272011-04-08 18:41:53 +000011256 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall41d89032010-01-28 01:54:34 +000011257
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011258 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11259 // that calls this method, using Object for the implicit object
11260 // parameter and passing along the remaining arguments.
11261 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011262
11263 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011264 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011265 return ExprError();
11266
Chandler Carruth6df868e2010-12-12 08:17:55 +000011267 const FunctionProtoType *Proto =
11268 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011269
11270 unsigned NumArgsInProto = Proto->getNumArgs();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011271 unsigned NumArgsToCheck = Args.size();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011272
11273 // Build the full argument list for the method call (the
11274 // implicit object parameter is placed at the beginning of the
11275 // list).
11276 Expr **MethodArgs;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011277 if (Args.size() < NumArgsInProto) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011278 NumArgsToCheck = NumArgsInProto;
11279 MethodArgs = new Expr*[NumArgsInProto + 1];
11280 } else {
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011281 MethodArgs = new Expr*[Args.size() + 1];
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011282 }
John Wiegley429bb272011-04-08 18:41:53 +000011283 MethodArgs[0] = Object.get();
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011284 for (unsigned ArgIdx = 0, e = Args.size(); ArgIdx != e; ++ArgIdx)
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011285 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011286
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011287 DeclarationNameInfo OpLocInfo(
11288 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11289 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011290 ExprResult NewFn = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011291 HadMultipleCandidates,
11292 OpLocInfo.getLoc(),
11293 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011294 if (NewFn.isInvalid())
11295 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011296
11297 // Once we've built TheCall, all of the expressions are properly
11298 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011299 QualType ResultTy = Method->getResultType();
11300 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11301 ResultTy = ResultTy.getNonLValueExprType(Context);
11302
John McCall9ae2f072010-08-23 23:25:46 +000011303 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011304 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011305 llvm::makeArrayRef(MethodArgs, Args.size()+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011306 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011307 delete [] MethodArgs;
11308
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011309 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011310 Method))
11311 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011312
Douglas Gregor518fda12009-01-13 05:10:00 +000011313 // We may have default arguments. If so, we need to allocate more
11314 // slots in the call for them.
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011315 if (Args.size() < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011316 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011317 else if (Args.size() > NumArgsInProto)
Douglas Gregor518fda12009-01-13 05:10:00 +000011318 NumArgsToCheck = NumArgsInProto;
11319
Chris Lattner312531a2009-04-12 08:11:20 +000011320 bool IsError = false;
11321
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011322 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011323 ExprResult ObjRes =
11324 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11325 Best->FoundDecl, Method);
11326 if (ObjRes.isInvalid())
11327 IsError = true;
11328 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011329 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011330 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011331
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011332 // Check the argument types.
11333 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011334 Expr *Arg;
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011335 if (i < Args.size()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011336 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011337
Douglas Gregor518fda12009-01-13 05:10:00 +000011338 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011339
John McCall60d7b3a2010-08-24 06:29:42 +000011340 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011341 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011342 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011343 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011344 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011345
Anders Carlsson3faa4862010-01-29 18:43:53 +000011346 IsError |= InputInit.isInvalid();
11347 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011348 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011349 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011350 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11351 if (DefArg.isInvalid()) {
11352 IsError = true;
11353 break;
11354 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011355
Douglas Gregord47c47d2009-11-09 19:27:57 +000011356 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011357 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011358
11359 TheCall->setArg(i + 1, Arg);
11360 }
11361
11362 // If this is a variadic call, handle args passed through "...".
11363 if (Proto->isVariadic()) {
11364 // Promote the arguments (C99 6.5.2.2p7).
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011365 for (unsigned i = NumArgsInProto, e = Args.size(); i < e; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011366 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11367 IsError |= Arg.isInvalid();
11368 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011369 }
11370 }
11371
Chris Lattner312531a2009-04-12 08:11:20 +000011372 if (IsError) return true;
11373
Dmitri Gribenko7297a2e2013-05-09 23:32:58 +000011374 DiagnoseSentinelCalls(Method, LParenLoc, Args);
Eli Friedmane61eb042012-02-18 04:48:30 +000011375
Richard Smith831421f2012-06-25 20:30:08 +000011376 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011377 return true;
11378
John McCall182f7092010-08-24 06:09:16 +000011379 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011380}
11381
Douglas Gregor8ba10742008-11-20 16:27:02 +000011382/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011383/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011384/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011385ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011386Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011387 assert(Base->getType()->isRecordType() &&
11388 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011389
John McCall5acb0c92011-10-17 18:40:02 +000011390 if (checkPlaceholderForOverload(*this, Base))
11391 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011392
John McCall5769d612010-02-08 23:07:23 +000011393 SourceLocation Loc = Base->getExprLoc();
11394
Douglas Gregor8ba10742008-11-20 16:27:02 +000011395 // C++ [over.ref]p1:
11396 //
11397 // [...] An expression x->m is interpreted as (x.operator->())->m
11398 // for a class object x of type T if T::operator->() exists and if
11399 // the operator is selected as the best match function by the
11400 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011401 DeclarationName OpName =
11402 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011403 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011404 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011405
John McCall5769d612010-02-08 23:07:23 +000011406 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011407 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011408 return ExprError();
11409
John McCalla24dc2e2009-11-17 02:14:36 +000011410 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11411 LookupQualifiedName(R, BaseRecord->getDecl());
11412 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011413
11414 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011415 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011416 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
Dmitri Gribenko55431692013-05-05 00:41:58 +000011417 None, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011418 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011419
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011420 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11421
Douglas Gregor8ba10742008-11-20 16:27:02 +000011422 // Perform overload resolution.
11423 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011424 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011425 case OR_Success:
11426 // Overload resolution succeeded; we'll build the call below.
11427 break;
11428
11429 case OR_No_Viable_Function:
11430 if (CandidateSet.empty())
11431 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011432 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011433 else
11434 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011435 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011436 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011437 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011438
11439 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011440 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11441 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011442 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011443 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011444
11445 case OR_Deleted:
11446 Diag(OpLoc, diag::err_ovl_deleted_oper)
11447 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011448 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011449 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011450 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011451 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011452 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011453 }
11454
John McCall9aa472c2010-03-19 07:35:19 +000011455 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
11456
Douglas Gregor8ba10742008-11-20 16:27:02 +000011457 // Convert the object parameter.
11458 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011459 ExprResult BaseResult =
11460 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11461 Best->FoundDecl, Method);
11462 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011463 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011464 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011465
Douglas Gregor8ba10742008-11-20 16:27:02 +000011466 // Build the operator call.
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011467 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method, Best->FoundDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011468 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011469 if (FnExpr.isInvalid())
11470 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011471
John McCallf89e55a2010-11-18 06:31:45 +000011472 QualType ResultTy = Method->getResultType();
11473 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11474 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011475 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011476 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011477 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011478
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011479 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011480 Method))
11481 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011482
11483 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011484}
11485
Richard Smith36f5cfe2012-03-09 08:00:36 +000011486/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11487/// a literal operator described by the provided lookup results.
11488ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11489 DeclarationNameInfo &SuffixInfo,
11490 ArrayRef<Expr*> Args,
11491 SourceLocation LitEndLoc,
11492 TemplateArgumentListInfo *TemplateArgs) {
11493 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011494
Richard Smith36f5cfe2012-03-09 08:00:36 +000011495 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11496 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11497 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011498
Richard Smith36f5cfe2012-03-09 08:00:36 +000011499 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11500
Richard Smith36f5cfe2012-03-09 08:00:36 +000011501 // Perform overload resolution. This will usually be trivial, but might need
11502 // to perform substitutions for a literal operator template.
11503 OverloadCandidateSet::iterator Best;
11504 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11505 case OR_Success:
11506 case OR_Deleted:
11507 break;
11508
11509 case OR_No_Viable_Function:
11510 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11511 << R.getLookupName();
11512 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11513 return ExprError();
11514
11515 case OR_Ambiguous:
11516 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11517 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11518 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011519 }
11520
Richard Smith36f5cfe2012-03-09 08:00:36 +000011521 FunctionDecl *FD = Best->Function;
Nick Lewyckyf5a6aef2013-02-07 05:08:22 +000011522 ExprResult Fn = CreateFunctionRefExpr(*this, FD, Best->FoundDecl,
11523 HadMultipleCandidates,
Richard Smith36f5cfe2012-03-09 08:00:36 +000011524 SuffixInfo.getLoc(),
11525 SuffixInfo.getInfo());
11526 if (Fn.isInvalid())
11527 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011528
11529 // Check the argument types. This should almost always be a no-op, except
11530 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011531 Expr *ConvArgs[2];
Richard Smith958ba642013-05-05 15:51:06 +000011532 for (unsigned ArgIdx = 0, N = Args.size(); ArgIdx != N; ++ArgIdx) {
Richard Smith9fcce652012-03-07 08:35:16 +000011533 ExprResult InputInit = PerformCopyInitialization(
11534 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11535 SourceLocation(), Args[ArgIdx]);
11536 if (InputInit.isInvalid())
11537 return true;
11538 ConvArgs[ArgIdx] = InputInit.take();
11539 }
11540
Richard Smith9fcce652012-03-07 08:35:16 +000011541 QualType ResultTy = FD->getResultType();
11542 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11543 ResultTy = ResultTy.getNonLValueExprType(Context);
11544
Richard Smith9fcce652012-03-07 08:35:16 +000011545 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011546 new (Context) UserDefinedLiteral(Context, Fn.take(),
11547 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011548 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11549
11550 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11551 return ExprError();
11552
Richard Smith831421f2012-06-25 20:30:08 +000011553 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011554 return ExprError();
11555
11556 return MaybeBindToTemporary(UDL);
11557}
11558
Sam Panzere1715b62012-08-21 00:52:01 +000011559/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11560/// given LookupResult is non-empty, it is assumed to describe a member which
11561/// will be invoked. Otherwise, the function will be found via argument
11562/// dependent lookup.
11563/// CallExpr is set to a valid expression and FRS_Success returned on success,
11564/// otherwise CallExpr is set to ExprError() and some non-success value
11565/// is returned.
11566Sema::ForRangeStatus
11567Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11568 SourceLocation RangeLoc, VarDecl *Decl,
11569 BeginEndFunction BEF,
11570 const DeclarationNameInfo &NameInfo,
11571 LookupResult &MemberLookup,
11572 OverloadCandidateSet *CandidateSet,
11573 Expr *Range, ExprResult *CallExpr) {
11574 CandidateSet->clear();
11575 if (!MemberLookup.empty()) {
11576 ExprResult MemberRef =
11577 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11578 /*IsPtr=*/false, CXXScopeSpec(),
11579 /*TemplateKWLoc=*/SourceLocation(),
11580 /*FirstQualifierInScope=*/0,
11581 MemberLookup,
11582 /*TemplateArgs=*/0);
11583 if (MemberRef.isInvalid()) {
11584 *CallExpr = ExprError();
11585 Diag(Range->getLocStart(), diag::note_in_for_range)
11586 << RangeLoc << BEF << Range->getType();
11587 return FRS_DiagnosticIssued;
11588 }
Dmitri Gribenko62ed8892013-05-05 20:40:26 +000011589 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, None, Loc, 0);
Sam Panzere1715b62012-08-21 00:52:01 +000011590 if (CallExpr->isInvalid()) {
11591 *CallExpr = ExprError();
11592 Diag(Range->getLocStart(), diag::note_in_for_range)
11593 << RangeLoc << BEF << Range->getType();
11594 return FRS_DiagnosticIssued;
11595 }
11596 } else {
11597 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011598 UnresolvedLookupExpr *Fn =
11599 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11600 NestedNameSpecifierLoc(), NameInfo,
11601 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011602 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011603
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011604 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, Range, Loc,
Sam Panzere1715b62012-08-21 00:52:01 +000011605 CandidateSet, CallExpr);
11606 if (CandidateSet->empty() || CandidateSetError) {
11607 *CallExpr = ExprError();
11608 return FRS_NoViableFunction;
11609 }
11610 OverloadCandidateSet::iterator Best;
11611 OverloadingResult OverloadResult =
11612 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11613
11614 if (OverloadResult == OR_No_Viable_Function) {
11615 *CallExpr = ExprError();
11616 return FRS_NoViableFunction;
11617 }
Dmitri Gribenko9e00f122013-05-09 21:02:07 +000011618 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, Range,
Sam Panzere1715b62012-08-21 00:52:01 +000011619 Loc, 0, CandidateSet, &Best,
11620 OverloadResult,
11621 /*AllowTypoCorrection=*/false);
11622 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11623 *CallExpr = ExprError();
11624 Diag(Range->getLocStart(), diag::note_in_for_range)
11625 << RangeLoc << BEF << Range->getType();
11626 return FRS_DiagnosticIssued;
11627 }
11628 }
11629 return FRS_Success;
11630}
11631
11632
Douglas Gregor904eed32008-11-10 20:40:00 +000011633/// FixOverloadedFunctionReference - E is an expression that refers to
11634/// a C++ overloaded function (possibly with some parentheses and
11635/// perhaps a '&' around it). We have resolved the overloaded function
11636/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011637/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011638Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011639 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011640 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011641 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11642 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011643 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011644 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011645
Douglas Gregor699ee522009-11-20 19:42:02 +000011646 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011647 }
11648
Douglas Gregor699ee522009-11-20 19:42:02 +000011649 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011650 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11651 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011652 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011653 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011654 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011655 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011656 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011657 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011658
11659 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011660 ICE->getCastKind(),
11661 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011662 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011663 }
11664
Douglas Gregor699ee522009-11-20 19:42:02 +000011665 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011666 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011667 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011668 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11669 if (Method->isStatic()) {
11670 // Do nothing: static member functions aren't any different
11671 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011672 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011673 // Fix the sub expression, which really has to be an
11674 // UnresolvedLookupExpr holding an overloaded member function
11675 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011676 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11677 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011678 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011679 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011680
John McCallba135432009-11-21 08:51:07 +000011681 assert(isa<DeclRefExpr>(SubExpr)
11682 && "fixed to something other than a decl ref");
11683 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11684 && "fixed to a member ref with no nested name qualifier");
11685
11686 // We have taken the address of a pointer to member
11687 // function. Perform the computation here so that we get the
11688 // appropriate pointer to member type.
11689 QualType ClassType
11690 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11691 QualType MemPtrType
11692 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11693
John McCallf89e55a2010-11-18 06:31:45 +000011694 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11695 VK_RValue, OK_Ordinary,
11696 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011697 }
11698 }
John McCall6bb80172010-03-30 21:47:33 +000011699 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11700 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011701 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011702 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011703
John McCall2de56d12010-08-25 11:45:40 +000011704 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011705 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011706 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011707 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011708 }
John McCallba135432009-11-21 08:51:07 +000011709
11710 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011711 // FIXME: avoid copy.
11712 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011713 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011714 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11715 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011716 }
11717
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011718 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11719 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011720 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011721 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011722 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011723 ULE->getNameLoc(),
11724 Fn->getType(),
11725 VK_LValue,
11726 Found.getDecl(),
11727 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011728 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011729 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11730 return DRE;
John McCallba135432009-11-21 08:51:07 +000011731 }
11732
John McCall129e2df2009-11-30 22:42:35 +000011733 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011734 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011735 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11736 if (MemExpr->hasExplicitTemplateArgs()) {
11737 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11738 TemplateArgs = &TemplateArgsBuffer;
11739 }
John McCalld5532b62009-11-23 01:53:49 +000011740
John McCallaa81e162009-12-01 22:10:20 +000011741 Expr *Base;
11742
John McCallf89e55a2010-11-18 06:31:45 +000011743 // If we're filling in a static method where we used to have an
11744 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011745 if (MemExpr->isImplicitAccess()) {
11746 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011747 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11748 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011749 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011750 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011751 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011752 MemExpr->getMemberLoc(),
11753 Fn->getType(),
11754 VK_LValue,
11755 Found.getDecl(),
11756 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011757 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011758 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11759 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011760 } else {
11761 SourceLocation Loc = MemExpr->getMemberLoc();
11762 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011763 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011764 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011765 Base = new (Context) CXXThisExpr(Loc,
11766 MemExpr->getBaseType(),
11767 /*isImplicit=*/true);
11768 }
John McCallaa81e162009-12-01 22:10:20 +000011769 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011770 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011771
John McCallf5307512011-04-27 00:36:17 +000011772 ExprValueKind valueKind;
11773 QualType type;
11774 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11775 valueKind = VK_LValue;
11776 type = Fn->getType();
11777 } else {
11778 valueKind = VK_RValue;
11779 type = Context.BoundMemberTy;
11780 }
11781
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011782 MemberExpr *ME = MemberExpr::Create(Context, Base,
11783 MemExpr->isArrow(),
11784 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011785 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011786 Fn,
11787 Found,
11788 MemExpr->getMemberNameInfo(),
11789 TemplateArgs,
11790 type, valueKind, OK_Ordinary);
11791 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011792 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011793 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011794 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011795
John McCall3fa5cae2010-10-26 07:05:15 +000011796 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011797}
11798
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011799ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011800 DeclAccessPair Found,
11801 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011802 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011803}
11804
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011805} // end namespace clang