blob: 82fe0c9ed080f3c34e87a4729ed6d8de0c77866b [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
John McCallf89e55a2010-11-18 06:31:45 +000039/// A convenience routine for creating a decayed reference to a
40/// function.
John Wiegley429bb272011-04-08 18:41:53 +000041static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000045 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000046 VK_LValue, Loc, LocInfo);
47 if (HadMultipleCandidates)
48 DRE->setHadMultipleCandidates(true);
49 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000050 E = S.DefaultFunctionArrayConversion(E.take());
51 if (E.isInvalid())
52 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000053 return E;
John McCallf89e55a2010-11-18 06:31:45 +000054}
55
John McCall120d63c2010-08-24 20:38:10 +000056static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000058 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000059 bool CStyle,
60 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000061
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000062static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63 QualType &ToType,
64 bool InOverloadResolution,
65 StandardConversionSequence &SCS,
66 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000067static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69 UserDefinedConversionSequence& User,
70 OverloadCandidateSet& Conversions,
71 bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86 const StandardConversionSequence& SCS1,
87 const StandardConversionSequence& SCS2);
88
89
90
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000091/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000093ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094GetConversionCategory(ImplicitConversionKind Kind) {
95 static const ImplicitConversionCategory
96 Category[(int)ICK_Num_Conversion_Kinds] = {
97 ICC_Identity,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
100 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000101 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000102 ICC_Qualification_Adjustment,
103 ICC_Promotion,
104 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 ICC_Promotion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
112 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000113 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000114 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000115 ICC_Conversion,
116 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000117 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000118 ICC_Conversion
119 };
120 return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126 static const ImplicitConversionRank
127 Rank[(int)ICK_Num_Conversion_Kinds] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000133 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134 ICR_Promotion,
135 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000144 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000145 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000146 ICR_Conversion,
147 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000148 ICR_Complex_Real_Conversion,
149 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000150 ICR_Conversion,
151 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 };
153 return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000160 "No conversion",
161 "Lvalue-to-rvalue",
162 "Array-to-pointer",
163 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000164 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165 "Qualification",
166 "Integral promotion",
167 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000168 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169 "Integral conversion",
170 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000171 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 "Floating-integral conversion",
173 "Pointer conversion",
174 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000175 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000176 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000177 "Derived-to-base conversion",
178 "Vector conversion",
179 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000183 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000184 };
185 return Name[Kind];
186}
187
Douglas Gregor60d62c22008-10-31 16:23:19 +0000188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191 First = ICK_Identity;
192 Second = ICK_Identity;
193 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000194 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000195 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000196 ReferenceBinding = false;
197 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000198 IsLvalueReference = true;
199 BindsToFunctionLvalue = false;
200 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000201 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000202 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000203 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000204}
205
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210 ImplicitConversionRank Rank = ICR_Exact_Match;
211 if (GetConversionRank(First) > Rank)
212 Rank = GetConversionRank(First);
213 if (GetConversionRank(Second) > Rank)
214 Rank = GetConversionRank(Second);
215 if (GetConversionRank(Third) > Rank)
216 Rank = GetConversionRank(Third);
217 return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000222/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000224bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer or function-to-pointer implicit conversions, so
227 // check for their presence as well as checking whether FromType is
228 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000229 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000230 (getFromType()->isPointerType() ||
231 getFromType()->isObjCObjectPointerType() ||
232 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000233 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 return true;
236
237 return false;
238}
239
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000244bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000245StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000246isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000247 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000248 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000249
250 // Note that FromType has not necessarily been transformed by the
251 // array-to-pointer implicit conversion, so check for its presence
252 // and redo the conversion to get a pointer.
253 if (First == ICK_Array_To_Pointer)
254 FromType = Context.getArrayDecayedType(FromType);
255
Douglas Gregorf9af5242011-04-15 20:45:44 +0000256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000258 return ToPtrType->getPointeeType()->isVoidType();
259
260 return false;
261}
262
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267 switch (ICE->getCastKind()) {
268 case CK_NoOp:
269 case CK_IntegralCast:
270 case CK_IntegralToBoolean:
271 case CK_IntegralToFloating:
272 case CK_FloatingToIntegral:
273 case CK_FloatingToBoolean:
274 case CK_FloatingCast:
275 Converted = ICE->getSubExpr();
276 continue;
277
278 default:
279 return Converted;
280 }
281 }
282
283 return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx The AST context.
290/// \param Converted The result of applying this standard conversion sequence.
291/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
292/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000293/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
294/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000295NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000298 APValue &ConstantValue,
299 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000301
302 // C++11 [dcl.init.list]p7:
303 // A narrowing conversion is an implicit conversion ...
304 QualType FromType = getToType(0);
305 QualType ToType = getToType(1);
306 switch (Second) {
307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000366 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
378 case ICK_Boolean_Conversion: // Bools are integers too.
379 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380 // Boolean conversions can be from pointers and pointers to members
381 // [conv.bool], and those aren't considered narrowing conversions.
382 return NK_Not_Narrowing;
383 } // Otherwise, fall through to the integral case.
384 case ICK_Integral_Conversion: {
385 assert(FromType->isIntegralOrUnscopedEnumerationType());
386 assert(ToType->isIntegralOrUnscopedEnumerationType());
387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388 const unsigned FromWidth = Ctx.getIntWidth(FromType);
389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390 const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000393 (FromWidth == ToWidth && FromSigned != ToSigned) ||
394 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000395 // Not all values of FromType can be represented in ToType.
396 llvm::APSInt InitializerValue;
397 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399 // Such conversions on variables are always narrowing.
400 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000401 }
402 bool Narrowing = false;
403 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000404 // Negative -> unsigned is narrowing. Otherwise, more bits is never
405 // narrowing.
406 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000407 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000408 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000409 // Add a bit to the InitializerValue so we don't have to worry about
410 // signed vs. unsigned comparisons.
411 InitializerValue = InitializerValue.extend(
412 InitializerValue.getBitWidth() + 1);
413 // Convert the initializer to and from the target width and signed-ness.
414 llvm::APSInt ConvertedValue = InitializerValue;
415 ConvertedValue = ConvertedValue.trunc(ToWidth);
416 ConvertedValue.setIsSigned(ToSigned);
417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418 ConvertedValue.setIsSigned(InitializerValue.isSigned());
419 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000420 if (ConvertedValue != InitializerValue)
421 Narrowing = true;
422 }
423 if (Narrowing) {
424 ConstantType = Initializer->getType();
425 ConstantValue = APValue(InitializerValue);
426 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000427 }
428 }
429 return NK_Not_Narrowing;
430 }
431
432 default:
433 // Other kinds of conversions are not narrowings.
434 return NK_Not_Narrowing;
435 }
436}
437
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000441 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 bool PrintedSomething = false;
443 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000444 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000445 PrintedSomething = true;
446 }
447
448 if (Second != ICK_Identity) {
449 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000450 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000453
454 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000455 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000456 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000458 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000459 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000460 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Third != ICK_Identity) {
465 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000466 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000467 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000473 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481 if (Before.First || Before.Second || Before.Third) {
482 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000483 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000484 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000485 if (ConversionFunction)
486 OS << '\'' << *ConversionFunction << '\'';
487 else
488 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 After.DebugPrint();
492 }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000498 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 switch (ConversionKind) {
500 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000501 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 Standard.DebugPrint();
503 break;
504 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 UserDefined.DebugPrint();
507 break;
508 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000509 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 break;
John McCall1d318332010-01-12 00:44:57 +0000511 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000512 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000513 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000515 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 break;
517 }
518
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000519 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520}
521
John McCall1d318332010-01-12 00:44:57 +0000522void AmbiguousConversionSequence::construct() {
523 new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527 conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532 FromTypePtr = O.FromTypePtr;
533 ToTypePtr = O.ToTypePtr;
534 new (&conversions()) ConversionSet(O.conversions());
535}
536
Douglas Gregora9333192010-05-08 17:41:32 +0000537namespace {
538 // Structure used by OverloadCandidate::DeductionFailureInfo to store
Richard Smith29805ca2013-01-31 05:19:49 +0000539 // template argument information.
540 struct DFIArguments {
Douglas Gregora9333192010-05-08 17:41:32 +0000541 TemplateArgument FirstArg;
542 TemplateArgument SecondArg;
543 };
Richard Smith29805ca2013-01-31 05:19:49 +0000544 // Structure used by OverloadCandidate::DeductionFailureInfo to store
545 // template parameter and template argument information.
546 struct DFIParamWithArguments : DFIArguments {
547 TemplateParameter Param;
548 };
Douglas Gregora9333192010-05-08 17:41:32 +0000549}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000550
Douglas Gregora9333192010-05-08 17:41:32 +0000551/// \brief Convert from Sema's representation of template deduction information
552/// to the form used in overload-candidate information.
553OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000554static MakeDeductionFailureInfo(ASTContext &Context,
555 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000556 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000557 OverloadCandidate::DeductionFailureInfo Result;
558 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000559 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000560 Result.Data = 0;
561 switch (TDK) {
562 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000563 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000564 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000565 case Sema::TDK_TooManyArguments:
566 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000567 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000568
Douglas Gregora9333192010-05-08 17:41:32 +0000569 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000570 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000571 Result.Data = Info.Param.getOpaqueValue();
572 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000573
Richard Smith29805ca2013-01-31 05:19:49 +0000574 case Sema::TDK_NonDeducedMismatch: {
575 // FIXME: Should allocate from normal heap so that we can free this later.
576 DFIArguments *Saved = new (Context) DFIArguments;
577 Saved->FirstArg = Info.FirstArg;
578 Saved->SecondArg = Info.SecondArg;
579 Result.Data = Saved;
580 break;
581 }
582
Douglas Gregora9333192010-05-08 17:41:32 +0000583 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000584 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000585 // FIXME: Should allocate from normal heap so that we can free this later.
586 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000587 Saved->Param = Info.Param;
588 Saved->FirstArg = Info.FirstArg;
589 Saved->SecondArg = Info.SecondArg;
590 Result.Data = Saved;
591 break;
592 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593
Douglas Gregora9333192010-05-08 17:41:32 +0000594 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000595 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000596 if (Info.hasSFINAEDiagnostic()) {
597 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
598 SourceLocation(), PartialDiagnostic::NullDiagnostic());
599 Info.takeSFINAEDiagnostic(*Diag);
600 Result.HasDiagnostic = true;
601 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000602 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000603
Douglas Gregora9333192010-05-08 17:41:32 +0000604 case Sema::TDK_FailedOverloadResolution:
Richard Smith0efa62f2013-01-31 04:03:12 +0000605 Result.Data = Info.Expression;
606 break;
607
Richard Smith29805ca2013-01-31 05:19:49 +0000608 case Sema::TDK_MiscellaneousDeductionFailure:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000610 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000611
Douglas Gregora9333192010-05-08 17:41:32 +0000612 return Result;
613}
John McCall1d318332010-01-12 00:44:57 +0000614
Douglas Gregora9333192010-05-08 17:41:32 +0000615void OverloadCandidate::DeductionFailureInfo::Destroy() {
616 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
617 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000618 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000619 case Sema::TDK_InstantiationDepth:
620 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000621 case Sema::TDK_TooManyArguments:
622 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000623 case Sema::TDK_InvalidExplicitArguments:
Richard Smith29805ca2013-01-31 05:19:49 +0000624 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000625 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000626
Douglas Gregora9333192010-05-08 17:41:32 +0000627 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000628 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000629 case Sema::TDK_NonDeducedMismatch:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000630 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000631 Data = 0;
632 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000633
634 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000635 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000636 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000637 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
638 Diag->~PartialDiagnosticAt();
639 HasDiagnostic = false;
640 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000641 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000642
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000643 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000644 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000645 break;
646 }
647}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000648
Richard Smithb8590f32012-05-07 09:03:25 +0000649PartialDiagnosticAt *
650OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
651 if (HasDiagnostic)
652 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
653 return 0;
654}
655
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000656TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000657OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
658 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
659 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000660 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000661 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000662 case Sema::TDK_TooManyArguments:
663 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000664 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000665 case Sema::TDK_NonDeducedMismatch:
666 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000667 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000668
Douglas Gregora9333192010-05-08 17:41:32 +0000669 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000670 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000671 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000672
673 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000674 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000675 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000676
Douglas Gregora9333192010-05-08 17:41:32 +0000677 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000678 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000679 break;
680 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000681
Douglas Gregora9333192010-05-08 17:41:32 +0000682 return TemplateParameter();
683}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000684
Douglas Gregorec20f462010-05-08 20:07:26 +0000685TemplateArgumentList *
686OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
687 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
Richard Smith29805ca2013-01-31 05:19:49 +0000688 case Sema::TDK_Success:
689 case Sema::TDK_Invalid:
690 case Sema::TDK_InstantiationDepth:
691 case Sema::TDK_TooManyArguments:
692 case Sema::TDK_TooFewArguments:
693 case Sema::TDK_Incomplete:
694 case Sema::TDK_InvalidExplicitArguments:
695 case Sema::TDK_Inconsistent:
696 case Sema::TDK_Underqualified:
697 case Sema::TDK_NonDeducedMismatch:
698 case Sema::TDK_FailedOverloadResolution:
699 return 0;
Douglas Gregorec20f462010-05-08 20:07:26 +0000700
Richard Smith29805ca2013-01-31 05:19:49 +0000701 case Sema::TDK_SubstitutionFailure:
702 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000703
Richard Smith29805ca2013-01-31 05:19:49 +0000704 // Unhandled
705 case Sema::TDK_MiscellaneousDeductionFailure:
706 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000707 }
708
709 return 0;
710}
711
Douglas Gregora9333192010-05-08 17:41:32 +0000712const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
713 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
714 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000715 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000716 case Sema::TDK_InstantiationDepth:
717 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000718 case Sema::TDK_TooManyArguments:
719 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000720 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000721 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000722 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000723 return 0;
724
Douglas Gregora9333192010-05-08 17:41:32 +0000725 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000726 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000727 case Sema::TDK_NonDeducedMismatch:
728 return &static_cast<DFIArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000729
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000730 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000731 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000732 break;
733 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000734
Douglas Gregora9333192010-05-08 17:41:32 +0000735 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000736}
Douglas Gregora9333192010-05-08 17:41:32 +0000737
738const TemplateArgument *
739OverloadCandidate::DeductionFailureInfo::getSecondArg() {
740 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
741 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000742 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000743 case Sema::TDK_InstantiationDepth:
744 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000745 case Sema::TDK_TooManyArguments:
746 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000747 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000748 case Sema::TDK_SubstitutionFailure:
Richard Smith29805ca2013-01-31 05:19:49 +0000749 case Sema::TDK_FailedOverloadResolution:
Douglas Gregora9333192010-05-08 17:41:32 +0000750 return 0;
751
Douglas Gregora9333192010-05-08 17:41:32 +0000752 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000753 case Sema::TDK_Underqualified:
Richard Smith29805ca2013-01-31 05:19:49 +0000754 case Sema::TDK_NonDeducedMismatch:
755 return &static_cast<DFIArguments*>(Data)->SecondArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000756
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000757 // Unhandled
Richard Smith29805ca2013-01-31 05:19:49 +0000758 case Sema::TDK_MiscellaneousDeductionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000759 break;
760 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000761
Douglas Gregora9333192010-05-08 17:41:32 +0000762 return 0;
763}
764
Richard Smith0efa62f2013-01-31 04:03:12 +0000765Expr *
766OverloadCandidate::DeductionFailureInfo::getExpr() {
767 if (static_cast<Sema::TemplateDeductionResult>(Result) ==
768 Sema::TDK_FailedOverloadResolution)
769 return static_cast<Expr*>(Data);
770
771 return 0;
772}
773
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000774void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000775 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000776 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
777 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000778 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
779 i->DeductionFailure.Destroy();
780 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000781}
782
783void OverloadCandidateSet::clear() {
784 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000785 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000786 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000787 Functions.clear();
788}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000789
John McCall5acb0c92011-10-17 18:40:02 +0000790namespace {
791 class UnbridgedCastsSet {
792 struct Entry {
793 Expr **Addr;
794 Expr *Saved;
795 };
796 SmallVector<Entry, 2> Entries;
797
798 public:
799 void save(Sema &S, Expr *&E) {
800 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
801 Entry entry = { &E, E };
802 Entries.push_back(entry);
803 E = S.stripARCUnbridgedCast(E);
804 }
805
806 void restore() {
807 for (SmallVectorImpl<Entry>::iterator
808 i = Entries.begin(), e = Entries.end(); i != e; ++i)
809 *i->Addr = i->Saved;
810 }
811 };
812}
813
814/// checkPlaceholderForOverload - Do any interesting placeholder-like
815/// preprocessing on the given expression.
816///
817/// \param unbridgedCasts a collection to which to add unbridged casts;
818/// without this, they will be immediately diagnosed as errors
819///
820/// Return true on unrecoverable error.
821static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
822 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000823 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
824 // We can't handle overloaded expressions here because overload
825 // resolution might reasonably tweak them.
826 if (placeholder->getKind() == BuiltinType::Overload) return false;
827
828 // If the context potentially accepts unbridged ARC casts, strip
829 // the unbridged cast and add it to the collection for later restoration.
830 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
831 unbridgedCasts) {
832 unbridgedCasts->save(S, E);
833 return false;
834 }
835
836 // Go ahead and check everything else.
837 ExprResult result = S.CheckPlaceholderExpr(E);
838 if (result.isInvalid())
839 return true;
840
841 E = result.take();
842 return false;
843 }
844
845 // Nothing to do.
846 return false;
847}
848
849/// checkArgPlaceholdersForOverload - Check a set of call operands for
850/// placeholders.
851static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
852 unsigned numArgs,
853 UnbridgedCastsSet &unbridged) {
854 for (unsigned i = 0; i != numArgs; ++i)
855 if (checkPlaceholderForOverload(S, args[i], &unbridged))
856 return true;
857
858 return false;
859}
860
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000861// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000862// overload of the declarations in Old. This routine returns false if
863// New and Old cannot be overloaded, e.g., if New has the same
864// signature as some function in Old (C++ 1.3.10) or if the Old
865// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000866// it does return false, MatchedDecl will point to the decl that New
867// cannot be overloaded with. This decl may be a UsingShadowDecl on
868// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000869//
870// Example: Given the following input:
871//
872// void f(int, float); // #1
873// void f(int, int); // #2
874// int f(int, int); // #3
875//
876// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000877// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000878//
John McCall51fa86f2009-12-02 08:47:38 +0000879// When we process #2, Old contains only the FunctionDecl for #1. By
880// comparing the parameter types, we see that #1 and #2 are overloaded
881// (since they have different signatures), so this routine returns
882// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000883//
John McCall51fa86f2009-12-02 08:47:38 +0000884// When we process #3, Old is an overload set containing #1 and #2. We
885// compare the signatures of #3 to #1 (they're overloaded, so we do
886// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
887// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000888// signature), IsOverload returns false and MatchedDecl will be set to
889// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000890//
891// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
892// into a class by a using declaration. The rules for whether to hide
893// shadow declarations ignore some properties which otherwise figure
894// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000895Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000896Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
897 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000898 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000899 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000900 NamedDecl *OldD = *I;
901
902 bool OldIsUsingDecl = false;
903 if (isa<UsingShadowDecl>(OldD)) {
904 OldIsUsingDecl = true;
905
906 // We can always introduce two using declarations into the same
907 // context, even if they have identical signatures.
908 if (NewIsUsingDecl) continue;
909
910 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
911 }
912
913 // If either declaration was introduced by a using declaration,
914 // we'll need to use slightly different rules for matching.
915 // Essentially, these rules are the normal rules, except that
916 // function templates hide function templates with different
917 // return types or template parameter lists.
918 bool UseMemberUsingDeclRules =
919 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
920
John McCall51fa86f2009-12-02 08:47:38 +0000921 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000922 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
923 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
924 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
925 continue;
926 }
927
John McCall871b2e72009-12-09 03:35:25 +0000928 Match = *I;
929 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000930 }
John McCall51fa86f2009-12-02 08:47:38 +0000931 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000932 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
933 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
934 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
935 continue;
936 }
937
John McCall871b2e72009-12-09 03:35:25 +0000938 Match = *I;
939 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000940 }
John McCalld7945c62010-11-10 03:01:53 +0000941 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000942 // We can overload with these, which can show up when doing
943 // redeclaration checks for UsingDecls.
944 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000945 } else if (isa<TagDecl>(OldD)) {
946 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000947 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
948 // Optimistically assume that an unresolved using decl will
949 // overload; if it doesn't, we'll have to diagnose during
950 // template instantiation.
951 } else {
John McCall68263142009-11-18 22:49:29 +0000952 // (C++ 13p1):
953 // Only function declarations can be overloaded; object and type
954 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000955 Match = *I;
956 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000957 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000958 }
John McCall68263142009-11-18 22:49:29 +0000959
John McCall871b2e72009-12-09 03:35:25 +0000960 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000961}
962
Rafael Espindola78eeba82012-12-28 14:21:58 +0000963static bool canBeOverloaded(const FunctionDecl &D) {
964 if (D.getAttr<OverloadableAttr>())
965 return true;
966 if (D.hasCLanguageLinkage())
967 return false;
Rafael Espindola7a525ac2013-01-12 01:47:40 +0000968
969 // Main cannot be overloaded (basic.start.main).
970 if (D.isMain())
971 return false;
972
Rafael Espindola78eeba82012-12-28 14:21:58 +0000973 return true;
974}
975
John McCallad00b772010-06-16 08:42:20 +0000976bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
977 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000978 // If both of the functions are extern "C", then they are not
979 // overloads.
Rafael Espindola78eeba82012-12-28 14:21:58 +0000980 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
John McCall7b492022010-08-12 07:09:11 +0000981 return false;
982
John McCall68263142009-11-18 22:49:29 +0000983 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
984 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
985
986 // C++ [temp.fct]p2:
987 // A function template can be overloaded with other function templates
988 // and with normal (non-template) functions.
989 if ((OldTemplate == 0) != (NewTemplate == 0))
990 return true;
991
992 // Is the function New an overload of the function Old?
993 QualType OldQType = Context.getCanonicalType(Old->getType());
994 QualType NewQType = Context.getCanonicalType(New->getType());
995
996 // Compare the signatures (C++ 1.3.10) of the two functions to
997 // determine whether they are overloads. If we find any mismatch
998 // in the signature, they are overloads.
999
1000 // If either of these functions is a K&R-style function (no
1001 // prototype), then we consider them to have matching signatures.
1002 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
1003 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
1004 return false;
1005
John McCallf4c73712011-01-19 06:33:43 +00001006 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
1007 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +00001008
1009 // The signature of a function includes the types of its
1010 // parameters (C++ 1.3.10), which includes the presence or absence
1011 // of the ellipsis; see C++ DR 357).
1012 if (OldQType != NewQType &&
1013 (OldType->getNumArgs() != NewType->getNumArgs() ||
1014 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001015 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +00001016 return true;
1017
1018 // C++ [temp.over.link]p4:
1019 // The signature of a function template consists of its function
1020 // signature, its return type and its template parameter list. The names
1021 // of the template parameters are significant only for establishing the
1022 // relationship between the template parameters and the rest of the
1023 // signature.
1024 //
1025 // We check the return type and template parameter lists for function
1026 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +00001027 //
1028 // However, we don't consider either of these when deciding whether
1029 // a member introduced by a shadow declaration is hidden.
1030 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +00001031 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
1032 OldTemplate->getTemplateParameters(),
1033 false, TPL_TemplateMatch) ||
1034 OldType->getResultType() != NewType->getResultType()))
1035 return true;
1036
1037 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001038 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001039 //
1040 // As part of this, also check whether one of the member functions
1041 // is static, in which case they are not overloads (C++
1042 // 13.1p2). While not part of the definition of the signature,
1043 // this check is important to determine whether these functions
1044 // can be overloaded.
Richard Smith21c8fa82013-01-14 05:37:29 +00001045 CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
1046 CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
John McCall68263142009-11-18 22:49:29 +00001047 if (OldMethod && NewMethod &&
Richard Smith21c8fa82013-01-14 05:37:29 +00001048 !OldMethod->isStatic() && !NewMethod->isStatic()) {
1049 if (OldMethod->getRefQualifier() != NewMethod->getRefQualifier()) {
1050 if (!UseUsingDeclRules &&
1051 (OldMethod->getRefQualifier() == RQ_None ||
1052 NewMethod->getRefQualifier() == RQ_None)) {
1053 // C++0x [over.load]p2:
1054 // - Member function declarations with the same name and the same
1055 // parameter-type-list as well as member function template
1056 // declarations with the same name, the same parameter-type-list, and
1057 // the same template parameter lists cannot be overloaded if any of
1058 // them, but not all, have a ref-qualifier (8.3.5).
1059 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1060 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1061 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1062 }
1063 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001064 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001065
Richard Smith21c8fa82013-01-14 05:37:29 +00001066 // We may not have applied the implicit const for a constexpr member
1067 // function yet (because we haven't yet resolved whether this is a static
1068 // or non-static member function). Add it now, on the assumption that this
1069 // is a redeclaration of OldMethod.
1070 unsigned NewQuals = NewMethod->getTypeQualifiers();
Richard Smith714fcc12013-01-14 08:00:39 +00001071 if (NewMethod->isConstexpr() && !isa<CXXConstructorDecl>(NewMethod))
Richard Smith21c8fa82013-01-14 05:37:29 +00001072 NewQuals |= Qualifiers::Const;
1073 if (OldMethod->getTypeQualifiers() != NewQuals)
1074 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001075 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001076
John McCall68263142009-11-18 22:49:29 +00001077 // The signatures match; this is not an overload.
1078 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001079}
1080
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001081/// \brief Checks availability of the function depending on the current
1082/// function context. Inside an unavailable function, unavailability is ignored.
1083///
1084/// \returns true if \arg FD is unavailable and current context is inside
1085/// an available function, false otherwise.
1086bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1087 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1088}
1089
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001090/// \brief Tries a user-defined conversion from From to ToType.
1091///
1092/// Produces an implicit conversion sequence for when a standard conversion
1093/// is not an option. See TryImplicitConversion for more information.
1094static ImplicitConversionSequence
1095TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1096 bool SuppressUserConversions,
1097 bool AllowExplicit,
1098 bool InOverloadResolution,
1099 bool CStyle,
1100 bool AllowObjCWritebackConversion) {
1101 ImplicitConversionSequence ICS;
1102
1103 if (SuppressUserConversions) {
1104 // We're not in the case above, so there is no conversion that
1105 // we can perform.
1106 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1107 return ICS;
1108 }
1109
1110 // Attempt user-defined conversion.
1111 OverloadCandidateSet Conversions(From->getExprLoc());
1112 OverloadingResult UserDefResult
1113 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1114 AllowExplicit);
1115
1116 if (UserDefResult == OR_Success) {
1117 ICS.setUserDefined();
1118 // C++ [over.ics.user]p4:
1119 // A conversion of an expression of class type to the same class
1120 // type is given Exact Match rank, and a conversion of an
1121 // expression of class type to a base class of that type is
1122 // given Conversion rank, in spite of the fact that a copy
1123 // constructor (i.e., a user-defined conversion function) is
1124 // called for those cases.
1125 if (CXXConstructorDecl *Constructor
1126 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1127 QualType FromCanon
1128 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1129 QualType ToCanon
1130 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1131 if (Constructor->isCopyConstructor() &&
1132 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1133 // Turn this into a "standard" conversion sequence, so that it
1134 // gets ranked with standard conversion sequences.
1135 ICS.setStandard();
1136 ICS.Standard.setAsIdentityConversion();
1137 ICS.Standard.setFromType(From->getType());
1138 ICS.Standard.setAllToTypes(ToType);
1139 ICS.Standard.CopyConstructor = Constructor;
1140 if (ToCanon != FromCanon)
1141 ICS.Standard.Second = ICK_Derived_To_Base;
1142 }
1143 }
1144
1145 // C++ [over.best.ics]p4:
1146 // However, when considering the argument of a user-defined
1147 // conversion function that is a candidate by 13.3.1.3 when
1148 // invoked for the copying of the temporary in the second step
1149 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1150 // 13.3.1.6 in all cases, only standard conversion sequences and
1151 // ellipsis conversion sequences are allowed.
1152 if (SuppressUserConversions && ICS.isUserDefined()) {
1153 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1154 }
1155 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1156 ICS.setAmbiguous();
1157 ICS.Ambiguous.setFromType(From->getType());
1158 ICS.Ambiguous.setToType(ToType);
1159 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1160 Cand != Conversions.end(); ++Cand)
1161 if (Cand->Viable)
1162 ICS.Ambiguous.addConversion(Cand->Function);
1163 } else {
1164 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1165 }
1166
1167 return ICS;
1168}
1169
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001170/// TryImplicitConversion - Attempt to perform an implicit conversion
1171/// from the given expression (Expr) to the given type (ToType). This
1172/// function returns an implicit conversion sequence that can be used
1173/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001174///
1175/// void f(float f);
1176/// void g(int i) { f(i); }
1177///
1178/// this routine would produce an implicit conversion sequence to
1179/// describe the initialization of f from i, which will be a standard
1180/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1181/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1182//
1183/// Note that this routine only determines how the conversion can be
1184/// performed; it does not actually perform the conversion. As such,
1185/// it will not produce any diagnostics if no conversion is available,
1186/// but will instead return an implicit conversion sequence of kind
1187/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001188///
1189/// If @p SuppressUserConversions, then user-defined conversions are
1190/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001191/// If @p AllowExplicit, then explicit user-defined conversions are
1192/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001193///
1194/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1195/// writeback conversion, which allows __autoreleasing id* parameters to
1196/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001197static ImplicitConversionSequence
1198TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1199 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001200 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001201 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001202 bool CStyle,
1203 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001204 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001205 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001206 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001207 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001208 return ICS;
1209 }
1210
David Blaikie4e4d0842012-03-11 07:00:24 +00001211 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001212 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001213 return ICS;
1214 }
1215
Douglas Gregor604eb652010-08-11 02:15:33 +00001216 // C++ [over.ics.user]p4:
1217 // A conversion of an expression of class type to the same class
1218 // type is given Exact Match rank, and a conversion of an
1219 // expression of class type to a base class of that type is
1220 // given Conversion rank, in spite of the fact that a copy/move
1221 // constructor (i.e., a user-defined conversion function) is
1222 // called for those cases.
1223 QualType FromType = From->getType();
1224 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001225 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1226 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001227 ICS.setStandard();
1228 ICS.Standard.setAsIdentityConversion();
1229 ICS.Standard.setFromType(FromType);
1230 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001231
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001232 // We don't actually check at this point whether there is a valid
1233 // copy/move constructor, since overloading just assumes that it
1234 // exists. When we actually perform initialization, we'll find the
1235 // appropriate constructor to copy the returned object, if needed.
1236 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001237
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001238 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001239 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001240 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001241
Douglas Gregor604eb652010-08-11 02:15:33 +00001242 return ICS;
1243 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001245 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1246 AllowExplicit, InOverloadResolution, CStyle,
1247 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001248}
1249
John McCallf85e1932011-06-15 23:02:42 +00001250ImplicitConversionSequence
1251Sema::TryImplicitConversion(Expr *From, QualType ToType,
1252 bool SuppressUserConversions,
1253 bool AllowExplicit,
1254 bool InOverloadResolution,
1255 bool CStyle,
1256 bool AllowObjCWritebackConversion) {
1257 return clang::TryImplicitConversion(*this, From, ToType,
1258 SuppressUserConversions, AllowExplicit,
1259 InOverloadResolution, CStyle,
1260 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001261}
1262
Douglas Gregor575c63a2010-04-16 22:27:05 +00001263/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001264/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001265/// converted expression. Flavor is the kind of conversion we're
1266/// performing, used in the error message. If @p AllowExplicit,
1267/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001268ExprResult
1269Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001270 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001271 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001272 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001273}
1274
John Wiegley429bb272011-04-08 18:41:53 +00001275ExprResult
1276Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001277 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001278 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001279 if (checkPlaceholderForOverload(*this, From))
1280 return ExprError();
1281
John McCallf85e1932011-06-15 23:02:42 +00001282 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1283 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001284 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001285 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001286
John McCall120d63c2010-08-24 20:38:10 +00001287 ICS = clang::TryImplicitConversion(*this, From, ToType,
1288 /*SuppressUserConversions=*/false,
1289 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001290 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001291 /*CStyle=*/false,
1292 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001293 return PerformImplicitConversion(From, ToType, ICS, Action);
1294}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001295
1296/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001297/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001298bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1299 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001300 if (Context.hasSameUnqualifiedType(FromType, ToType))
1301 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001302
John McCall00ccbef2010-12-21 00:44:39 +00001303 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1304 // where F adds one of the following at most once:
1305 // - a pointer
1306 // - a member pointer
1307 // - a block pointer
1308 CanQualType CanTo = Context.getCanonicalType(ToType);
1309 CanQualType CanFrom = Context.getCanonicalType(FromType);
1310 Type::TypeClass TyClass = CanTo->getTypeClass();
1311 if (TyClass != CanFrom->getTypeClass()) return false;
1312 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1313 if (TyClass == Type::Pointer) {
1314 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1315 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1316 } else if (TyClass == Type::BlockPointer) {
1317 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1318 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1319 } else if (TyClass == Type::MemberPointer) {
1320 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1321 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1322 } else {
1323 return false;
1324 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001325
John McCall00ccbef2010-12-21 00:44:39 +00001326 TyClass = CanTo->getTypeClass();
1327 if (TyClass != CanFrom->getTypeClass()) return false;
1328 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1329 return false;
1330 }
1331
1332 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1333 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1334 if (!EInfo.getNoReturn()) return false;
1335
1336 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1337 assert(QualType(FromFn, 0).isCanonical());
1338 if (QualType(FromFn, 0) != CanTo) return false;
1339
1340 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001341 return true;
1342}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001343
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001344/// \brief Determine whether the conversion from FromType to ToType is a valid
1345/// vector conversion.
1346///
1347/// \param ICK Will be set to the vector conversion kind, if this is a vector
1348/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001349static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1350 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001351 // We need at least one of these types to be a vector type to have a vector
1352 // conversion.
1353 if (!ToType->isVectorType() && !FromType->isVectorType())
1354 return false;
1355
1356 // Identical types require no conversions.
1357 if (Context.hasSameUnqualifiedType(FromType, ToType))
1358 return false;
1359
1360 // There are no conversions between extended vector types, only identity.
1361 if (ToType->isExtVectorType()) {
1362 // There are no conversions between extended vector types other than the
1363 // identity conversion.
1364 if (FromType->isExtVectorType())
1365 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001366
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001367 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001368 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001369 ICK = ICK_Vector_Splat;
1370 return true;
1371 }
1372 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001373
1374 // We can perform the conversion between vector types in the following cases:
1375 // 1)vector types are equivalent AltiVec and GCC vector types
1376 // 2)lax vector conversions are permitted and the vector types are of the
1377 // same size
1378 if (ToType->isVectorType() && FromType->isVectorType()) {
1379 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001380 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001381 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001382 ICK = ICK_Vector_Conversion;
1383 return true;
1384 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001385 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001386
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001387 return false;
1388}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001389
Douglas Gregor7d000652012-04-12 20:48:09 +00001390static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1391 bool InOverloadResolution,
1392 StandardConversionSequence &SCS,
1393 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001394
Douglas Gregor60d62c22008-10-31 16:23:19 +00001395/// IsStandardConversion - Determines whether there is a standard
1396/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1397/// expression From to the type ToType. Standard conversion sequences
1398/// only consider non-class types; for conversions that involve class
1399/// types, use TryImplicitConversion. If a conversion exists, SCS will
1400/// contain the standard conversion sequence required to perform this
1401/// conversion and this routine will return true. Otherwise, this
1402/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001403static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1404 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001405 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001406 bool CStyle,
1407 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001408 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001409
Douglas Gregor60d62c22008-10-31 16:23:19 +00001410 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001411 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001412 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001413 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001414 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001415 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001416
Douglas Gregorf9201e02009-02-11 23:02:49 +00001417 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001418 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001419 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001420 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001421 return false;
1422
Mike Stump1eb44332009-09-09 15:08:12 +00001423 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001424 }
1425
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001426 // The first conversion can be an lvalue-to-rvalue conversion,
1427 // array-to-pointer conversion, or function-to-pointer conversion
1428 // (C++ 4p1).
1429
John McCall120d63c2010-08-24 20:38:10 +00001430 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001431 DeclAccessPair AccessPair;
1432 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001433 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001434 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001435 // We were able to resolve the address of the overloaded function,
1436 // so we can convert to the type of that function.
1437 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001438
1439 // we can sometimes resolve &foo<int> regardless of ToType, so check
1440 // if the type matches (identity) or we are converting to bool
1441 if (!S.Context.hasSameUnqualifiedType(
1442 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1443 QualType resultTy;
1444 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001445 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001446 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1447 // otherwise, only a boolean conversion is standard
1448 if (!ToType->isBooleanType())
1449 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001450 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001451
Chandler Carruth90434232011-03-29 08:08:18 +00001452 // Check if the "from" expression is taking the address of an overloaded
1453 // function and recompute the FromType accordingly. Take advantage of the
1454 // fact that non-static member functions *must* have such an address-of
1455 // expression.
1456 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1457 if (Method && !Method->isStatic()) {
1458 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1459 "Non-unary operator on non-static member address");
1460 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1461 == UO_AddrOf &&
1462 "Non-address-of operator on non-static member address");
1463 const Type *ClassType
1464 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1465 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001466 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1467 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1468 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001469 "Non-address-of operator for overloaded function expression");
1470 FromType = S.Context.getPointerType(FromType);
1471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001472
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001473 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001474 assert(S.Context.hasSameType(
1475 FromType,
1476 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001477 } else {
1478 return false;
1479 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001480 }
John McCall21480112011-08-30 00:57:29 +00001481 // Lvalue-to-rvalue conversion (C++11 4.1):
1482 // A glvalue (3.10) of a non-function, non-array type T can
1483 // be converted to a prvalue.
1484 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001485 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001486 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001487 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001488 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001489
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001490 // C11 6.3.2.1p2:
1491 // ... if the lvalue has atomic type, the value has the non-atomic version
1492 // of the type of the lvalue ...
1493 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1494 FromType = Atomic->getValueType();
1495
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001496 // If T is a non-class type, the type of the rvalue is the
1497 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001498 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1499 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001501 } else if (FromType->isArrayType()) {
1502 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001503 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001504
1505 // An lvalue or rvalue of type "array of N T" or "array of unknown
1506 // bound of T" can be converted to an rvalue of type "pointer to
1507 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001508 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001509
John McCall120d63c2010-08-24 20:38:10 +00001510 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001511 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001512 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001513
1514 // For the purpose of ranking in overload resolution
1515 // (13.3.3.1.1), this conversion is considered an
1516 // array-to-pointer conversion followed by a qualification
1517 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001518 SCS.Second = ICK_Identity;
1519 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001520 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001521 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001522 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001523 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001524 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001525 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001526 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001527
1528 // An lvalue of function type T can be converted to an rvalue of
1529 // type "pointer to T." The result is a pointer to the
1530 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001531 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001532 } else {
1533 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001534 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001535 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001536 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001537
1538 // The second conversion can be an integral promotion, floating
1539 // point promotion, integral conversion, floating point conversion,
1540 // floating-integral conversion, pointer conversion,
1541 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001542 // For overloading in C, this can also be a "compatible-type"
1543 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001544 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001545 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001546 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001547 // The unqualified versions of the types are the same: there's no
1548 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001549 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001550 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001551 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001552 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001554 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001555 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001556 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001557 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001558 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001559 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001560 SCS.Second = ICK_Complex_Promotion;
1561 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001562 } else if (ToType->isBooleanType() &&
1563 (FromType->isArithmeticType() ||
1564 FromType->isAnyPointerType() ||
1565 FromType->isBlockPointerType() ||
1566 FromType->isMemberPointerType() ||
1567 FromType->isNullPtrType())) {
1568 // Boolean conversions (C++ 4.12).
1569 SCS.Second = ICK_Boolean_Conversion;
1570 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001571 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001572 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001573 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001574 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001575 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001576 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001577 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001578 SCS.Second = ICK_Complex_Conversion;
1579 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001580 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1581 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001582 // Complex-real conversions (C99 6.3.1.7)
1583 SCS.Second = ICK_Complex_Real;
1584 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001585 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001586 // Floating point conversions (C++ 4.8).
1587 SCS.Second = ICK_Floating_Conversion;
1588 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001589 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001590 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001591 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001592 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001593 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001594 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001595 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001596 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001597 SCS.Second = ICK_Block_Pointer_Conversion;
1598 } else if (AllowObjCWritebackConversion &&
1599 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1600 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001601 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1602 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001603 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001604 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001605 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001606 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001607 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001608 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001609 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001610 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001611 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001612 SCS.Second = SecondICK;
1613 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001614 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001615 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001616 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001617 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001618 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001619 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001620 // Treat a conversion that strips "noreturn" as an identity conversion.
1621 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001622 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1623 InOverloadResolution,
1624 SCS, CStyle)) {
1625 SCS.Second = ICK_TransparentUnionConversion;
1626 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001627 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1628 CStyle)) {
1629 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001630 // appropriately.
1631 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001632 } else {
1633 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001634 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001635 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001636 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001637
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001638 QualType CanonFrom;
1639 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001640 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001641 bool ObjCLifetimeConversion;
1642 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1643 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001644 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001645 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001646 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001647 CanonFrom = S.Context.getCanonicalType(FromType);
1648 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001649 } else {
1650 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001651 SCS.Third = ICK_Identity;
1652
Mike Stump1eb44332009-09-09 15:08:12 +00001653 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001654 // [...] Any difference in top-level cv-qualification is
1655 // subsumed by the initialization itself and does not constitute
1656 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001657 CanonFrom = S.Context.getCanonicalType(FromType);
1658 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001659 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001660 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001661 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001662 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1663 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001664 FromType = ToType;
1665 CanonFrom = CanonTo;
1666 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001668 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001669
1670 // If we have not converted the argument type to the parameter type,
1671 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001672 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001673 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001674
Douglas Gregor60d62c22008-10-31 16:23:19 +00001675 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001677
1678static bool
1679IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1680 QualType &ToType,
1681 bool InOverloadResolution,
1682 StandardConversionSequence &SCS,
1683 bool CStyle) {
1684
1685 const RecordType *UT = ToType->getAsUnionType();
1686 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1687 return false;
1688 // The field to initialize within the transparent union.
1689 RecordDecl *UD = UT->getDecl();
1690 // It's compatible if the expression matches any of the fields.
1691 for (RecordDecl::field_iterator it = UD->field_begin(),
1692 itend = UD->field_end();
1693 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001694 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1695 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001696 ToType = it->getType();
1697 return true;
1698 }
1699 }
1700 return false;
1701}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001702
1703/// IsIntegralPromotion - Determines whether the conversion from the
1704/// expression From (whose potentially-adjusted type is FromType) to
1705/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1706/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001707bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001708 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001709 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001710 if (!To) {
1711 return false;
1712 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001713
1714 // An rvalue of type char, signed char, unsigned char, short int, or
1715 // unsigned short int can be converted to an rvalue of type int if
1716 // int can represent all the values of the source type; otherwise,
1717 // the source rvalue can be converted to an rvalue of type unsigned
1718 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001719 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1720 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001721 if (// We can promote any signed, promotable integer type to an int
1722 (FromType->isSignedIntegerType() ||
1723 // We can promote any unsigned integer type whose size is
1724 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001725 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001726 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001727 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001728 }
1729
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001730 return To->getKind() == BuiltinType::UInt;
1731 }
1732
Richard Smithe7ff9192012-09-13 21:18:54 +00001733 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001734 // A prvalue of an unscoped enumeration type whose underlying type is not
1735 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1736 // following types that can represent all the values of the enumeration
1737 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1738 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001739 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001740 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001741 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001742 // with lowest integer conversion rank (4.13) greater than the rank of long
1743 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001744 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001745 // C++11 [conv.prom]p4:
1746 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1747 // can be converted to a prvalue of its underlying type. Moreover, if
1748 // integral promotion can be applied to its underlying type, a prvalue of an
1749 // unscoped enumeration type whose underlying type is fixed can also be
1750 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001751 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1752 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1753 // provided for a scoped enumeration.
1754 if (FromEnumType->getDecl()->isScoped())
1755 return false;
1756
Richard Smithe7ff9192012-09-13 21:18:54 +00001757 // We can perform an integral promotion to the underlying type of the enum,
1758 // even if that's not the promoted type.
1759 if (FromEnumType->getDecl()->isFixed()) {
1760 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1761 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1762 IsIntegralPromotion(From, Underlying, ToType);
1763 }
1764
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001765 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001766 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001767 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001768 return Context.hasSameUnqualifiedType(ToType,
1769 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001770 }
John McCall842aef82009-12-09 09:09:27 +00001771
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001772 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001773 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1774 // to an rvalue a prvalue of the first of the following types that can
1775 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001776 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001777 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001778 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001779 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001780 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001781 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001782 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001783 // Determine whether the type we're converting from is signed or
1784 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001785 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001786 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001787
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001788 // The types we'll try to promote to, in the appropriate
1789 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001790 QualType PromoteTypes[6] = {
1791 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001792 Context.LongTy, Context.UnsignedLongTy ,
1793 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001794 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001795 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001796 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1797 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001798 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001799 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1800 // We found the type that we can promote to. If this is the
1801 // type we wanted, we have a promotion. Otherwise, no
1802 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001803 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001804 }
1805 }
1806 }
1807
1808 // An rvalue for an integral bit-field (9.6) can be converted to an
1809 // rvalue of type int if int can represent all the values of the
1810 // bit-field; otherwise, it can be converted to unsigned int if
1811 // unsigned int can represent all the values of the bit-field. If
1812 // the bit-field is larger yet, no integral promotion applies to
1813 // it. If the bit-field has an enumerated type, it is treated as any
1814 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001815 // FIXME: We should delay checking of bit-fields until we actually perform the
1816 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001817 using llvm::APSInt;
1818 if (From)
1819 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001820 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001821 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001822 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1823 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1824 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001825
Douglas Gregor86f19402008-12-20 23:49:58 +00001826 // Are we promoting to an int from a bitfield that fits in an int?
1827 if (BitWidth < ToSize ||
1828 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1829 return To->getKind() == BuiltinType::Int;
1830 }
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Douglas Gregor86f19402008-12-20 23:49:58 +00001832 // Are we promoting to an unsigned int from an unsigned bitfield
1833 // that fits into an unsigned int?
1834 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1835 return To->getKind() == BuiltinType::UInt;
1836 }
Mike Stump1eb44332009-09-09 15:08:12 +00001837
Douglas Gregor86f19402008-12-20 23:49:58 +00001838 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001839 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001840 }
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001842 // An rvalue of type bool can be converted to an rvalue of type int,
1843 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001844 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001845 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001846 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001847
1848 return false;
1849}
1850
1851/// IsFloatingPointPromotion - Determines whether the conversion from
1852/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1853/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001854bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001855 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1856 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001857 /// An rvalue of type float can be converted to an rvalue of type
1858 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001859 if (FromBuiltin->getKind() == BuiltinType::Float &&
1860 ToBuiltin->getKind() == BuiltinType::Double)
1861 return true;
1862
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001863 // C99 6.3.1.5p1:
1864 // When a float is promoted to double or long double, or a
1865 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001866 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001867 (FromBuiltin->getKind() == BuiltinType::Float ||
1868 FromBuiltin->getKind() == BuiltinType::Double) &&
1869 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1870 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001871
1872 // Half can be promoted to float.
Joey Gouly19dbb202013-01-23 11:56:20 +00001873 if (!getLangOpts().NativeHalfType &&
1874 FromBuiltin->getKind() == BuiltinType::Half &&
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001875 ToBuiltin->getKind() == BuiltinType::Float)
1876 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001877 }
1878
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001879 return false;
1880}
1881
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001882/// \brief Determine if a conversion is a complex promotion.
1883///
1884/// A complex promotion is defined as a complex -> complex conversion
1885/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001886/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001887bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001888 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001889 if (!FromComplex)
1890 return false;
1891
John McCall183700f2009-09-21 23:43:11 +00001892 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001893 if (!ToComplex)
1894 return false;
1895
1896 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001897 ToComplex->getElementType()) ||
1898 IsIntegralPromotion(0, FromComplex->getElementType(),
1899 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001900}
1901
Douglas Gregorcb7de522008-11-26 23:31:11 +00001902/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1903/// the pointer type FromPtr to a pointer to type ToPointee, with the
1904/// same type qualifiers as FromPtr has on its pointee type. ToType,
1905/// if non-empty, will be a pointer to ToType that may or may not have
1906/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001907///
Mike Stump1eb44332009-09-09 15:08:12 +00001908static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001909BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001910 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001911 ASTContext &Context,
1912 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001913 assert((FromPtr->getTypeClass() == Type::Pointer ||
1914 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1915 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001916
John McCallf85e1932011-06-15 23:02:42 +00001917 /// Conversions to 'id' subsume cv-qualifier conversions.
1918 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001919 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001920
1921 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001922 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001923 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001924 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001925
John McCallf85e1932011-06-15 23:02:42 +00001926 if (StripObjCLifetime)
1927 Quals.removeObjCLifetime();
1928
Mike Stump1eb44332009-09-09 15:08:12 +00001929 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001930 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001931 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001932 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001933 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001934
1935 // Build a pointer to ToPointee. It has the right qualifiers
1936 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001937 if (isa<ObjCObjectPointerType>(ToType))
1938 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001939 return Context.getPointerType(ToPointee);
1940 }
1941
1942 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001943 QualType QualifiedCanonToPointee
1944 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001945
Douglas Gregorda80f742010-12-01 21:43:58 +00001946 if (isa<ObjCObjectPointerType>(ToType))
1947 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1948 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001949}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001950
Mike Stump1eb44332009-09-09 15:08:12 +00001951static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001952 bool InOverloadResolution,
1953 ASTContext &Context) {
1954 // Handle value-dependent integral null pointer constants correctly.
1955 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1956 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001957 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001958 return !InOverloadResolution;
1959
Douglas Gregorce940492009-09-25 04:25:58 +00001960 return Expr->isNullPointerConstant(Context,
1961 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1962 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001963}
Mike Stump1eb44332009-09-09 15:08:12 +00001964
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001965/// IsPointerConversion - Determines whether the conversion of the
1966/// expression From, which has the (possibly adjusted) type FromType,
1967/// can be converted to the type ToType via a pointer conversion (C++
1968/// 4.10). If so, returns true and places the converted type (that
1969/// might differ from ToType in its cv-qualifiers at some level) into
1970/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001971///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001972/// This routine also supports conversions to and from block pointers
1973/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1974/// pointers to interfaces. FIXME: Once we've determined the
1975/// appropriate overloading rules for Objective-C, we may want to
1976/// split the Objective-C checks into a different routine; however,
1977/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001978/// conversions, so for now they live here. IncompatibleObjC will be
1979/// set if the conversion is an allowed Objective-C conversion that
1980/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001981bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001982 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001983 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001984 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001985 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001986 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1987 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001988 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001989
Mike Stump1eb44332009-09-09 15:08:12 +00001990 // Conversion from a null pointer constant to any Objective-C pointer type.
1991 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001992 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001993 ConvertedType = ToType;
1994 return true;
1995 }
1996
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001997 // Blocks: Block pointers can be converted to void*.
1998 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001999 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002000 ConvertedType = ToType;
2001 return true;
2002 }
2003 // Blocks: A null pointer constant can be converted to a block
2004 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00002005 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002006 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00002007 ConvertedType = ToType;
2008 return true;
2009 }
2010
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002011 // If the left-hand-side is nullptr_t, the right side can be a null
2012 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00002013 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002014 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00002015 ConvertedType = ToType;
2016 return true;
2017 }
2018
Ted Kremenek6217b802009-07-29 21:53:49 +00002019 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002020 if (!ToTypePtr)
2021 return false;
2022
2023 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00002024 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002025 ConvertedType = ToType;
2026 return true;
2027 }
Sebastian Redl07779722008-10-31 14:43:28 +00002028
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002029 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002030 // , including objective-c pointers.
2031 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00002032 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00002033 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002034 ConvertedType = BuildSimilarlyQualifiedPointerType(
2035 FromType->getAs<ObjCObjectPointerType>(),
2036 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002037 ToType, Context);
2038 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00002039 }
Ted Kremenek6217b802009-07-29 21:53:49 +00002040 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002041 if (!FromTypePtr)
2042 return false;
2043
2044 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002045
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002046 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002047 // pointer conversion, so don't do all of the work below.
2048 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2049 return false;
2050
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002051 // An rvalue of type "pointer to cv T," where T is an object type,
2052 // can be converted to an rvalue of type "pointer to cv void" (C++
2053 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002054 if (FromPointeeType->isIncompleteOrObjectType() &&
2055 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002057 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002058 ToType, Context,
2059 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002060 return true;
2061 }
2062
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002063 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002064 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002065 ToPointeeType->isVoidType()) {
2066 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2067 ToPointeeType,
2068 ToType, Context);
2069 return true;
2070 }
2071
Douglas Gregorf9201e02009-02-11 23:02:49 +00002072 // When we're overloading in C, we allow a special kind of pointer
2073 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002074 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002075 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002076 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002077 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002078 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002079 return true;
2080 }
2081
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002082 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002083 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002084 // An rvalue of type "pointer to cv D," where D is a class type,
2085 // can be converted to an rvalue of type "pointer to cv B," where
2086 // B is a base class (clause 10) of D. If B is an inaccessible
2087 // (clause 11) or ambiguous (10.2) base class of D, a program that
2088 // necessitates this conversion is ill-formed. The result of the
2089 // conversion is a pointer to the base class sub-object of the
2090 // derived class object. The null pointer value is converted to
2091 // the null pointer value of the destination type.
2092 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002093 // Note that we do not check for ambiguity or inaccessibility
2094 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002095 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002096 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002097 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002098 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002099 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002100 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002101 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002102 ToType, Context);
2103 return true;
2104 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002105
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002106 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2107 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2108 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2109 ToPointeeType,
2110 ToType, Context);
2111 return true;
2112 }
2113
Douglas Gregorc7887512008-12-19 19:13:09 +00002114 return false;
2115}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002116
2117/// \brief Adopt the given qualifiers for the given type.
2118static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2119 Qualifiers TQs = T.getQualifiers();
2120
2121 // Check whether qualifiers already match.
2122 if (TQs == Qs)
2123 return T;
2124
2125 if (Qs.compatiblyIncludes(TQs))
2126 return Context.getQualifiedType(T, Qs);
2127
2128 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2129}
Douglas Gregorc7887512008-12-19 19:13:09 +00002130
2131/// isObjCPointerConversion - Determines whether this is an
2132/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2133/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002134bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002135 QualType& ConvertedType,
2136 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002137 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002138 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002139
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002140 // The set of qualifiers on the type we're converting from.
2141 Qualifiers FromQualifiers = FromType.getQualifiers();
2142
Steve Naroff14108da2009-07-10 23:34:53 +00002143 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002144 const ObjCObjectPointerType* ToObjCPtr =
2145 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002146 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002147 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002148
Steve Naroff14108da2009-07-10 23:34:53 +00002149 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002150 // If the pointee types are the same (ignoring qualifications),
2151 // then this is not a pointer conversion.
2152 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2153 FromObjCPtr->getPointeeType()))
2154 return false;
2155
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002156 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002157 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002158 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002159 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002160 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002161 return true;
2162 }
2163 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002164 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002165 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002166 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002167 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002168 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002169 return true;
2170 }
2171 // Objective C++: We're able to convert from a pointer to an
2172 // interface to a pointer to a different interface.
2173 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002174 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2175 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002176 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002177 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2178 FromObjCPtr->getPointeeType()))
2179 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002180 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002181 ToObjCPtr->getPointeeType(),
2182 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002183 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002184 return true;
2185 }
2186
2187 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2188 // Okay: this is some kind of implicit downcast of Objective-C
2189 // interfaces, which is permitted. However, we're going to
2190 // complain about it.
2191 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002192 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002193 ToObjCPtr->getPointeeType(),
2194 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002195 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002196 return true;
2197 }
Mike Stump1eb44332009-09-09 15:08:12 +00002198 }
Steve Naroff14108da2009-07-10 23:34:53 +00002199 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002200 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002201 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002202 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002203 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002204 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002205 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002206 // to a block pointer type.
2207 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002208 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002209 return true;
2210 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002211 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002212 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002213 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002214 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002215 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002216 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002217 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002218 return true;
2219 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002220 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002221 return false;
2222
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002223 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002224 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002225 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002226 else if (const BlockPointerType *FromBlockPtr =
2227 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002228 FromPointeeType = FromBlockPtr->getPointeeType();
2229 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002230 return false;
2231
Douglas Gregorc7887512008-12-19 19:13:09 +00002232 // If we have pointers to pointers, recursively check whether this
2233 // is an Objective-C conversion.
2234 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2235 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2236 IncompatibleObjC)) {
2237 // We always complain about this conversion.
2238 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002239 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002240 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002241 return true;
2242 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002243 // Allow conversion of pointee being objective-c pointer to another one;
2244 // as in I* to id.
2245 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2246 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2247 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2248 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002249
Douglas Gregorda80f742010-12-01 21:43:58 +00002250 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002251 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002252 return true;
2253 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002254
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002255 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002256 // differences in the argument and result types are in Objective-C
2257 // pointer conversions. If so, we permit the conversion (but
2258 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002259 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002260 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002261 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002262 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002263 if (FromFunctionType && ToFunctionType) {
2264 // If the function types are exactly the same, this isn't an
2265 // Objective-C pointer conversion.
2266 if (Context.getCanonicalType(FromPointeeType)
2267 == Context.getCanonicalType(ToPointeeType))
2268 return false;
2269
2270 // Perform the quick checks that will tell us whether these
2271 // function types are obviously different.
2272 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2273 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2274 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2275 return false;
2276
2277 bool HasObjCConversion = false;
2278 if (Context.getCanonicalType(FromFunctionType->getResultType())
2279 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2280 // Okay, the types match exactly. Nothing to do.
2281 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2282 ToFunctionType->getResultType(),
2283 ConvertedType, IncompatibleObjC)) {
2284 // Okay, we have an Objective-C pointer conversion.
2285 HasObjCConversion = true;
2286 } else {
2287 // Function types are too different. Abort.
2288 return false;
2289 }
Mike Stump1eb44332009-09-09 15:08:12 +00002290
Douglas Gregorc7887512008-12-19 19:13:09 +00002291 // Check argument types.
2292 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2293 ArgIdx != NumArgs; ++ArgIdx) {
2294 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2295 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2296 if (Context.getCanonicalType(FromArgType)
2297 == Context.getCanonicalType(ToArgType)) {
2298 // Okay, the types match exactly. Nothing to do.
2299 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2300 ConvertedType, IncompatibleObjC)) {
2301 // Okay, we have an Objective-C pointer conversion.
2302 HasObjCConversion = true;
2303 } else {
2304 // Argument types are too different. Abort.
2305 return false;
2306 }
2307 }
2308
2309 if (HasObjCConversion) {
2310 // We had an Objective-C conversion. Allow this pointer
2311 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002312 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002313 IncompatibleObjC = true;
2314 return true;
2315 }
2316 }
2317
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002318 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002319}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002320
John McCallf85e1932011-06-15 23:02:42 +00002321/// \brief Determine whether this is an Objective-C writeback conversion,
2322/// used for parameter passing when performing automatic reference counting.
2323///
2324/// \param FromType The type we're converting form.
2325///
2326/// \param ToType The type we're converting to.
2327///
2328/// \param ConvertedType The type that will be produced after applying
2329/// this conversion.
2330bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2331 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002332 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002333 Context.hasSameUnqualifiedType(FromType, ToType))
2334 return false;
2335
2336 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2337 QualType ToPointee;
2338 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2339 ToPointee = ToPointer->getPointeeType();
2340 else
2341 return false;
2342
2343 Qualifiers ToQuals = ToPointee.getQualifiers();
2344 if (!ToPointee->isObjCLifetimeType() ||
2345 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002346 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002347 return false;
2348
2349 // Argument must be a pointer to __strong to __weak.
2350 QualType FromPointee;
2351 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2352 FromPointee = FromPointer->getPointeeType();
2353 else
2354 return false;
2355
2356 Qualifiers FromQuals = FromPointee.getQualifiers();
2357 if (!FromPointee->isObjCLifetimeType() ||
2358 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2359 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2360 return false;
2361
2362 // Make sure that we have compatible qualifiers.
2363 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2364 if (!ToQuals.compatiblyIncludes(FromQuals))
2365 return false;
2366
2367 // Remove qualifiers from the pointee type we're converting from; they
2368 // aren't used in the compatibility check belong, and we'll be adding back
2369 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2370 FromPointee = FromPointee.getUnqualifiedType();
2371
2372 // The unqualified form of the pointee types must be compatible.
2373 ToPointee = ToPointee.getUnqualifiedType();
2374 bool IncompatibleObjC;
2375 if (Context.typesAreCompatible(FromPointee, ToPointee))
2376 FromPointee = ToPointee;
2377 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2378 IncompatibleObjC))
2379 return false;
2380
2381 /// \brief Construct the type we're converting to, which is a pointer to
2382 /// __autoreleasing pointee.
2383 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2384 ConvertedType = Context.getPointerType(FromPointee);
2385 return true;
2386}
2387
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002388bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2389 QualType& ConvertedType) {
2390 QualType ToPointeeType;
2391 if (const BlockPointerType *ToBlockPtr =
2392 ToType->getAs<BlockPointerType>())
2393 ToPointeeType = ToBlockPtr->getPointeeType();
2394 else
2395 return false;
2396
2397 QualType FromPointeeType;
2398 if (const BlockPointerType *FromBlockPtr =
2399 FromType->getAs<BlockPointerType>())
2400 FromPointeeType = FromBlockPtr->getPointeeType();
2401 else
2402 return false;
2403 // We have pointer to blocks, check whether the only
2404 // differences in the argument and result types are in Objective-C
2405 // pointer conversions. If so, we permit the conversion.
2406
2407 const FunctionProtoType *FromFunctionType
2408 = FromPointeeType->getAs<FunctionProtoType>();
2409 const FunctionProtoType *ToFunctionType
2410 = ToPointeeType->getAs<FunctionProtoType>();
2411
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002412 if (!FromFunctionType || !ToFunctionType)
2413 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002414
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002415 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002416 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002417
2418 // Perform the quick checks that will tell us whether these
2419 // function types are obviously different.
2420 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2421 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2422 return false;
2423
2424 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2425 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2426 if (FromEInfo != ToEInfo)
2427 return false;
2428
2429 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002430 if (Context.hasSameType(FromFunctionType->getResultType(),
2431 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002432 // Okay, the types match exactly. Nothing to do.
2433 } else {
2434 QualType RHS = FromFunctionType->getResultType();
2435 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002436 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002437 !RHS.hasQualifiers() && LHS.hasQualifiers())
2438 LHS = LHS.getUnqualifiedType();
2439
2440 if (Context.hasSameType(RHS,LHS)) {
2441 // OK exact match.
2442 } else if (isObjCPointerConversion(RHS, LHS,
2443 ConvertedType, IncompatibleObjC)) {
2444 if (IncompatibleObjC)
2445 return false;
2446 // Okay, we have an Objective-C pointer conversion.
2447 }
2448 else
2449 return false;
2450 }
2451
2452 // Check argument types.
2453 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2454 ArgIdx != NumArgs; ++ArgIdx) {
2455 IncompatibleObjC = false;
2456 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2457 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2458 if (Context.hasSameType(FromArgType, ToArgType)) {
2459 // Okay, the types match exactly. Nothing to do.
2460 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2461 ConvertedType, IncompatibleObjC)) {
2462 if (IncompatibleObjC)
2463 return false;
2464 // Okay, we have an Objective-C pointer conversion.
2465 } else
2466 // Argument types are too different. Abort.
2467 return false;
2468 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002469 if (LangOpts.ObjCAutoRefCount &&
2470 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2471 ToFunctionType))
2472 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002473
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002474 ConvertedType = ToType;
2475 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002476}
2477
Richard Trieu6efd4c52011-11-23 22:32:32 +00002478enum {
2479 ft_default,
2480 ft_different_class,
2481 ft_parameter_arity,
2482 ft_parameter_mismatch,
2483 ft_return_type,
2484 ft_qualifer_mismatch
2485};
2486
2487/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2488/// function types. Catches different number of parameter, mismatch in
2489/// parameter types, and different return types.
2490void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2491 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002492 // If either type is not valid, include no extra info.
2493 if (FromType.isNull() || ToType.isNull()) {
2494 PDiag << ft_default;
2495 return;
2496 }
2497
Richard Trieu6efd4c52011-11-23 22:32:32 +00002498 // Get the function type from the pointers.
2499 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2500 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2501 *ToMember = ToType->getAs<MemberPointerType>();
2502 if (FromMember->getClass() != ToMember->getClass()) {
2503 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2504 << QualType(FromMember->getClass(), 0);
2505 return;
2506 }
2507 FromType = FromMember->getPointeeType();
2508 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002509 }
2510
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002511 if (FromType->isPointerType())
2512 FromType = FromType->getPointeeType();
2513 if (ToType->isPointerType())
2514 ToType = ToType->getPointeeType();
2515
2516 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002517 FromType = FromType.getNonReferenceType();
2518 ToType = ToType.getNonReferenceType();
2519
Richard Trieu6efd4c52011-11-23 22:32:32 +00002520 // Don't print extra info for non-specialized template functions.
2521 if (FromType->isInstantiationDependentType() &&
2522 !FromType->getAs<TemplateSpecializationType>()) {
2523 PDiag << ft_default;
2524 return;
2525 }
2526
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002527 // No extra info for same types.
2528 if (Context.hasSameType(FromType, ToType)) {
2529 PDiag << ft_default;
2530 return;
2531 }
2532
Richard Trieu6efd4c52011-11-23 22:32:32 +00002533 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2534 *ToFunction = ToType->getAs<FunctionProtoType>();
2535
2536 // Both types need to be function types.
2537 if (!FromFunction || !ToFunction) {
2538 PDiag << ft_default;
2539 return;
2540 }
2541
2542 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2543 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2544 << FromFunction->getNumArgs();
2545 return;
2546 }
2547
2548 // Handle different parameter types.
2549 unsigned ArgPos;
2550 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2551 PDiag << ft_parameter_mismatch << ArgPos + 1
2552 << ToFunction->getArgType(ArgPos)
2553 << FromFunction->getArgType(ArgPos);
2554 return;
2555 }
2556
2557 // Handle different return type.
2558 if (!Context.hasSameType(FromFunction->getResultType(),
2559 ToFunction->getResultType())) {
2560 PDiag << ft_return_type << ToFunction->getResultType()
2561 << FromFunction->getResultType();
2562 return;
2563 }
2564
2565 unsigned FromQuals = FromFunction->getTypeQuals(),
2566 ToQuals = ToFunction->getTypeQuals();
2567 if (FromQuals != ToQuals) {
2568 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2569 return;
2570 }
2571
2572 // Unable to find a difference, so add no extra info.
2573 PDiag << ft_default;
2574}
2575
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002576/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002577/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002578/// they have same number of arguments. This routine assumes that Objective-C
2579/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002580/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002581/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002582bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002583 const FunctionProtoType *NewType,
2584 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002585 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002586 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2587 N = NewType->arg_type_begin(),
2588 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2589 if (!Context.hasSameType(*O, *N)) {
2590 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2591 return false;
2592 }
2593 }
2594 return true;
2595 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002596
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002597 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2598 N = NewType->arg_type_begin(),
2599 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2600 QualType ToType = (*O);
2601 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002602 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002603 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2604 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002605 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2606 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2607 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2608 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002609 continue;
2610 }
John McCallc12c5bb2010-05-15 11:32:37 +00002611 else if (const ObjCObjectPointerType *PTTo =
2612 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002613 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002614 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002615 if (Context.hasSameUnqualifiedType(
2616 PTTo->getObjectType()->getBaseType(),
2617 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002618 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002619 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002620 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002621 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002622 }
2623 }
2624 return true;
2625}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002626
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002627/// CheckPointerConversion - Check the pointer conversion from the
2628/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002629/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002630/// conversions for which IsPointerConversion has already returned
2631/// true. It returns true and produces a diagnostic if there was an
2632/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002633bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002634 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002635 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002636 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002637 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002638 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002639
John McCalldaa8e4e2010-11-15 09:13:47 +00002640 Kind = CK_BitCast;
2641
David Blaikie50800fc2012-08-08 17:33:31 +00002642 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2643 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2644 Expr::NPCK_ZeroExpression) {
2645 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2646 DiagRuntimeBehavior(From->getExprLoc(), From,
2647 PDiag(diag::warn_impcast_bool_to_null_pointer)
2648 << ToType << From->getSourceRange());
2649 else if (!isUnevaluatedContext())
2650 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2651 << ToType << From->getSourceRange();
2652 }
John McCall1d9b3b22011-09-09 05:25:32 +00002653 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2654 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002655 QualType FromPointeeType = FromPtrType->getPointeeType(),
2656 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002657
Douglas Gregor5fccd362010-03-03 23:55:11 +00002658 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2659 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002660 // We must have a derived-to-base conversion. Check an
2661 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002662 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2663 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002664 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002665 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002666 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002667
Anders Carlsson61faec12009-09-12 04:46:44 +00002668 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002669 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002670 }
2671 }
John McCall1d9b3b22011-09-09 05:25:32 +00002672 } else if (const ObjCObjectPointerType *ToPtrType =
2673 ToType->getAs<ObjCObjectPointerType>()) {
2674 if (const ObjCObjectPointerType *FromPtrType =
2675 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002676 // Objective-C++ conversions are always okay.
2677 // FIXME: We should have a different class of conversions for the
2678 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002679 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002680 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002681 } else if (FromType->isBlockPointerType()) {
2682 Kind = CK_BlockPointerToObjCPointerCast;
2683 } else {
2684 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002685 }
John McCall1d9b3b22011-09-09 05:25:32 +00002686 } else if (ToType->isBlockPointerType()) {
2687 if (!FromType->isBlockPointerType())
2688 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002689 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002690
2691 // We shouldn't fall into this case unless it's valid for other
2692 // reasons.
2693 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2694 Kind = CK_NullToPointer;
2695
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002696 return false;
2697}
2698
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002699/// IsMemberPointerConversion - Determines whether the conversion of the
2700/// expression From, which has the (possibly adjusted) type FromType, can be
2701/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2702/// If so, returns true and places the converted type (that might differ from
2703/// ToType in its cv-qualifiers at some level) into ConvertedType.
2704bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002705 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002706 bool InOverloadResolution,
2707 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002708 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002709 if (!ToTypePtr)
2710 return false;
2711
2712 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002713 if (From->isNullPointerConstant(Context,
2714 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2715 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002716 ConvertedType = ToType;
2717 return true;
2718 }
2719
2720 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002721 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002722 if (!FromTypePtr)
2723 return false;
2724
2725 // A pointer to member of B can be converted to a pointer to member of D,
2726 // where D is derived from B (C++ 4.11p2).
2727 QualType FromClass(FromTypePtr->getClass(), 0);
2728 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002729
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002730 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002731 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002732 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002733 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2734 ToClass.getTypePtr());
2735 return true;
2736 }
2737
2738 return false;
2739}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002740
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002741/// CheckMemberPointerConversion - Check the member pointer conversion from the
2742/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002743/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002744/// for which IsMemberPointerConversion has already returned true. It returns
2745/// true and produces a diagnostic if there was an error, or returns false
2746/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002747bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002748 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002749 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002750 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002751 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002752 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002753 if (!FromPtrType) {
2754 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002755 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002756 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002757 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002758 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002759 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002760 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002761
Ted Kremenek6217b802009-07-29 21:53:49 +00002762 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002763 assert(ToPtrType && "No member pointer cast has a target type "
2764 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002765
Sebastian Redl21593ac2009-01-28 18:33:18 +00002766 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2767 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002768
Sebastian Redl21593ac2009-01-28 18:33:18 +00002769 // FIXME: What about dependent types?
2770 assert(FromClass->isRecordType() && "Pointer into non-class.");
2771 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002772
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002773 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002774 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002775 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2776 assert(DerivationOkay &&
2777 "Should not have been called if derivation isn't OK.");
2778 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002779
Sebastian Redl21593ac2009-01-28 18:33:18 +00002780 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2781 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002782 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2783 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2784 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2785 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002786 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002787
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002788 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002789 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2790 << FromClass << ToClass << QualType(VBase, 0)
2791 << From->getSourceRange();
2792 return true;
2793 }
2794
John McCall6b2accb2010-02-10 09:31:12 +00002795 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002796 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2797 Paths.front(),
2798 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002799
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002800 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002801 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002802 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002803 return false;
2804}
2805
Douglas Gregor98cd5992008-10-21 23:43:52 +00002806/// IsQualificationConversion - Determines whether the conversion from
2807/// an rvalue of type FromType to ToType is a qualification conversion
2808/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002809///
2810/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2811/// when the qualification conversion involves a change in the Objective-C
2812/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002813bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002814Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002815 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002816 FromType = Context.getCanonicalType(FromType);
2817 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002818 ObjCLifetimeConversion = false;
2819
Douglas Gregor98cd5992008-10-21 23:43:52 +00002820 // If FromType and ToType are the same type, this is not a
2821 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002822 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002823 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002824
Douglas Gregor98cd5992008-10-21 23:43:52 +00002825 // (C++ 4.4p4):
2826 // A conversion can add cv-qualifiers at levels other than the first
2827 // in multi-level pointers, subject to the following rules: [...]
2828 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002829 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002830 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002831 // Within each iteration of the loop, we check the qualifiers to
2832 // determine if this still looks like a qualification
2833 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002834 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002835 // until there are no more pointers or pointers-to-members left to
2836 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002837 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002838
Douglas Gregor621c92a2011-04-25 18:40:17 +00002839 Qualifiers FromQuals = FromType.getQualifiers();
2840 Qualifiers ToQuals = ToType.getQualifiers();
2841
John McCallf85e1932011-06-15 23:02:42 +00002842 // Objective-C ARC:
2843 // Check Objective-C lifetime conversions.
2844 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2845 UnwrappedAnyPointer) {
2846 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2847 ObjCLifetimeConversion = true;
2848 FromQuals.removeObjCLifetime();
2849 ToQuals.removeObjCLifetime();
2850 } else {
2851 // Qualification conversions cannot cast between different
2852 // Objective-C lifetime qualifiers.
2853 return false;
2854 }
2855 }
2856
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002857 // Allow addition/removal of GC attributes but not changing GC attributes.
2858 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2859 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2860 FromQuals.removeObjCGCAttr();
2861 ToQuals.removeObjCGCAttr();
2862 }
2863
Douglas Gregor98cd5992008-10-21 23:43:52 +00002864 // -- for every j > 0, if const is in cv 1,j then const is in cv
2865 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002866 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002867 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002868
Douglas Gregor98cd5992008-10-21 23:43:52 +00002869 // -- if the cv 1,j and cv 2,j are different, then const is in
2870 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002871 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002872 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002873 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Douglas Gregor98cd5992008-10-21 23:43:52 +00002875 // Keep track of whether all prior cv-qualifiers in the "to" type
2876 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002877 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002878 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002879 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002880
2881 // We are left with FromType and ToType being the pointee types
2882 // after unwrapping the original FromType and ToType the same number
2883 // of types. If we unwrapped any pointers, and if FromType and
2884 // ToType have the same unqualified type (since we checked
2885 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002886 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002887}
2888
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002889/// \brief - Determine whether this is a conversion from a scalar type to an
2890/// atomic type.
2891///
2892/// If successful, updates \c SCS's second and third steps in the conversion
2893/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002894static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2895 bool InOverloadResolution,
2896 StandardConversionSequence &SCS,
2897 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002898 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2899 if (!ToAtomic)
2900 return false;
2901
2902 StandardConversionSequence InnerSCS;
2903 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2904 InOverloadResolution, InnerSCS,
2905 CStyle, /*AllowObjCWritebackConversion=*/false))
2906 return false;
2907
2908 SCS.Second = InnerSCS.Second;
2909 SCS.setToType(1, InnerSCS.getToType(1));
2910 SCS.Third = InnerSCS.Third;
2911 SCS.QualificationIncludesObjCLifetime
2912 = InnerSCS.QualificationIncludesObjCLifetime;
2913 SCS.setToType(2, InnerSCS.getToType(2));
2914 return true;
2915}
2916
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002917static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2918 CXXConstructorDecl *Constructor,
2919 QualType Type) {
2920 const FunctionProtoType *CtorType =
2921 Constructor->getType()->getAs<FunctionProtoType>();
2922 if (CtorType->getNumArgs() > 0) {
2923 QualType FirstArg = CtorType->getArgType(0);
2924 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2925 return true;
2926 }
2927 return false;
2928}
2929
Sebastian Redl56a04282012-02-11 23:51:08 +00002930static OverloadingResult
2931IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2932 CXXRecordDecl *To,
2933 UserDefinedConversionSequence &User,
2934 OverloadCandidateSet &CandidateSet,
2935 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002936 DeclContext::lookup_result R = S.LookupConstructors(To);
2937 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002938 Con != ConEnd; ++Con) {
2939 NamedDecl *D = *Con;
2940 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2941
2942 // Find the constructor (which may be a template).
2943 CXXConstructorDecl *Constructor = 0;
2944 FunctionTemplateDecl *ConstructorTmpl
2945 = dyn_cast<FunctionTemplateDecl>(D);
2946 if (ConstructorTmpl)
2947 Constructor
2948 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2949 else
2950 Constructor = cast<CXXConstructorDecl>(D);
2951
2952 bool Usable = !Constructor->isInvalidDecl() &&
2953 S.isInitListConstructor(Constructor) &&
2954 (AllowExplicit || !Constructor->isExplicit());
2955 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002956 // If the first argument is (a reference to) the target type,
2957 // suppress conversions.
2958 bool SuppressUserConversions =
2959 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002960 if (ConstructorTmpl)
2961 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2962 /*ExplicitArgs*/ 0,
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 else
2966 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002967 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002968 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002969 }
2970 }
2971
2972 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2973
2974 OverloadCandidateSet::iterator Best;
2975 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2976 case OR_Success: {
2977 // Record the standard conversion we used and the conversion function.
2978 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002979 QualType ThisType = Constructor->getThisType(S.Context);
2980 // Initializer lists don't have conversions as such.
2981 User.Before.setAsIdentityConversion();
2982 User.HadMultipleCandidates = HadMultipleCandidates;
2983 User.ConversionFunction = Constructor;
2984 User.FoundConversionFunction = Best->FoundDecl;
2985 User.After.setAsIdentityConversion();
2986 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2987 User.After.setAllToTypes(ToType);
2988 return OR_Success;
2989 }
2990
2991 case OR_No_Viable_Function:
2992 return OR_No_Viable_Function;
2993 case OR_Deleted:
2994 return OR_Deleted;
2995 case OR_Ambiguous:
2996 return OR_Ambiguous;
2997 }
2998
2999 llvm_unreachable("Invalid OverloadResult!");
3000}
3001
Douglas Gregor734d9862009-01-30 23:27:23 +00003002/// Determines whether there is a user-defined conversion sequence
3003/// (C++ [over.ics.user]) that converts expression From to the type
3004/// ToType. If such a conversion exists, User will contain the
3005/// user-defined conversion sequence that performs such a conversion
3006/// and this routine will return true. Otherwise, this routine returns
3007/// false and User is unspecified.
3008///
Douglas Gregor734d9862009-01-30 23:27:23 +00003009/// \param AllowExplicit true if the conversion should consider C++0x
3010/// "explicit" conversion functions as well as non-explicit conversion
3011/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00003012static OverloadingResult
3013IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00003014 UserDefinedConversionSequence &User,
3015 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00003016 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003017 // Whether we will only visit constructors.
3018 bool ConstructorsOnly = false;
3019
3020 // If the type we are conversion to is a class type, enumerate its
3021 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00003022 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003023 // C++ [over.match.ctor]p1:
3024 // When objects of class type are direct-initialized (8.5), or
3025 // copy-initialized from an expression of the same or a
3026 // derived class type (8.5), overload resolution selects the
3027 // constructor. [...] For copy-initialization, the candidate
3028 // functions are all the converting constructors (12.3.1) of
3029 // that class. The argument list is the expression-list within
3030 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00003031 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003032 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00003033 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003034 ConstructorsOnly = true;
3035
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00003036 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00003037 // RequireCompleteType may have returned true due to some invalid decl
3038 // during template instantiation, but ToType may be complete enough now
3039 // to try to recover.
3040 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00003041 // We're not going to find any constructors.
3042 } else if (CXXRecordDecl *ToRecordDecl
3043 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003044
3045 Expr **Args = &From;
3046 unsigned NumArgs = 1;
3047 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003048 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003049 // But first, see if there is an init-list-contructor that will work.
3050 OverloadingResult Result = IsInitializerListConstructorConversion(
3051 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3052 if (Result != OR_No_Viable_Function)
3053 return Result;
3054 // Never mind.
3055 CandidateSet.clear();
3056
3057 // If we're list-initializing, we pass the individual elements as
3058 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003059 Args = InitList->getInits();
3060 NumArgs = InitList->getNumInits();
3061 ListInitializing = true;
3062 }
3063
David Blaikie3bc93e32012-12-19 00:45:41 +00003064 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3065 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003066 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003067 NamedDecl *D = *Con;
3068 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3069
Douglas Gregordec06662009-08-21 18:42:58 +00003070 // Find the constructor (which may be a template).
3071 CXXConstructorDecl *Constructor = 0;
3072 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003073 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003074 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003075 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003076 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3077 else
John McCall9aa472c2010-03-19 07:35:19 +00003078 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003079
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003080 bool Usable = !Constructor->isInvalidDecl();
3081 if (ListInitializing)
3082 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3083 else
3084 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3085 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003086 bool SuppressUserConversions = !ConstructorsOnly;
3087 if (SuppressUserConversions && ListInitializing) {
3088 SuppressUserConversions = false;
3089 if (NumArgs == 1) {
3090 // If the first argument is (a reference to) the target type,
3091 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003092 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3093 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003094 }
3095 }
Douglas Gregordec06662009-08-21 18:42:58 +00003096 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003097 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3098 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003099 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003100 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003101 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003102 // Allow one user-defined conversion when user specifies a
3103 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003104 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003105 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003106 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003107 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003108 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003109 }
3110 }
3111
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003112 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003113 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003114 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003115 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003116 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003117 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003118 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003119 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3120 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003121 std::pair<CXXRecordDecl::conversion_iterator,
3122 CXXRecordDecl::conversion_iterator>
3123 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3124 for (CXXRecordDecl::conversion_iterator
3125 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003126 DeclAccessPair FoundDecl = I.getPair();
3127 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003128 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3129 if (isa<UsingShadowDecl>(D))
3130 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3131
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003132 CXXConversionDecl *Conv;
3133 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003134 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3135 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003136 else
John McCall32daa422010-03-31 01:36:47 +00003137 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003138
3139 if (AllowExplicit || !Conv->isExplicit()) {
3140 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003141 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3142 ActingContext, From, ToType,
3143 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003144 else
John McCall120d63c2010-08-24 20:38:10 +00003145 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3146 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003147 }
3148 }
3149 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003150 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003151
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003152 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3153
Douglas Gregor60d62c22008-10-31 16:23:19 +00003154 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003155 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003156 case OR_Success:
3157 // Record the standard conversion we used and the conversion function.
3158 if (CXXConstructorDecl *Constructor
3159 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3160 // C++ [over.ics.user]p1:
3161 // If the user-defined conversion is specified by a
3162 // constructor (12.3.1), the initial standard conversion
3163 // sequence converts the source type to the type required by
3164 // the argument of the constructor.
3165 //
3166 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003167 if (isa<InitListExpr>(From)) {
3168 // Initializer lists don't have conversions as such.
3169 User.Before.setAsIdentityConversion();
3170 } else {
3171 if (Best->Conversions[0].isEllipsis())
3172 User.EllipsisConversion = true;
3173 else {
3174 User.Before = Best->Conversions[0].Standard;
3175 User.EllipsisConversion = false;
3176 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003177 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003178 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003179 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003180 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003181 User.After.setAsIdentityConversion();
3182 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3183 User.After.setAllToTypes(ToType);
3184 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003185 }
3186 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003187 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3188 // C++ [over.ics.user]p1:
3189 //
3190 // [...] If the user-defined conversion is specified by a
3191 // conversion function (12.3.2), the initial standard
3192 // conversion sequence converts the source type to the
3193 // implicit object parameter of the conversion function.
3194 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003195 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003196 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003197 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003198 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003199
John McCall120d63c2010-08-24 20:38:10 +00003200 // C++ [over.ics.user]p2:
3201 // The second standard conversion sequence converts the
3202 // result of the user-defined conversion to the target type
3203 // for the sequence. Since an implicit conversion sequence
3204 // is an initialization, the special rules for
3205 // initialization by user-defined conversion apply when
3206 // selecting the best user-defined conversion for a
3207 // user-defined conversion sequence (see 13.3.3 and
3208 // 13.3.3.1).
3209 User.After = Best->FinalConversion;
3210 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003211 }
David Blaikie7530c032012-01-17 06:56:22 +00003212 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003213
John McCall120d63c2010-08-24 20:38:10 +00003214 case OR_No_Viable_Function:
3215 return OR_No_Viable_Function;
3216 case OR_Deleted:
3217 // No conversion here! We're done.
3218 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219
John McCall120d63c2010-08-24 20:38:10 +00003220 case OR_Ambiguous:
3221 return OR_Ambiguous;
3222 }
3223
David Blaikie7530c032012-01-17 06:56:22 +00003224 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003225}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003226
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003227bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003228Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003229 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003230 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003231 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003232 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003233 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003234 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003235 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003236 diag::err_typecheck_ambiguous_condition)
3237 << From->getType() << ToType << From->getSourceRange();
3238 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003239 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003240 diag::err_typecheck_nonviable_condition)
3241 << From->getType() << ToType << From->getSourceRange();
3242 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003243 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003244 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003245 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003246}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003247
Douglas Gregorb734e242012-02-22 17:32:19 +00003248/// \brief Compare the user-defined conversion functions or constructors
3249/// of two user-defined conversion sequences to determine whether any ordering
3250/// is possible.
3251static ImplicitConversionSequence::CompareKind
3252compareConversionFunctions(Sema &S,
3253 FunctionDecl *Function1,
3254 FunctionDecl *Function2) {
Richard Smith80ad52f2013-01-02 11:42:31 +00003255 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus11)
Douglas Gregorb734e242012-02-22 17:32:19 +00003256 return ImplicitConversionSequence::Indistinguishable;
3257
3258 // Objective-C++:
3259 // If both conversion functions are implicitly-declared conversions from
3260 // a lambda closure type to a function pointer and a block pointer,
3261 // respectively, always prefer the conversion to a function pointer,
3262 // because the function pointer is more lightweight and is more likely
3263 // to keep code working.
3264 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3265 if (!Conv1)
3266 return ImplicitConversionSequence::Indistinguishable;
3267
3268 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3269 if (!Conv2)
3270 return ImplicitConversionSequence::Indistinguishable;
3271
3272 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3273 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3274 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3275 if (Block1 != Block2)
3276 return Block1? ImplicitConversionSequence::Worse
3277 : ImplicitConversionSequence::Better;
3278 }
3279
3280 return ImplicitConversionSequence::Indistinguishable;
3281}
3282
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003283/// CompareImplicitConversionSequences - Compare two implicit
3284/// conversion sequences to determine whether one is better than the
3285/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003286static ImplicitConversionSequence::CompareKind
3287CompareImplicitConversionSequences(Sema &S,
3288 const ImplicitConversionSequence& ICS1,
3289 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003290{
3291 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3292 // conversion sequences (as defined in 13.3.3.1)
3293 // -- a standard conversion sequence (13.3.3.1.1) is a better
3294 // conversion sequence than a user-defined conversion sequence or
3295 // an ellipsis conversion sequence, and
3296 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3297 // conversion sequence than an ellipsis conversion sequence
3298 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003299 //
John McCall1d318332010-01-12 00:44:57 +00003300 // C++0x [over.best.ics]p10:
3301 // For the purpose of ranking implicit conversion sequences as
3302 // described in 13.3.3.2, the ambiguous conversion sequence is
3303 // treated as a user-defined sequence that is indistinguishable
3304 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003305 if (ICS1.getKindRank() < ICS2.getKindRank())
3306 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003307 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003308 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003309
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003310 // The following checks require both conversion sequences to be of
3311 // the same kind.
3312 if (ICS1.getKind() != ICS2.getKind())
3313 return ImplicitConversionSequence::Indistinguishable;
3314
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003315 ImplicitConversionSequence::CompareKind Result =
3316 ImplicitConversionSequence::Indistinguishable;
3317
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003318 // Two implicit conversion sequences of the same form are
3319 // indistinguishable conversion sequences unless one of the
3320 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003321 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003322 Result = CompareStandardConversionSequences(S,
3323 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003324 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003325 // User-defined conversion sequence U1 is a better conversion
3326 // sequence than another user-defined conversion sequence U2 if
3327 // they contain the same user-defined conversion function or
3328 // constructor and if the second standard conversion sequence of
3329 // U1 is better than the second standard conversion sequence of
3330 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003331 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003332 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003333 Result = CompareStandardConversionSequences(S,
3334 ICS1.UserDefined.After,
3335 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003336 else
3337 Result = compareConversionFunctions(S,
3338 ICS1.UserDefined.ConversionFunction,
3339 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003340 }
3341
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003342 // List-initialization sequence L1 is a better conversion sequence than
3343 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3344 // for some X and L2 does not.
3345 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003346 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003347 ICS1.isListInitializationSequence() &&
3348 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003349 if (ICS1.isStdInitializerListElement() &&
3350 !ICS2.isStdInitializerListElement())
3351 return ImplicitConversionSequence::Better;
3352 if (!ICS1.isStdInitializerListElement() &&
3353 ICS2.isStdInitializerListElement())
3354 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003355 }
3356
3357 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003358}
3359
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003360static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3361 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3362 Qualifiers Quals;
3363 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003365 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003366
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003367 return Context.hasSameUnqualifiedType(T1, T2);
3368}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369
Douglas Gregorad323a82010-01-27 03:51:04 +00003370// Per 13.3.3.2p3, compare the given standard conversion sequences to
3371// determine if one is a proper subset of the other.
3372static ImplicitConversionSequence::CompareKind
3373compareStandardConversionSubsets(ASTContext &Context,
3374 const StandardConversionSequence& SCS1,
3375 const StandardConversionSequence& SCS2) {
3376 ImplicitConversionSequence::CompareKind Result
3377 = ImplicitConversionSequence::Indistinguishable;
3378
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003380 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003381 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3382 return ImplicitConversionSequence::Better;
3383 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3384 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003385
Douglas Gregorad323a82010-01-27 03:51:04 +00003386 if (SCS1.Second != SCS2.Second) {
3387 if (SCS1.Second == ICK_Identity)
3388 Result = ImplicitConversionSequence::Better;
3389 else if (SCS2.Second == ICK_Identity)
3390 Result = ImplicitConversionSequence::Worse;
3391 else
3392 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003393 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003394 return ImplicitConversionSequence::Indistinguishable;
3395
3396 if (SCS1.Third == SCS2.Third) {
3397 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3398 : ImplicitConversionSequence::Indistinguishable;
3399 }
3400
3401 if (SCS1.Third == ICK_Identity)
3402 return Result == ImplicitConversionSequence::Worse
3403 ? ImplicitConversionSequence::Indistinguishable
3404 : ImplicitConversionSequence::Better;
3405
3406 if (SCS2.Third == ICK_Identity)
3407 return Result == ImplicitConversionSequence::Better
3408 ? ImplicitConversionSequence::Indistinguishable
3409 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003410
Douglas Gregorad323a82010-01-27 03:51:04 +00003411 return ImplicitConversionSequence::Indistinguishable;
3412}
3413
Douglas Gregor440a4832011-01-26 14:52:12 +00003414/// \brief Determine whether one of the given reference bindings is better
3415/// than the other based on what kind of bindings they are.
3416static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3417 const StandardConversionSequence &SCS2) {
3418 // C++0x [over.ics.rank]p3b4:
3419 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3420 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003421 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003422 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003423 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003424 // reference*.
3425 //
3426 // FIXME: Rvalue references. We're going rogue with the above edits,
3427 // because the semantics in the current C++0x working paper (N3225 at the
3428 // time of this writing) break the standard definition of std::forward
3429 // and std::reference_wrapper when dealing with references to functions.
3430 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003431 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3432 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3433 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003434
Douglas Gregor440a4832011-01-26 14:52:12 +00003435 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3436 SCS2.IsLvalueReference) ||
3437 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3438 !SCS2.IsLvalueReference);
3439}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003440
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003441/// CompareStandardConversionSequences - Compare two standard
3442/// conversion sequences to determine whether one is better than the
3443/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003444static ImplicitConversionSequence::CompareKind
3445CompareStandardConversionSequences(Sema &S,
3446 const StandardConversionSequence& SCS1,
3447 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003448{
3449 // Standard conversion sequence S1 is a better conversion sequence
3450 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3451
3452 // -- S1 is a proper subsequence of S2 (comparing the conversion
3453 // sequences in the canonical form defined by 13.3.3.1.1,
3454 // excluding any Lvalue Transformation; the identity conversion
3455 // sequence is considered to be a subsequence of any
3456 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003457 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003458 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003459 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003460
3461 // -- the rank of S1 is better than the rank of S2 (by the rules
3462 // defined below), or, if not that,
3463 ImplicitConversionRank Rank1 = SCS1.getRank();
3464 ImplicitConversionRank Rank2 = SCS2.getRank();
3465 if (Rank1 < Rank2)
3466 return ImplicitConversionSequence::Better;
3467 else if (Rank2 < Rank1)
3468 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003469
Douglas Gregor57373262008-10-22 14:17:15 +00003470 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3471 // are indistinguishable unless one of the following rules
3472 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003473
Douglas Gregor57373262008-10-22 14:17:15 +00003474 // A conversion that is not a conversion of a pointer, or
3475 // pointer to member, to bool is better than another conversion
3476 // that is such a conversion.
3477 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3478 return SCS2.isPointerConversionToBool()
3479 ? ImplicitConversionSequence::Better
3480 : ImplicitConversionSequence::Worse;
3481
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003482 // C++ [over.ics.rank]p4b2:
3483 //
3484 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003485 // conversion of B* to A* is better than conversion of B* to
3486 // void*, and conversion of A* to void* is better than conversion
3487 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003488 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003489 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003490 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003491 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003492 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3493 // Exactly one of the conversion sequences is a conversion to
3494 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003495 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3496 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003497 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3498 // Neither conversion sequence converts to a void pointer; compare
3499 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003500 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003501 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003502 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003503 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3504 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003505 // Both conversion sequences are conversions to void
3506 // pointers. Compare the source types to determine if there's an
3507 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003508 QualType FromType1 = SCS1.getFromType();
3509 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003510
3511 // Adjust the types we're converting from via the array-to-pointer
3512 // conversion, if we need to.
3513 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003514 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003515 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003516 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003517
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003518 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3519 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003520
John McCall120d63c2010-08-24 20:38:10 +00003521 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003522 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003523 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003524 return ImplicitConversionSequence::Worse;
3525
3526 // Objective-C++: If one interface is more specific than the
3527 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003528 const ObjCObjectPointerType* FromObjCPtr1
3529 = FromType1->getAs<ObjCObjectPointerType>();
3530 const ObjCObjectPointerType* FromObjCPtr2
3531 = FromType2->getAs<ObjCObjectPointerType>();
3532 if (FromObjCPtr1 && FromObjCPtr2) {
3533 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3534 FromObjCPtr2);
3535 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3536 FromObjCPtr1);
3537 if (AssignLeft != AssignRight) {
3538 return AssignLeft? ImplicitConversionSequence::Better
3539 : ImplicitConversionSequence::Worse;
3540 }
Douglas Gregor01919692009-12-13 21:37:05 +00003541 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003542 }
Douglas Gregor57373262008-10-22 14:17:15 +00003543
3544 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3545 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003546 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003547 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003548 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003549
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003550 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003551 // Check for a better reference binding based on the kind of bindings.
3552 if (isBetterReferenceBindingKind(SCS1, SCS2))
3553 return ImplicitConversionSequence::Better;
3554 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3555 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003556
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003557 // C++ [over.ics.rank]p3b4:
3558 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3559 // which the references refer are the same type except for
3560 // top-level cv-qualifiers, and the type to which the reference
3561 // initialized by S2 refers is more cv-qualified than the type
3562 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003563 QualType T1 = SCS1.getToType(2);
3564 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003565 T1 = S.Context.getCanonicalType(T1);
3566 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003567 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003568 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3569 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003570 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003571 // Objective-C++ ARC: If the references refer to objects with different
3572 // lifetimes, prefer bindings that don't change lifetime.
3573 if (SCS1.ObjCLifetimeConversionBinding !=
3574 SCS2.ObjCLifetimeConversionBinding) {
3575 return SCS1.ObjCLifetimeConversionBinding
3576 ? ImplicitConversionSequence::Worse
3577 : ImplicitConversionSequence::Better;
3578 }
3579
Chandler Carruth6df868e2010-12-12 08:17:55 +00003580 // If the type is an array type, promote the element qualifiers to the
3581 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003582 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003583 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003584 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003585 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003586 if (T2.isMoreQualifiedThan(T1))
3587 return ImplicitConversionSequence::Better;
3588 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003589 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003590 }
3591 }
Douglas Gregor57373262008-10-22 14:17:15 +00003592
Francois Pichet1c98d622011-09-18 21:37:37 +00003593 // In Microsoft mode, prefer an integral conversion to a
3594 // floating-to-integral conversion if the integral conversion
3595 // is between types of the same size.
3596 // For example:
3597 // void f(float);
3598 // void f(int);
3599 // int main {
3600 // long a;
3601 // f(a);
3602 // }
3603 // Here, MSVC will call f(int) instead of generating a compile error
3604 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003605 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003606 SCS1.Second == ICK_Integral_Conversion &&
3607 SCS2.Second == ICK_Floating_Integral &&
3608 S.Context.getTypeSize(SCS1.getFromType()) ==
3609 S.Context.getTypeSize(SCS1.getToType(2)))
3610 return ImplicitConversionSequence::Better;
3611
Douglas Gregor57373262008-10-22 14:17:15 +00003612 return ImplicitConversionSequence::Indistinguishable;
3613}
3614
3615/// CompareQualificationConversions - Compares two standard conversion
3616/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003617/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3618ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003619CompareQualificationConversions(Sema &S,
3620 const StandardConversionSequence& SCS1,
3621 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003622 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003623 // -- S1 and S2 differ only in their qualification conversion and
3624 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3625 // cv-qualification signature of type T1 is a proper subset of
3626 // the cv-qualification signature of type T2, and S1 is not the
3627 // deprecated string literal array-to-pointer conversion (4.2).
3628 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3629 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3630 return ImplicitConversionSequence::Indistinguishable;
3631
3632 // FIXME: the example in the standard doesn't use a qualification
3633 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003634 QualType T1 = SCS1.getToType(2);
3635 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003636 T1 = S.Context.getCanonicalType(T1);
3637 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003638 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003639 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3640 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003641
3642 // If the types are the same, we won't learn anything by unwrapped
3643 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003644 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003645 return ImplicitConversionSequence::Indistinguishable;
3646
Chandler Carruth28e318c2009-12-29 07:16:59 +00003647 // If the type is an array type, promote the element qualifiers to the type
3648 // for comparison.
3649 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003650 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003651 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003652 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003653
Mike Stump1eb44332009-09-09 15:08:12 +00003654 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003655 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003656
3657 // Objective-C++ ARC:
3658 // Prefer qualification conversions not involving a change in lifetime
3659 // to qualification conversions that do not change lifetime.
3660 if (SCS1.QualificationIncludesObjCLifetime !=
3661 SCS2.QualificationIncludesObjCLifetime) {
3662 Result = SCS1.QualificationIncludesObjCLifetime
3663 ? ImplicitConversionSequence::Worse
3664 : ImplicitConversionSequence::Better;
3665 }
3666
John McCall120d63c2010-08-24 20:38:10 +00003667 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003668 // Within each iteration of the loop, we check the qualifiers to
3669 // determine if this still looks like a qualification
3670 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003671 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003672 // until there are no more pointers or pointers-to-members left
3673 // to unwrap. This essentially mimics what
3674 // IsQualificationConversion does, but here we're checking for a
3675 // strict subset of qualifiers.
3676 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3677 // The qualifiers are the same, so this doesn't tell us anything
3678 // about how the sequences rank.
3679 ;
3680 else if (T2.isMoreQualifiedThan(T1)) {
3681 // T1 has fewer qualifiers, so it could be the better sequence.
3682 if (Result == ImplicitConversionSequence::Worse)
3683 // Neither has qualifiers that are a subset of the other's
3684 // qualifiers.
3685 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003686
Douglas Gregor57373262008-10-22 14:17:15 +00003687 Result = ImplicitConversionSequence::Better;
3688 } else if (T1.isMoreQualifiedThan(T2)) {
3689 // T2 has fewer qualifiers, so it could be the better sequence.
3690 if (Result == ImplicitConversionSequence::Better)
3691 // Neither has qualifiers that are a subset of the other's
3692 // qualifiers.
3693 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Douglas Gregor57373262008-10-22 14:17:15 +00003695 Result = ImplicitConversionSequence::Worse;
3696 } else {
3697 // Qualifiers are disjoint.
3698 return ImplicitConversionSequence::Indistinguishable;
3699 }
3700
3701 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003702 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003703 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003704 }
3705
Douglas Gregor57373262008-10-22 14:17:15 +00003706 // Check that the winning standard conversion sequence isn't using
3707 // the deprecated string literal array to pointer conversion.
3708 switch (Result) {
3709 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003710 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003711 Result = ImplicitConversionSequence::Indistinguishable;
3712 break;
3713
3714 case ImplicitConversionSequence::Indistinguishable:
3715 break;
3716
3717 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003718 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003719 Result = ImplicitConversionSequence::Indistinguishable;
3720 break;
3721 }
3722
3723 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003724}
3725
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726/// CompareDerivedToBaseConversions - Compares two standard conversion
3727/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003728/// various kinds of derived-to-base conversions (C++
3729/// [over.ics.rank]p4b3). As part of these checks, we also look at
3730/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003731ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003732CompareDerivedToBaseConversions(Sema &S,
3733 const StandardConversionSequence& SCS1,
3734 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003735 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003736 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003737 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003738 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003739
3740 // Adjust the types we're converting from via the array-to-pointer
3741 // conversion, if we need to.
3742 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003743 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003744 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003745 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003746
3747 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003748 FromType1 = S.Context.getCanonicalType(FromType1);
3749 ToType1 = S.Context.getCanonicalType(ToType1);
3750 FromType2 = S.Context.getCanonicalType(FromType2);
3751 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003752
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003753 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003754 //
3755 // If class B is derived directly or indirectly from class A and
3756 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003757 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003758 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003759 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003760 SCS2.Second == ICK_Pointer_Conversion &&
3761 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3762 FromType1->isPointerType() && FromType2->isPointerType() &&
3763 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003764 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003765 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003766 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003767 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003768 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003769 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003770 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003771 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003772
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003773 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003774 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003775 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003776 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003777 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003778 return ImplicitConversionSequence::Worse;
3779 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003780
3781 // -- conversion of B* to A* is better than conversion of C* to A*,
3782 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003783 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003784 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003785 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003786 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003787 }
3788 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3789 SCS2.Second == ICK_Pointer_Conversion) {
3790 const ObjCObjectPointerType *FromPtr1
3791 = FromType1->getAs<ObjCObjectPointerType>();
3792 const ObjCObjectPointerType *FromPtr2
3793 = FromType2->getAs<ObjCObjectPointerType>();
3794 const ObjCObjectPointerType *ToPtr1
3795 = ToType1->getAs<ObjCObjectPointerType>();
3796 const ObjCObjectPointerType *ToPtr2
3797 = ToType2->getAs<ObjCObjectPointerType>();
3798
3799 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3800 // Apply the same conversion ranking rules for Objective-C pointer types
3801 // that we do for C++ pointers to class types. However, we employ the
3802 // Objective-C pseudo-subtyping relationship used for assignment of
3803 // Objective-C pointer types.
3804 bool FromAssignLeft
3805 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3806 bool FromAssignRight
3807 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3808 bool ToAssignLeft
3809 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3810 bool ToAssignRight
3811 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3812
3813 // A conversion to an a non-id object pointer type or qualified 'id'
3814 // type is better than a conversion to 'id'.
3815 if (ToPtr1->isObjCIdType() &&
3816 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3817 return ImplicitConversionSequence::Worse;
3818 if (ToPtr2->isObjCIdType() &&
3819 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3820 return ImplicitConversionSequence::Better;
3821
3822 // A conversion to a non-id object pointer type is better than a
3823 // conversion to a qualified 'id' type
3824 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3825 return ImplicitConversionSequence::Worse;
3826 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3827 return ImplicitConversionSequence::Better;
3828
3829 // A conversion to an a non-Class object pointer type or qualified 'Class'
3830 // type is better than a conversion to 'Class'.
3831 if (ToPtr1->isObjCClassType() &&
3832 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3833 return ImplicitConversionSequence::Worse;
3834 if (ToPtr2->isObjCClassType() &&
3835 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3836 return ImplicitConversionSequence::Better;
3837
3838 // A conversion to a non-Class object pointer type is better than a
3839 // conversion to a qualified 'Class' type.
3840 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3841 return ImplicitConversionSequence::Worse;
3842 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3843 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Douglas Gregor395cc372011-01-31 18:51:41 +00003845 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3846 if (S.Context.hasSameType(FromType1, FromType2) &&
3847 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3848 (ToAssignLeft != ToAssignRight))
3849 return ToAssignLeft? ImplicitConversionSequence::Worse
3850 : ImplicitConversionSequence::Better;
3851
3852 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3853 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3854 (FromAssignLeft != FromAssignRight))
3855 return FromAssignLeft? ImplicitConversionSequence::Better
3856 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003857 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003858 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003859
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003860 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003861 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3862 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3863 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003864 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003865 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003866 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003867 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003868 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003869 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003870 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003871 ToType2->getAs<MemberPointerType>();
3872 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3873 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3874 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3875 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3876 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3877 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3878 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3879 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003880 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003881 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003882 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003883 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003884 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003885 return ImplicitConversionSequence::Better;
3886 }
3887 // conversion of B::* to C::* is better than conversion of A::* to C::*
3888 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003889 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003890 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003891 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003892 return ImplicitConversionSequence::Worse;
3893 }
3894 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003895
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003896 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003897 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003898 // -- binding of an expression of type C to a reference of type
3899 // B& is better than binding an expression of type C to a
3900 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003901 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3902 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3903 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003904 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003905 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003906 return ImplicitConversionSequence::Worse;
3907 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003908
Douglas Gregor225c41e2008-11-03 19:09:14 +00003909 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003910 // -- binding of an expression of type B to a reference of type
3911 // A& is better than binding an expression of type C to a
3912 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003913 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3914 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3915 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003916 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003917 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003918 return ImplicitConversionSequence::Worse;
3919 }
3920 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003921
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003922 return ImplicitConversionSequence::Indistinguishable;
3923}
3924
Douglas Gregorabe183d2010-04-13 16:31:36 +00003925/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3926/// determine whether they are reference-related,
3927/// reference-compatible, reference-compatible with added
3928/// qualification, or incompatible, for use in C++ initialization by
3929/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3930/// type, and the first type (T1) is the pointee type of the reference
3931/// type being initialized.
3932Sema::ReferenceCompareResult
3933Sema::CompareReferenceRelationship(SourceLocation Loc,
3934 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003935 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003936 bool &ObjCConversion,
3937 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003938 assert(!OrigT1->isReferenceType() &&
3939 "T1 must be the pointee type of the reference type");
3940 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3941
3942 QualType T1 = Context.getCanonicalType(OrigT1);
3943 QualType T2 = Context.getCanonicalType(OrigT2);
3944 Qualifiers T1Quals, T2Quals;
3945 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3946 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3947
3948 // C++ [dcl.init.ref]p4:
3949 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3950 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3951 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003952 DerivedToBase = false;
3953 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003954 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003955 if (UnqualT1 == UnqualT2) {
3956 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003957 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003958 IsDerivedFrom(UnqualT2, UnqualT1))
3959 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003960 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3961 UnqualT2->isObjCObjectOrInterfaceType() &&
3962 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3963 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003964 else
3965 return Ref_Incompatible;
3966
3967 // At this point, we know that T1 and T2 are reference-related (at
3968 // least).
3969
3970 // If the type is an array type, promote the element qualifiers to the type
3971 // for comparison.
3972 if (isa<ArrayType>(T1) && T1Quals)
3973 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3974 if (isa<ArrayType>(T2) && T2Quals)
3975 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3976
3977 // C++ [dcl.init.ref]p4:
3978 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3979 // reference-related to T2 and cv1 is the same cv-qualification
3980 // as, or greater cv-qualification than, cv2. For purposes of
3981 // overload resolution, cases for which cv1 is greater
3982 // cv-qualification than cv2 are identified as
3983 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003984 //
3985 // Note that we also require equivalence of Objective-C GC and address-space
3986 // qualifiers when performing these computations, so that e.g., an int in
3987 // address space 1 is not reference-compatible with an int in address
3988 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003989 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3990 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3991 T1Quals.removeObjCLifetime();
3992 T2Quals.removeObjCLifetime();
3993 ObjCLifetimeConversion = true;
3994 }
3995
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003996 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003997 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003998 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003999 return Ref_Compatible_With_Added_Qualification;
4000 else
4001 return Ref_Related;
4002}
4003
Douglas Gregor604eb652010-08-11 02:15:33 +00004004/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00004005/// with DeclType. Return true if something definite is found.
4006static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00004007FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
4008 QualType DeclType, SourceLocation DeclLoc,
4009 Expr *Init, QualType T2, bool AllowRvalues,
4010 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004011 assert(T2->isRecordType() && "Can only find conversions of record types.");
4012 CXXRecordDecl *T2RecordDecl
4013 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
4014
4015 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00004016 std::pair<CXXRecordDecl::conversion_iterator,
4017 CXXRecordDecl::conversion_iterator>
4018 Conversions = T2RecordDecl->getVisibleConversionFunctions();
4019 for (CXXRecordDecl::conversion_iterator
4020 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004021 NamedDecl *D = *I;
4022 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
4023 if (isa<UsingShadowDecl>(D))
4024 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4025
4026 FunctionTemplateDecl *ConvTemplate
4027 = dyn_cast<FunctionTemplateDecl>(D);
4028 CXXConversionDecl *Conv;
4029 if (ConvTemplate)
4030 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
4031 else
4032 Conv = cast<CXXConversionDecl>(D);
4033
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004034 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00004035 // explicit conversions, skip it.
4036 if (!AllowExplicit && Conv->isExplicit())
4037 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004038
Douglas Gregor604eb652010-08-11 02:15:33 +00004039 if (AllowRvalues) {
4040 bool DerivedToBase = false;
4041 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004042 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00004043
4044 // If we are initializing an rvalue reference, don't permit conversion
4045 // functions that return lvalues.
4046 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4047 const ReferenceType *RefType
4048 = Conv->getConversionType()->getAs<LValueReferenceType>();
4049 if (RefType && !RefType->getPointeeType()->isFunctionType())
4050 continue;
4051 }
4052
Douglas Gregor604eb652010-08-11 02:15:33 +00004053 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004054 S.CompareReferenceRelationship(
4055 DeclLoc,
4056 Conv->getConversionType().getNonReferenceType()
4057 .getUnqualifiedType(),
4058 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004059 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004060 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004061 continue;
4062 } else {
4063 // If the conversion function doesn't return a reference type,
4064 // it can't be considered for this conversion. An rvalue reference
4065 // is only acceptable if its referencee is a function type.
4066
4067 const ReferenceType *RefType =
4068 Conv->getConversionType()->getAs<ReferenceType>();
4069 if (!RefType ||
4070 (!RefType->isLValueReferenceType() &&
4071 !RefType->getPointeeType()->isFunctionType()))
4072 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004073 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004074
Douglas Gregor604eb652010-08-11 02:15:33 +00004075 if (ConvTemplate)
4076 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004077 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004078 else
4079 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004080 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004081 }
4082
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004083 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4084
Sebastian Redl4680bf22010-06-30 18:13:39 +00004085 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004086 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004087 case OR_Success:
4088 // C++ [over.ics.ref]p1:
4089 //
4090 // [...] If the parameter binds directly to the result of
4091 // applying a conversion function to the argument
4092 // expression, the implicit conversion sequence is a
4093 // user-defined conversion sequence (13.3.3.1.2), with the
4094 // second standard conversion sequence either an identity
4095 // conversion or, if the conversion function returns an
4096 // entity of a type that is a derived class of the parameter
4097 // type, a derived-to-base Conversion.
4098 if (!Best->FinalConversion.DirectBinding)
4099 return false;
4100
4101 ICS.setUserDefined();
4102 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4103 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004104 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004105 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004106 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004107 ICS.UserDefined.EllipsisConversion = false;
4108 assert(ICS.UserDefined.After.ReferenceBinding &&
4109 ICS.UserDefined.After.DirectBinding &&
4110 "Expected a direct reference binding!");
4111 return true;
4112
4113 case OR_Ambiguous:
4114 ICS.setAmbiguous();
4115 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4116 Cand != CandidateSet.end(); ++Cand)
4117 if (Cand->Viable)
4118 ICS.Ambiguous.addConversion(Cand->Function);
4119 return true;
4120
4121 case OR_No_Viable_Function:
4122 case OR_Deleted:
4123 // There was no suitable conversion, or we found a deleted
4124 // conversion; continue with other checks.
4125 return false;
4126 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004127
David Blaikie7530c032012-01-17 06:56:22 +00004128 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004129}
4130
Douglas Gregorabe183d2010-04-13 16:31:36 +00004131/// \brief Compute an implicit conversion sequence for reference
4132/// initialization.
4133static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004134TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004135 SourceLocation DeclLoc,
4136 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004137 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004138 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4139
4140 // Most paths end in a failed conversion.
4141 ImplicitConversionSequence ICS;
4142 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4143
4144 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4145 QualType T2 = Init->getType();
4146
4147 // If the initializer is the address of an overloaded function, try
4148 // to resolve the overloaded function. If all goes well, T2 is the
4149 // type of the resulting function.
4150 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4151 DeclAccessPair Found;
4152 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4153 false, Found))
4154 T2 = Fn->getType();
4155 }
4156
4157 // Compute some basic properties of the types and the initializer.
4158 bool isRValRef = DeclType->isRValueReferenceType();
4159 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004160 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004161 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004162 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004163 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004164 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004165 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004166
Douglas Gregorabe183d2010-04-13 16:31:36 +00004167
Sebastian Redl4680bf22010-06-30 18:13:39 +00004168 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004169 // A reference to type "cv1 T1" is initialized by an expression
4170 // of type "cv2 T2" as follows:
4171
Sebastian Redl4680bf22010-06-30 18:13:39 +00004172 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004173 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004174 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4175 // reference-compatible with "cv2 T2," or
4176 //
4177 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4178 if (InitCategory.isLValue() &&
4179 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004180 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004181 // When a parameter of reference type binds directly (8.5.3)
4182 // to an argument expression, the implicit conversion sequence
4183 // is the identity conversion, unless the argument expression
4184 // has a type that is a derived class of the parameter type,
4185 // in which case the implicit conversion sequence is a
4186 // derived-to-base Conversion (13.3.3.1).
4187 ICS.setStandard();
4188 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004189 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4190 : ObjCConversion? ICK_Compatible_Conversion
4191 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004192 ICS.Standard.Third = ICK_Identity;
4193 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4194 ICS.Standard.setToType(0, T2);
4195 ICS.Standard.setToType(1, T1);
4196 ICS.Standard.setToType(2, T1);
4197 ICS.Standard.ReferenceBinding = true;
4198 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004199 ICS.Standard.IsLvalueReference = !isRValRef;
4200 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4201 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004202 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004203 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004204 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004205
Sebastian Redl4680bf22010-06-30 18:13:39 +00004206 // Nothing more to do: the inaccessibility/ambiguity check for
4207 // derived-to-base conversions is suppressed when we're
4208 // computing the implicit conversion sequence (C++
4209 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004210 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004211 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004212
Sebastian Redl4680bf22010-06-30 18:13:39 +00004213 // -- has a class type (i.e., T2 is a class type), where T1 is
4214 // not reference-related to T2, and can be implicitly
4215 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4216 // is reference-compatible with "cv3 T3" 92) (this
4217 // conversion is selected by enumerating the applicable
4218 // conversion functions (13.3.1.6) and choosing the best
4219 // one through overload resolution (13.3)),
4220 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004221 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004222 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004223 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4224 Init, T2, /*AllowRvalues=*/false,
4225 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004226 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004227 }
4228 }
4229
Sebastian Redl4680bf22010-06-30 18:13:39 +00004230 // -- Otherwise, the reference shall be an lvalue reference to a
4231 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004232 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004233 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004234 // We actually handle one oddity of C++ [over.ics.ref] at this
4235 // point, which is that, due to p2 (which short-circuits reference
4236 // binding by only attempting a simple conversion for non-direct
4237 // bindings) and p3's strange wording, we allow a const volatile
4238 // reference to bind to an rvalue. Hence the check for the presence
4239 // of "const" rather than checking for "const" being the only
4240 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004241 // This is also the point where rvalue references and lvalue inits no longer
4242 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004243 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004244 return ICS;
4245
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004246 // -- If the initializer expression
4247 //
4248 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004249 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004250 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4251 (InitCategory.isXValue() ||
4252 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4253 (InitCategory.isLValue() && T2->isFunctionType()))) {
4254 ICS.setStandard();
4255 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004256 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004257 : ObjCConversion? ICK_Compatible_Conversion
4258 : ICK_Identity;
4259 ICS.Standard.Third = ICK_Identity;
4260 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4261 ICS.Standard.setToType(0, T2);
4262 ICS.Standard.setToType(1, T1);
4263 ICS.Standard.setToType(2, T1);
4264 ICS.Standard.ReferenceBinding = true;
4265 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4266 // binding unless we're binding to a class prvalue.
4267 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4268 // allow the use of rvalue references in C++98/03 for the benefit of
4269 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004270 ICS.Standard.DirectBinding =
Richard Smith80ad52f2013-01-02 11:42:31 +00004271 S.getLangOpts().CPlusPlus11 ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004272 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004273 ICS.Standard.IsLvalueReference = !isRValRef;
4274 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004275 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004276 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004277 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004278 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004279 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004280 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004281
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004282 // -- has a class type (i.e., T2 is a class type), where T1 is not
4283 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004284 // an xvalue, class prvalue, or function lvalue of type
4285 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004286 // "cv3 T3",
4287 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004288 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004289 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004290 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004291 // class subobject).
4292 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004293 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004294 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4295 Init, T2, /*AllowRvalues=*/true,
4296 AllowExplicit)) {
4297 // In the second case, if the reference is an rvalue reference
4298 // and the second standard conversion sequence of the
4299 // user-defined conversion sequence includes an lvalue-to-rvalue
4300 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004302 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4303 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4304
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004305 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004306 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004307
Douglas Gregorabe183d2010-04-13 16:31:36 +00004308 // -- Otherwise, a temporary of type "cv1 T1" is created and
4309 // initialized from the initializer expression using the
4310 // rules for a non-reference copy initialization (8.5). The
4311 // reference is then bound to the temporary. If T1 is
4312 // reference-related to T2, cv1 must be the same
4313 // cv-qualification as, or greater cv-qualification than,
4314 // cv2; otherwise, the program is ill-formed.
4315 if (RefRelationship == Sema::Ref_Related) {
4316 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4317 // we would be reference-compatible or reference-compatible with
4318 // added qualification. But that wasn't the case, so the reference
4319 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004320 //
4321 // Note that we only want to check address spaces and cvr-qualifiers here.
4322 // ObjC GC and lifetime qualifiers aren't important.
4323 Qualifiers T1Quals = T1.getQualifiers();
4324 Qualifiers T2Quals = T2.getQualifiers();
4325 T1Quals.removeObjCGCAttr();
4326 T1Quals.removeObjCLifetime();
4327 T2Quals.removeObjCGCAttr();
4328 T2Quals.removeObjCLifetime();
4329 if (!T1Quals.compatiblyIncludes(T2Quals))
4330 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004331 }
4332
4333 // If at least one of the types is a class type, the types are not
4334 // related, and we aren't allowed any user conversions, the
4335 // reference binding fails. This case is important for breaking
4336 // recursion, since TryImplicitConversion below will attempt to
4337 // create a temporary through the use of a copy constructor.
4338 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4339 (T1->isRecordType() || T2->isRecordType()))
4340 return ICS;
4341
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004342 // If T1 is reference-related to T2 and the reference is an rvalue
4343 // reference, the initializer expression shall not be an lvalue.
4344 if (RefRelationship >= Sema::Ref_Related &&
4345 isRValRef && Init->Classify(S.Context).isLValue())
4346 return ICS;
4347
Douglas Gregorabe183d2010-04-13 16:31:36 +00004348 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004349 // When a parameter of reference type is not bound directly to
4350 // an argument expression, the conversion sequence is the one
4351 // required to convert the argument expression to the
4352 // underlying type of the reference according to
4353 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4354 // to copy-initializing a temporary of the underlying type with
4355 // the argument expression. Any difference in top-level
4356 // cv-qualification is subsumed by the initialization itself
4357 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004358 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4359 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004360 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004361 /*CStyle=*/false,
4362 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004363
4364 // Of course, that's still a reference binding.
4365 if (ICS.isStandard()) {
4366 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004367 ICS.Standard.IsLvalueReference = !isRValRef;
4368 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4369 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004370 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004371 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004372 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004373 // Don't allow rvalue references to bind to lvalues.
4374 if (DeclType->isRValueReferenceType()) {
4375 if (const ReferenceType *RefType
4376 = ICS.UserDefined.ConversionFunction->getResultType()
4377 ->getAs<LValueReferenceType>()) {
4378 if (!RefType->getPointeeType()->isFunctionType()) {
4379 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4380 DeclType);
4381 return ICS;
4382 }
4383 }
4384 }
4385
Douglas Gregorabe183d2010-04-13 16:31:36 +00004386 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004387 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4388 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4389 ICS.UserDefined.After.BindsToRvalue = true;
4390 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4391 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004392 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004393
Douglas Gregorabe183d2010-04-13 16:31:36 +00004394 return ICS;
4395}
4396
Sebastian Redl5405b812011-10-16 18:19:34 +00004397static ImplicitConversionSequence
4398TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4399 bool SuppressUserConversions,
4400 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004401 bool AllowObjCWritebackConversion,
4402 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004403
4404/// TryListConversion - Try to copy-initialize a value of type ToType from the
4405/// initializer list From.
4406static ImplicitConversionSequence
4407TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4408 bool SuppressUserConversions,
4409 bool InOverloadResolution,
4410 bool AllowObjCWritebackConversion) {
4411 // C++11 [over.ics.list]p1:
4412 // When an argument is an initializer list, it is not an expression and
4413 // special rules apply for converting it to a parameter type.
4414
4415 ImplicitConversionSequence Result;
4416 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004417 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004418
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004419 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004420 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004421 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004422 return Result;
4423
Sebastian Redl5405b812011-10-16 18:19:34 +00004424 // C++11 [over.ics.list]p2:
4425 // If the parameter type is std::initializer_list<X> or "array of X" and
4426 // all the elements can be implicitly converted to X, the implicit
4427 // conversion sequence is the worst conversion necessary to convert an
4428 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004429 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004430 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004431 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004432 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004433 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004434 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004435 if (!X.isNull()) {
4436 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4437 Expr *Init = From->getInit(i);
4438 ImplicitConversionSequence ICS =
4439 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4440 InOverloadResolution,
4441 AllowObjCWritebackConversion);
4442 // If a single element isn't convertible, fail.
4443 if (ICS.isBad()) {
4444 Result = ICS;
4445 break;
4446 }
4447 // Otherwise, look for the worst conversion.
4448 if (Result.isBad() ||
4449 CompareImplicitConversionSequences(S, ICS, Result) ==
4450 ImplicitConversionSequence::Worse)
4451 Result = ICS;
4452 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004453
4454 // For an empty list, we won't have computed any conversion sequence.
4455 // Introduce the identity conversion sequence.
4456 if (From->getNumInits() == 0) {
4457 Result.setStandard();
4458 Result.Standard.setAsIdentityConversion();
4459 Result.Standard.setFromType(ToType);
4460 Result.Standard.setAllToTypes(ToType);
4461 }
4462
Sebastian Redlfe592282012-01-17 22:49:48 +00004463 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004464 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004465 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004466 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004467
4468 // C++11 [over.ics.list]p3:
4469 // Otherwise, if the parameter is a non-aggregate class X and overload
4470 // resolution chooses a single best constructor [...] the implicit
4471 // conversion sequence is a user-defined conversion sequence. If multiple
4472 // constructors are viable but none is better than the others, the
4473 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004474 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4475 // This function can deal with initializer lists.
4476 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4477 /*AllowExplicit=*/false,
4478 InOverloadResolution, /*CStyle=*/false,
4479 AllowObjCWritebackConversion);
4480 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004481 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004482 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004483
4484 // C++11 [over.ics.list]p4:
4485 // Otherwise, if the parameter has an aggregate type which can be
4486 // initialized from the initializer list [...] the implicit conversion
4487 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004488 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004489 // Type is an aggregate, argument is an init list. At this point it comes
4490 // down to checking whether the initialization works.
4491 // FIXME: Find out whether this parameter is consumed or not.
4492 InitializedEntity Entity =
4493 InitializedEntity::InitializeParameter(S.Context, ToType,
4494 /*Consumed=*/false);
4495 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4496 Result.setUserDefined();
4497 Result.UserDefined.Before.setAsIdentityConversion();
4498 // Initializer lists don't have a type.
4499 Result.UserDefined.Before.setFromType(QualType());
4500 Result.UserDefined.Before.setAllToTypes(QualType());
4501
4502 Result.UserDefined.After.setAsIdentityConversion();
4503 Result.UserDefined.After.setFromType(ToType);
4504 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004505 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004506 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004507 return Result;
4508 }
4509
4510 // C++11 [over.ics.list]p5:
4511 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004512 if (ToType->isReferenceType()) {
4513 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4514 // mention initializer lists in any way. So we go by what list-
4515 // initialization would do and try to extrapolate from that.
4516
4517 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4518
4519 // If the initializer list has a single element that is reference-related
4520 // to the parameter type, we initialize the reference from that.
4521 if (From->getNumInits() == 1) {
4522 Expr *Init = From->getInit(0);
4523
4524 QualType T2 = Init->getType();
4525
4526 // If the initializer is the address of an overloaded function, try
4527 // to resolve the overloaded function. If all goes well, T2 is the
4528 // type of the resulting function.
4529 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4530 DeclAccessPair Found;
4531 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4532 Init, ToType, false, Found))
4533 T2 = Fn->getType();
4534 }
4535
4536 // Compute some basic properties of the types and the initializer.
4537 bool dummy1 = false;
4538 bool dummy2 = false;
4539 bool dummy3 = false;
4540 Sema::ReferenceCompareResult RefRelationship
4541 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4542 dummy2, dummy3);
4543
4544 if (RefRelationship >= Sema::Ref_Related)
4545 return TryReferenceInit(S, Init, ToType,
4546 /*FIXME:*/From->getLocStart(),
4547 SuppressUserConversions,
4548 /*AllowExplicit=*/false);
4549 }
4550
4551 // Otherwise, we bind the reference to a temporary created from the
4552 // initializer list.
4553 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4554 InOverloadResolution,
4555 AllowObjCWritebackConversion);
4556 if (Result.isFailure())
4557 return Result;
4558 assert(!Result.isEllipsis() &&
4559 "Sub-initialization cannot result in ellipsis conversion.");
4560
4561 // Can we even bind to a temporary?
4562 if (ToType->isRValueReferenceType() ||
4563 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4564 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4565 Result.UserDefined.After;
4566 SCS.ReferenceBinding = true;
4567 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4568 SCS.BindsToRvalue = true;
4569 SCS.BindsToFunctionLvalue = false;
4570 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4571 SCS.ObjCLifetimeConversionBinding = false;
4572 } else
4573 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4574 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004575 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004576 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004577
4578 // C++11 [over.ics.list]p6:
4579 // Otherwise, if the parameter type is not a class:
4580 if (!ToType->isRecordType()) {
4581 // - if the initializer list has one element, the implicit conversion
4582 // sequence is the one required to convert the element to the
4583 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004584 unsigned NumInits = From->getNumInits();
4585 if (NumInits == 1)
4586 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4587 SuppressUserConversions,
4588 InOverloadResolution,
4589 AllowObjCWritebackConversion);
4590 // - if the initializer list has no elements, the implicit conversion
4591 // sequence is the identity conversion.
4592 else if (NumInits == 0) {
4593 Result.setStandard();
4594 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004595 Result.Standard.setFromType(ToType);
4596 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004597 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004598 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004599 return Result;
4600 }
4601
4602 // C++11 [over.ics.list]p7:
4603 // In all cases other than those enumerated above, no conversion is possible
4604 return Result;
4605}
4606
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004607/// TryCopyInitialization - Try to copy-initialize a value of type
4608/// ToType from the expression From. Return the implicit conversion
4609/// sequence required to pass this argument, which may be a bad
4610/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004611/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004612/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004613static ImplicitConversionSequence
4614TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004615 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004616 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004617 bool AllowObjCWritebackConversion,
4618 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004619 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4620 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4621 InOverloadResolution,AllowObjCWritebackConversion);
4622
Douglas Gregorabe183d2010-04-13 16:31:36 +00004623 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004624 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004625 /*FIXME:*/From->getLocStart(),
4626 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004627 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004628
John McCall120d63c2010-08-24 20:38:10 +00004629 return TryImplicitConversion(S, From, ToType,
4630 SuppressUserConversions,
4631 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004632 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004633 /*CStyle=*/false,
4634 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004635}
4636
Anna Zaksf3546ee2011-07-28 19:46:48 +00004637static bool TryCopyInitialization(const CanQualType FromQTy,
4638 const CanQualType ToQTy,
4639 Sema &S,
4640 SourceLocation Loc,
4641 ExprValueKind FromVK) {
4642 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4643 ImplicitConversionSequence ICS =
4644 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4645
4646 return !ICS.isBad();
4647}
4648
Douglas Gregor96176b32008-11-18 23:14:02 +00004649/// TryObjectArgumentInitialization - Try to initialize the object
4650/// parameter of the given member function (@c Method) from the
4651/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004652static ImplicitConversionSequence
Richard Smith98bfbf52013-01-26 02:07:32 +00004653TryObjectArgumentInitialization(Sema &S, QualType FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004654 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004655 CXXMethodDecl *Method,
4656 CXXRecordDecl *ActingContext) {
4657 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004658 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4659 // const volatile object.
4660 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4661 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004662 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004663
4664 // Set up the conversion sequence as a "bad" conversion, to allow us
4665 // to exit early.
4666 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004667
4668 // We need to have an object of class type.
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004669 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004670 FromType = PT->getPointeeType();
4671
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004672 // When we had a pointer, it's implicitly dereferenced, so we
4673 // better have an lvalue.
4674 assert(FromClassification.isLValue());
4675 }
4676
Anders Carlssona552f7c2009-05-01 18:34:30 +00004677 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004678
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004679 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004680 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004681 // parameter is
4682 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004683 // - "lvalue reference to cv X" for functions declared without a
4684 // ref-qualifier or with the & ref-qualifier
4685 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004686 // ref-qualifier
4687 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004688 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004689 // cv-qualification on the member function declaration.
4690 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004691 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004692 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004693 // (C++ [over.match.funcs]p5). We perform a simplified version of
4694 // reference binding here, that allows class rvalues to bind to
4695 // non-constant references.
4696
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004697 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004698 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004699 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004700 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004701 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004702 ICS.setBad(BadConversionSequence::bad_qualifiers,
Richard Smith98bfbf52013-01-26 02:07:32 +00004703 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004704 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004705 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004706
4707 // Check that we have either the same type or a derived type. It
4708 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004709 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004710 ImplicitConversionKind SecondKind;
4711 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4712 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004713 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004714 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004715 else {
John McCallb1bdc622010-02-25 01:37:24 +00004716 ICS.setBad(BadConversionSequence::unrelated_class,
4717 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004718 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004719 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004720
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004721 // Check the ref-qualifier.
4722 switch (Method->getRefQualifier()) {
4723 case RQ_None:
4724 // Do nothing; we don't care about lvalueness or rvalueness.
4725 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004726
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004727 case RQ_LValue:
4728 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4729 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004730 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004731 ImplicitParamType);
4732 return ICS;
4733 }
4734 break;
4735
4736 case RQ_RValue:
4737 if (!FromClassification.isRValue()) {
4738 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004739 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004740 ImplicitParamType);
4741 return ICS;
4742 }
4743 break;
4744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004745
Douglas Gregor96176b32008-11-18 23:14:02 +00004746 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004747 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004748 ICS.Standard.setAsIdentityConversion();
4749 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004750 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004751 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004752 ICS.Standard.ReferenceBinding = true;
4753 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004754 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004755 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004756 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4757 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4758 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004759 return ICS;
4760}
4761
4762/// PerformObjectArgumentInitialization - Perform initialization of
4763/// the implicit object parameter for the given Method with the given
4764/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004765ExprResult
4766Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004767 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004768 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004769 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004770 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004771 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004772 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004774 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004775 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004776 FromRecordType = PT->getPointeeType();
4777 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004778 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004779 } else {
4780 FromRecordType = From->getType();
4781 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004782 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004783 }
4784
John McCall701c89e2009-12-03 04:06:58 +00004785 // Note that we always use the true parent context when performing
4786 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004787 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004788 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4789 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004790 if (ICS.isBad()) {
4791 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4792 Qualifiers FromQs = FromRecordType.getQualifiers();
4793 Qualifiers ToQs = DestType.getQualifiers();
4794 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4795 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004796 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004797 diag::err_member_function_call_bad_cvr)
4798 << Method->getDeclName() << FromRecordType << (CVR - 1)
4799 << From->getSourceRange();
4800 Diag(Method->getLocation(), diag::note_previous_decl)
4801 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004802 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004803 }
4804 }
4805
Daniel Dunbar96a00142012-03-09 18:35:03 +00004806 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004807 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004808 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004809 }
Mike Stump1eb44332009-09-09 15:08:12 +00004810
John Wiegley429bb272011-04-08 18:41:53 +00004811 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4812 ExprResult FromRes =
4813 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4814 if (FromRes.isInvalid())
4815 return ExprError();
4816 From = FromRes.take();
4817 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004818
Douglas Gregor5fccd362010-03-03 23:55:11 +00004819 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004820 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004821 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004822 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004823}
4824
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004825/// TryContextuallyConvertToBool - Attempt to contextually convert the
4826/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004827static ImplicitConversionSequence
4828TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004829 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004830 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004831 // FIXME: Are these flags correct?
4832 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004833 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004834 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004835 /*CStyle=*/false,
4836 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004837}
4838
4839/// PerformContextuallyConvertToBool - Perform a contextual conversion
4840/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004841ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004842 if (checkPlaceholderForOverload(*this, From))
4843 return ExprError();
4844
John McCall120d63c2010-08-24 20:38:10 +00004845 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004846 if (!ICS.isBad())
4847 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004848
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004849 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004850 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004851 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004852 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004853 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004854}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004855
Richard Smith8ef7b202012-01-18 23:55:52 +00004856/// Check that the specified conversion is permitted in a converted constant
4857/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4858/// is acceptable.
4859static bool CheckConvertedConstantConversions(Sema &S,
4860 StandardConversionSequence &SCS) {
4861 // Since we know that the target type is an integral or unscoped enumeration
4862 // type, most conversion kinds are impossible. All possible First and Third
4863 // conversions are fine.
4864 switch (SCS.Second) {
4865 case ICK_Identity:
4866 case ICK_Integral_Promotion:
4867 case ICK_Integral_Conversion:
4868 return true;
4869
4870 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004871 // Conversion from an integral or unscoped enumeration type to bool is
4872 // classified as ICK_Boolean_Conversion, but it's also an integral
4873 // conversion, so it's permitted in a converted constant expression.
4874 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4875 SCS.getToType(2)->isBooleanType();
4876
Richard Smith8ef7b202012-01-18 23:55:52 +00004877 case ICK_Floating_Integral:
4878 case ICK_Complex_Real:
4879 return false;
4880
4881 case ICK_Lvalue_To_Rvalue:
4882 case ICK_Array_To_Pointer:
4883 case ICK_Function_To_Pointer:
4884 case ICK_NoReturn_Adjustment:
4885 case ICK_Qualification:
4886 case ICK_Compatible_Conversion:
4887 case ICK_Vector_Conversion:
4888 case ICK_Vector_Splat:
4889 case ICK_Derived_To_Base:
4890 case ICK_Pointer_Conversion:
4891 case ICK_Pointer_Member:
4892 case ICK_Block_Pointer_Conversion:
4893 case ICK_Writeback_Conversion:
4894 case ICK_Floating_Promotion:
4895 case ICK_Complex_Promotion:
4896 case ICK_Complex_Conversion:
4897 case ICK_Floating_Conversion:
4898 case ICK_TransparentUnionConversion:
4899 llvm_unreachable("unexpected second conversion kind");
4900
4901 case ICK_Num_Conversion_Kinds:
4902 break;
4903 }
4904
4905 llvm_unreachable("unknown conversion kind");
4906}
4907
4908/// CheckConvertedConstantExpression - Check that the expression From is a
4909/// converted constant expression of type T, perform the conversion and produce
4910/// the converted expression, per C++11 [expr.const]p3.
4911ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4912 llvm::APSInt &Value,
4913 CCEKind CCE) {
Richard Smith80ad52f2013-01-02 11:42:31 +00004914 assert(LangOpts.CPlusPlus11 && "converted constant expression outside C++11");
Richard Smith8ef7b202012-01-18 23:55:52 +00004915 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4916
4917 if (checkPlaceholderForOverload(*this, From))
4918 return ExprError();
4919
4920 // C++11 [expr.const]p3 with proposed wording fixes:
4921 // A converted constant expression of type T is a core constant expression,
4922 // implicitly converted to a prvalue of type T, where the converted
4923 // expression is a literal constant expression and the implicit conversion
4924 // sequence contains only user-defined conversions, lvalue-to-rvalue
4925 // conversions, integral promotions, and integral conversions other than
4926 // narrowing conversions.
4927 ImplicitConversionSequence ICS =
4928 TryImplicitConversion(From, T,
4929 /*SuppressUserConversions=*/false,
4930 /*AllowExplicit=*/false,
4931 /*InOverloadResolution=*/false,
4932 /*CStyle=*/false,
4933 /*AllowObjcWritebackConversion=*/false);
4934 StandardConversionSequence *SCS = 0;
4935 switch (ICS.getKind()) {
4936 case ImplicitConversionSequence::StandardConversion:
4937 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004938 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004939 diag::err_typecheck_converted_constant_expression_disallowed)
4940 << From->getType() << From->getSourceRange() << T;
4941 SCS = &ICS.Standard;
4942 break;
4943 case ImplicitConversionSequence::UserDefinedConversion:
4944 // We are converting from class type to an integral or enumeration type, so
4945 // the Before sequence must be trivial.
4946 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004947 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004948 diag::err_typecheck_converted_constant_expression_disallowed)
4949 << From->getType() << From->getSourceRange() << T;
4950 SCS = &ICS.UserDefined.After;
4951 break;
4952 case ImplicitConversionSequence::AmbiguousConversion:
4953 case ImplicitConversionSequence::BadConversion:
4954 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004955 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004956 diag::err_typecheck_converted_constant_expression)
4957 << From->getType() << From->getSourceRange() << T;
4958 return ExprError();
4959
4960 case ImplicitConversionSequence::EllipsisConversion:
4961 llvm_unreachable("ellipsis conversion in converted constant expression");
4962 }
4963
4964 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4965 if (Result.isInvalid())
4966 return Result;
4967
4968 // Check for a narrowing implicit conversion.
4969 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004970 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004971 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4972 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004973 case NK_Variable_Narrowing:
4974 // Implicit conversion to a narrower type, and the value is not a constant
4975 // expression. We'll diagnose this in a moment.
4976 case NK_Not_Narrowing:
4977 break;
4978
4979 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004980 Diag(From->getLocStart(),
4981 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4982 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004983 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004984 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004985 break;
4986
4987 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004988 Diag(From->getLocStart(),
4989 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4990 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004991 << CCE << /*Constant*/0 << From->getType() << T;
4992 break;
4993 }
4994
4995 // Check the expression is a constant expression.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00004996 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith8ef7b202012-01-18 23:55:52 +00004997 Expr::EvalResult Eval;
4998 Eval.Diag = &Notes;
4999
5000 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
5001 // The expression can't be folded, so we can't keep it at this position in
5002 // the AST.
5003 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00005004 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00005005 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00005006
5007 if (Notes.empty()) {
5008 // It's a constant expression.
5009 return Result;
5010 }
Richard Smith8ef7b202012-01-18 23:55:52 +00005011 }
5012
5013 // It's not a constant expression. Produce an appropriate diagnostic.
5014 if (Notes.size() == 1 &&
5015 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
5016 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
5017 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00005018 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00005019 << CCE << From->getSourceRange();
5020 for (unsigned I = 0; I < Notes.size(); ++I)
5021 Diag(Notes[I].first, Notes[I].second);
5022 }
Richard Smithf72fccf2012-01-30 22:27:01 +00005023 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00005024}
5025
John McCall0bcc9bc2011-09-09 06:11:02 +00005026/// dropPointerConversions - If the given standard conversion sequence
5027/// involves any pointer conversions, remove them. This may change
5028/// the result type of the conversion sequence.
5029static void dropPointerConversion(StandardConversionSequence &SCS) {
5030 if (SCS.Second == ICK_Pointer_Conversion) {
5031 SCS.Second = ICK_Identity;
5032 SCS.Third = ICK_Identity;
5033 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
5034 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005035}
John McCall120d63c2010-08-24 20:38:10 +00005036
John McCall0bcc9bc2011-09-09 06:11:02 +00005037/// TryContextuallyConvertToObjCPointer - Attempt to contextually
5038/// convert the expression From to an Objective-C pointer type.
5039static ImplicitConversionSequence
5040TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
5041 // Do an implicit conversion to 'id'.
5042 QualType Ty = S.Context.getObjCIdType();
5043 ImplicitConversionSequence ICS
5044 = TryImplicitConversion(S, From, Ty,
5045 // FIXME: Are these flags correct?
5046 /*SuppressUserConversions=*/false,
5047 /*AllowExplicit=*/true,
5048 /*InOverloadResolution=*/false,
5049 /*CStyle=*/false,
5050 /*AllowObjCWritebackConversion=*/false);
5051
5052 // Strip off any final conversions to 'id'.
5053 switch (ICS.getKind()) {
5054 case ImplicitConversionSequence::BadConversion:
5055 case ImplicitConversionSequence::AmbiguousConversion:
5056 case ImplicitConversionSequence::EllipsisConversion:
5057 break;
5058
5059 case ImplicitConversionSequence::UserDefinedConversion:
5060 dropPointerConversion(ICS.UserDefined.After);
5061 break;
5062
5063 case ImplicitConversionSequence::StandardConversion:
5064 dropPointerConversion(ICS.Standard);
5065 break;
5066 }
5067
5068 return ICS;
5069}
5070
5071/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5072/// conversion of the expression From to an Objective-C pointer type.
5073ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005074 if (checkPlaceholderForOverload(*this, From))
5075 return ExprError();
5076
John McCallc12c5bb2010-05-15 11:32:37 +00005077 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005078 ImplicitConversionSequence ICS =
5079 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005080 if (!ICS.isBad())
5081 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005082 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005083}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005084
Richard Smithf39aec12012-02-04 07:07:42 +00005085/// Determine whether the provided type is an integral type, or an enumeration
5086/// type of a permitted flavor.
5087static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5088 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5089 : T->isIntegralOrUnscopedEnumerationType();
5090}
5091
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005092/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005093/// enumeration type.
5094///
5095/// This routine will attempt to convert an expression of class type to an
5096/// integral or enumeration type, if that class type only has a single
5097/// conversion to an integral or enumeration type.
5098///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005099/// \param Loc The source location of the construct that requires the
5100/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005101///
James Dennett40ae6662012-06-22 08:52:37 +00005102/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005103///
James Dennett40ae6662012-06-22 08:52:37 +00005104/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005105///
Richard Smithf39aec12012-02-04 07:07:42 +00005106/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5107/// enumerations should be considered.
5108///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005109/// \returns The expression, converted to an integral or enumeration type if
5110/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005111ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005112Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005113 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005114 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005115 // We can't perform any more checking for type-dependent expressions.
5116 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005117 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005118
Eli Friedmanceccab92012-01-26 00:26:18 +00005119 // Process placeholders immediately.
5120 if (From->hasPlaceholderType()) {
5121 ExprResult result = CheckPlaceholderExpr(From);
5122 if (result.isInvalid()) return result;
5123 From = result.take();
5124 }
5125
Douglas Gregorc30614b2010-06-29 23:17:37 +00005126 // If the expression already has integral or enumeration type, we're golden.
5127 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005128 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005129 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005130
5131 // FIXME: Check for missing '()' if T is a function type?
5132
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005133 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00005134 // expression of integral or enumeration type.
5135 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005136 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005137 if (!Diagnoser.Suppress)
5138 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005139 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005141
Douglas Gregorc30614b2010-06-29 23:17:37 +00005142 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005143 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005144 ICEConvertDiagnoser &Diagnoser;
5145 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005146
Douglas Gregorab41fe92012-05-04 22:38:52 +00005147 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5148 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005149
5150 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005151 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005152 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005153 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005154
5155 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005156 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
Douglas Gregorc30614b2010-06-29 23:17:37 +00005158 // Look for a conversion to an integral or enumeration type.
5159 UnresolvedSet<4> ViableConversions;
5160 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005161 std::pair<CXXRecordDecl::conversion_iterator,
5162 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005163 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005164
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005165 bool HadMultipleCandidates
5166 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005167
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005168 for (CXXRecordDecl::conversion_iterator
5169 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005170 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005171 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5172 if (isIntegralOrEnumerationType(
5173 Conversion->getConversionType().getNonReferenceType(),
5174 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005175 if (Conversion->isExplicit())
5176 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5177 else
5178 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5179 }
Richard Smithf39aec12012-02-04 07:07:42 +00005180 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005181 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005182
Douglas Gregorc30614b2010-06-29 23:17:37 +00005183 switch (ViableConversions.size()) {
5184 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005185 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005186 DeclAccessPair Found = ExplicitConversions[0];
5187 CXXConversionDecl *Conversion
5188 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189
Douglas Gregorc30614b2010-06-29 23:17:37 +00005190 // The user probably meant to invoke the given explicit
5191 // conversion; use it.
5192 QualType ConvTy
5193 = Conversion->getConversionType().getNonReferenceType();
5194 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005195 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005196
Douglas Gregorab41fe92012-05-04 22:38:52 +00005197 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005198 << FixItHint::CreateInsertion(From->getLocStart(),
5199 "static_cast<" + TypeStr + ">(")
5200 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5201 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005202 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005203
5204 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005205 // explicit conversion function.
5206 if (isSFINAEContext())
5207 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005208
Douglas Gregorc30614b2010-06-29 23:17:37 +00005209 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005210 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5211 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005212 if (Result.isInvalid())
5213 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005214 // Record usage of conversion in an implicit cast.
5215 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5216 CK_UserDefinedConversion,
5217 Result.get(), 0,
5218 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005220
Douglas Gregorc30614b2010-06-29 23:17:37 +00005221 // We'll complain below about a non-integral condition type.
5222 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005223
Douglas Gregorc30614b2010-06-29 23:17:37 +00005224 case 1: {
5225 // Apply this conversion.
5226 DeclAccessPair Found = ViableConversions[0];
5227 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005228
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005229 CXXConversionDecl *Conversion
5230 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5231 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005232 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005233 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005234 if (isSFINAEContext())
5235 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005236
Douglas Gregorab41fe92012-05-04 22:38:52 +00005237 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5238 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005239 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005240
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005241 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5242 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005243 if (Result.isInvalid())
5244 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005245 // Record usage of conversion in an implicit cast.
5246 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5247 CK_UserDefinedConversion,
5248 Result.get(), 0,
5249 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005250 break;
5251 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005252
Douglas Gregorc30614b2010-06-29 23:17:37 +00005253 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005254 if (Diagnoser.Suppress)
5255 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005256
Douglas Gregorab41fe92012-05-04 22:38:52 +00005257 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005258 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5259 CXXConversionDecl *Conv
5260 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5261 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005262 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005263 }
John McCall9ae2f072010-08-23 23:25:46 +00005264 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005265 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005266
Richard Smith282e7e62012-02-04 09:53:13 +00005267 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005268 !Diagnoser.Suppress) {
5269 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5270 << From->getSourceRange();
5271 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005272
Eli Friedmanceccab92012-01-26 00:26:18 +00005273 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005274}
5275
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005276/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005277/// candidate functions, using the given function call arguments. If
5278/// @p SuppressUserConversions, then don't allow user-defined
5279/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005280///
James Dennett699c9042012-06-15 07:13:21 +00005281/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005282/// based on an incomplete set of function arguments. This feature is used by
5283/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005284void
5285Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005286 DeclAccessPair FoundDecl,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005287 ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005288 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005289 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005290 bool PartialOverloading,
5291 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005292 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005293 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005294 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005295 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005296 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005297
Douglas Gregor88a35142008-12-22 05:46:06 +00005298 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005299 if (!isa<CXXConstructorDecl>(Method)) {
5300 // If we get here, it's because we're calling a member function
5301 // that is named without a member access expression (e.g.,
5302 // "this->f") that was either written explicitly or created
5303 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005304 // function, e.g., X::f(). We use an empty type for the implied
5305 // object argument (C++ [over.call.func]p3), and the acting context
5306 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005307 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005308 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005309 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005310 return;
5311 }
5312 // We treat a constructor like a non-member function, since its object
5313 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005314 }
5315
Douglas Gregorfd476482009-11-13 23:59:09 +00005316 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005317 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005318
Douglas Gregor7edfb692009-11-23 12:27:39 +00005319 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005320 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005321
Douglas Gregor66724ea2009-11-14 01:20:54 +00005322 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5323 // C++ [class.copy]p3:
5324 // A member function template is never instantiated to perform the copy
5325 // of a class object to an object of its class type.
5326 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005327 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005328 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005329 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5330 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005331 return;
5332 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005333
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005334 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005335 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005336 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005337 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005338 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005339 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005340 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005341 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005342
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005343 unsigned NumArgsInProto = Proto->getNumArgs();
5344
5345 // (C++ 13.3.2p2): A candidate function having fewer than m
5346 // parameters is viable only if it has an ellipsis in its parameter
5347 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005348 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005349 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005350 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005351 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005352 return;
5353 }
5354
5355 // (C++ 13.3.2p2): A candidate function having more than m parameters
5356 // is viable only if the (m+1)st parameter has a default argument
5357 // (8.3.6). For the purposes of overload resolution, the
5358 // parameter list is truncated on the right, so that there are
5359 // exactly m parameters.
5360 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005361 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005362 // Not enough arguments.
5363 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005364 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005365 return;
5366 }
5367
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005368 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005369 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005370 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5371 if (CheckCUDATarget(Caller, Function)) {
5372 Candidate.Viable = false;
5373 Candidate.FailureKind = ovl_fail_bad_target;
5374 return;
5375 }
5376
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005377 // Determine the implicit conversion sequences for each of the
5378 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005379 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005380 if (ArgIdx < NumArgsInProto) {
5381 // (C++ 13.3.2p3): for F to be a viable function, there shall
5382 // exist for each argument an implicit conversion sequence
5383 // (13.3.3.1) that converts that argument to the corresponding
5384 // parameter of F.
5385 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005386 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005387 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005388 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005389 /*InOverloadResolution=*/true,
5390 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005391 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005392 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005393 if (Candidate.Conversions[ArgIdx].isBad()) {
5394 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005395 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005396 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005397 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005398 } else {
5399 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5400 // argument for which there is no corresponding parameter is
5401 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005402 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005403 }
5404 }
5405}
5406
Douglas Gregor063daf62009-03-13 18:40:31 +00005407/// \brief Add all of the function declarations in the given function set to
5408/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005409void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005410 ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005411 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005412 bool SuppressUserConversions,
5413 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005414 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005415 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5416 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005417 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005418 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005419 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005420 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005421 Args.slice(1), CandidateSet,
5422 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005423 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005424 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005425 SuppressUserConversions);
5426 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005427 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005428 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5429 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005430 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005431 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005432 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005433 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005434 Args[0]->Classify(Context), Args.slice(1),
5435 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005436 else
John McCall9aa472c2010-03-19 07:35:19 +00005437 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005438 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005439 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005440 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005441 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005442}
5443
John McCall314be4e2009-11-17 07:50:12 +00005444/// AddMethodCandidate - Adds a named decl (which is some kind of
5445/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005446void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005447 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005448 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005449 Expr **Args, unsigned NumArgs,
5450 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005451 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005452 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005453 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005454
5455 if (isa<UsingShadowDecl>(Decl))
5456 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005457
John McCall314be4e2009-11-17 07:50:12 +00005458 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5459 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5460 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005461 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5462 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005463 ObjectType, ObjectClassification,
5464 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005465 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005466 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005467 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005468 ObjectType, ObjectClassification,
5469 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005470 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005471 }
5472}
5473
Douglas Gregor96176b32008-11-18 23:14:02 +00005474/// AddMethodCandidate - Adds the given C++ member function to the set
5475/// of candidate functions, using the given function call arguments
5476/// and the object argument (@c Object). For example, in a call
5477/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5478/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5479/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005480/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005481void
John McCall9aa472c2010-03-19 07:35:19 +00005482Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005483 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005484 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005485 ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005486 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005487 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005488 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005489 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005490 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005491 assert(!isa<CXXConstructorDecl>(Method) &&
5492 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005493
Douglas Gregor3f396022009-09-28 04:47:19 +00005494 if (!CandidateSet.isNewCandidate(Method))
5495 return;
5496
Douglas Gregor7edfb692009-11-23 12:27:39 +00005497 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005498 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005499
Douglas Gregor96176b32008-11-18 23:14:02 +00005500 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005501 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005502 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005503 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005504 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005505 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005506 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005507
5508 unsigned NumArgsInProto = Proto->getNumArgs();
5509
5510 // (C++ 13.3.2p2): A candidate function having fewer than m
5511 // parameters is viable only if it has an ellipsis in its parameter
5512 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005513 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005514 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005515 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005516 return;
5517 }
5518
5519 // (C++ 13.3.2p2): A candidate function having more than m parameters
5520 // is viable only if the (m+1)st parameter has a default argument
5521 // (8.3.6). For the purposes of overload resolution, the
5522 // parameter list is truncated on the right, so that there are
5523 // exactly m parameters.
5524 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005525 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005526 // Not enough arguments.
5527 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005528 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005529 return;
5530 }
5531
5532 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005533
John McCall701c89e2009-12-03 04:06:58 +00005534 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005535 // The implicit object argument is ignored.
5536 Candidate.IgnoreObjectArgument = true;
5537 else {
5538 // Determine the implicit conversion sequence for the object
5539 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005540 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005541 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5542 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005543 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005544 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005545 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005546 return;
5547 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005548 }
5549
5550 // Determine the implicit conversion sequences for each of the
5551 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005552 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005553 if (ArgIdx < NumArgsInProto) {
5554 // (C++ 13.3.2p3): for F to be a viable function, there shall
5555 // exist for each argument an implicit conversion sequence
5556 // (13.3.3.1) that converts that argument to the corresponding
5557 // parameter of F.
5558 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005559 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005560 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005561 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005562 /*InOverloadResolution=*/true,
5563 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005564 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005565 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005566 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005567 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005568 break;
5569 }
5570 } else {
5571 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5572 // argument for which there is no corresponding parameter is
5573 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005574 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005575 }
5576 }
5577}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005578
Douglas Gregor6b906862009-08-21 00:16:32 +00005579/// \brief Add a C++ member function template as a candidate to the candidate
5580/// set, using template argument deduction to produce an appropriate member
5581/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005582void
Douglas Gregor6b906862009-08-21 00:16:32 +00005583Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005584 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005585 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005586 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005587 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005588 Expr::Classification ObjectClassification,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005589 ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005590 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005591 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005592 if (!CandidateSet.isNewCandidate(MethodTmpl))
5593 return;
5594
Douglas Gregor6b906862009-08-21 00:16:32 +00005595 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005596 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005597 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005598 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005599 // candidate functions in the usual way.113) A given name can refer to one
5600 // or more function templates and also to a set of overloaded non-template
5601 // functions. In such a case, the candidate functions generated from each
5602 // function template are combined with the set of non-template candidate
5603 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005604 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005605 FunctionDecl *Specialization = 0;
5606 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005607 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5608 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005609 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005610 Candidate.FoundDecl = FoundDecl;
5611 Candidate.Function = MethodTmpl->getTemplatedDecl();
5612 Candidate.Viable = false;
5613 Candidate.FailureKind = ovl_fail_bad_deduction;
5614 Candidate.IsSurrogate = false;
5615 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005616 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005617 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005618 Info);
5619 return;
5620 }
Mike Stump1eb44332009-09-09 15:08:12 +00005621
Douglas Gregor6b906862009-08-21 00:16:32 +00005622 // Add the function template specialization produced by template argument
5623 // deduction as a candidate.
5624 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005625 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005626 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005627 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005628 ActingContext, ObjectType, ObjectClassification, Args,
5629 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005630}
5631
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005632/// \brief Add a C++ function template specialization as a candidate
5633/// in the candidate set, using template argument deduction to produce
5634/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005635void
Douglas Gregore53060f2009-06-25 22:08:12 +00005636Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005637 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005638 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005639 ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005640 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005641 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005642 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5643 return;
5644
Douglas Gregore53060f2009-06-25 22:08:12 +00005645 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005646 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005647 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005648 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005649 // candidate functions in the usual way.113) A given name can refer to one
5650 // or more function templates and also to a set of overloaded non-template
5651 // functions. In such a case, the candidate functions generated from each
5652 // function template are combined with the set of non-template candidate
5653 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005654 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005655 FunctionDecl *Specialization = 0;
5656 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005657 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5658 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005659 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005660 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005661 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5662 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005663 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005664 Candidate.IsSurrogate = false;
5665 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005666 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005667 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005668 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005669 return;
5670 }
Mike Stump1eb44332009-09-09 15:08:12 +00005671
Douglas Gregore53060f2009-06-25 22:08:12 +00005672 // Add the function template specialization produced by template argument
5673 // deduction as a candidate.
5674 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005675 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005676 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005677}
Mike Stump1eb44332009-09-09 15:08:12 +00005678
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005679/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005680/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005681/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005682/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005683/// (which may or may not be the same type as the type that the
5684/// conversion function produces).
5685void
5686Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005687 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005688 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005689 Expr *From, QualType ToType,
5690 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005691 assert(!Conversion->getDescribedFunctionTemplate() &&
5692 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005693 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005694 if (!CandidateSet.isNewCandidate(Conversion))
5695 return;
5696
Douglas Gregor7edfb692009-11-23 12:27:39 +00005697 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005698 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005699
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005700 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005701 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005702 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005703 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005704 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005705 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005706 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005707 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005708 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005709 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005710 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005711
Douglas Gregorbca39322010-08-19 15:37:02 +00005712 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005713 // For conversion functions, the function is considered to be a member of
5714 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005715 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005716 //
5717 // Determine the implicit conversion sequence for the implicit
5718 // object parameter.
5719 QualType ImplicitParamType = From->getType();
5720 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5721 ImplicitParamType = FromPtrType->getPointeeType();
5722 CXXRecordDecl *ConversionContext
5723 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005724
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005725 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005726 = TryObjectArgumentInitialization(*this, From->getType(),
5727 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005728 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005729
John McCall1d318332010-01-12 00:44:57 +00005730 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005731 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005732 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005733 return;
5734 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005735
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005736 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005737 // derived to base as such conversions are given Conversion Rank. They only
5738 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5739 QualType FromCanon
5740 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5741 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5742 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5743 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005744 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005745 return;
5746 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005747
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005748 // To determine what the conversion from the result of calling the
5749 // conversion function to the type we're eventually trying to
5750 // convert to (ToType), we need to synthesize a call to the
5751 // conversion function and attempt copy initialization from it. This
5752 // makes sure that we get the right semantics with respect to
5753 // lvalues/rvalues and the type. Fortunately, we can allocate this
5754 // call on the stack and we don't need its arguments to be
5755 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005756 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005757 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005758 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5759 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005760 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005761 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005762
Richard Smith87c1f1f2011-07-13 22:53:21 +00005763 QualType ConversionType = Conversion->getConversionType();
5764 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005765 Candidate.Viable = false;
5766 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5767 return;
5768 }
5769
Richard Smith87c1f1f2011-07-13 22:53:21 +00005770 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005771
Mike Stump1eb44332009-09-09 15:08:12 +00005772 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005773 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5774 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005775 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005776 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005777 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005778 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005779 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005780 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005781 /*InOverloadResolution=*/false,
5782 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005783
John McCall1d318332010-01-12 00:44:57 +00005784 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005785 case ImplicitConversionSequence::StandardConversion:
5786 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005787
Douglas Gregorc520c842010-04-12 23:42:09 +00005788 // C++ [over.ics.user]p3:
5789 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005790 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005791 // shall have exact match rank.
5792 if (Conversion->getPrimaryTemplate() &&
5793 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5794 Candidate.Viable = false;
5795 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5796 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005797
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005798 // C++0x [dcl.init.ref]p5:
5799 // In the second case, if the reference is an rvalue reference and
5800 // the second standard conversion sequence of the user-defined
5801 // conversion sequence includes an lvalue-to-rvalue conversion, the
5802 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005803 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005804 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5805 Candidate.Viable = false;
5806 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5807 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005808 break;
5809
5810 case ImplicitConversionSequence::BadConversion:
5811 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005812 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005813 break;
5814
5815 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005816 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005817 "Can only end up with a standard conversion sequence or failure");
5818 }
5819}
5820
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005821/// \brief Adds a conversion function template specialization
5822/// candidate to the overload set, using template argument deduction
5823/// to deduce the template arguments of the conversion function
5824/// template from the type that we are converting to (C++
5825/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005826void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005827Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005828 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005829 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005830 Expr *From, QualType ToType,
5831 OverloadCandidateSet &CandidateSet) {
5832 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5833 "Only conversion function templates permitted here");
5834
Douglas Gregor3f396022009-09-28 04:47:19 +00005835 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5836 return;
5837
Craig Topper93e45992012-09-19 02:26:47 +00005838 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005839 CXXConversionDecl *Specialization = 0;
5840 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005841 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005842 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005843 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005844 Candidate.FoundDecl = FoundDecl;
5845 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5846 Candidate.Viable = false;
5847 Candidate.FailureKind = ovl_fail_bad_deduction;
5848 Candidate.IsSurrogate = false;
5849 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005850 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005851 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005852 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005853 return;
5854 }
Mike Stump1eb44332009-09-09 15:08:12 +00005855
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005856 // Add the conversion function template specialization produced by
5857 // template argument deduction as a candidate.
5858 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005859 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005860 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005861}
5862
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005863/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5864/// converts the given @c Object to a function pointer via the
5865/// conversion function @c Conversion, and then attempts to call it
5866/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5867/// the type of function that we'll eventually be calling.
5868void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005869 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005870 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005871 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005872 Expr *Object,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00005873 ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005874 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005875 if (!CandidateSet.isNewCandidate(Conversion))
5876 return;
5877
Douglas Gregor7edfb692009-11-23 12:27:39 +00005878 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005879 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005880
Ahmed Charles13a140c2012-02-25 11:00:22 +00005881 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005882 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005883 Candidate.Function = 0;
5884 Candidate.Surrogate = Conversion;
5885 Candidate.Viable = true;
5886 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005887 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005888 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005889
5890 // Determine the implicit conversion sequence for the implicit
5891 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005892 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005893 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005894 Object->Classify(Context),
5895 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005896 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005897 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005898 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005899 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005900 return;
5901 }
5902
5903 // The first conversion is actually a user-defined conversion whose
5904 // first conversion is ObjectInit's standard conversion (which is
5905 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005906 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005907 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005908 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005909 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005910 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005911 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005912 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005913 = Candidate.Conversions[0].UserDefined.Before;
5914 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5915
Mike Stump1eb44332009-09-09 15:08:12 +00005916 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005917 unsigned NumArgsInProto = Proto->getNumArgs();
5918
5919 // (C++ 13.3.2p2): A candidate function having fewer than m
5920 // parameters is viable only if it has an ellipsis in its parameter
5921 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005922 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005923 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005924 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005925 return;
5926 }
5927
5928 // Function types don't have any default arguments, so just check if
5929 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005930 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005931 // Not enough arguments.
5932 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005933 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005934 return;
5935 }
5936
5937 // Determine the implicit conversion sequences for each of the
5938 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005939 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005940 if (ArgIdx < NumArgsInProto) {
5941 // (C++ 13.3.2p3): for F to be a viable function, there shall
5942 // exist for each argument an implicit conversion sequence
5943 // (13.3.3.1) that converts that argument to the corresponding
5944 // parameter of F.
5945 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005946 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005947 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005948 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005949 /*InOverloadResolution=*/false,
5950 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005951 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005952 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005953 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005954 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005955 break;
5956 }
5957 } else {
5958 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5959 // argument for which there is no corresponding parameter is
5960 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005961 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005962 }
5963 }
5964}
5965
Douglas Gregor063daf62009-03-13 18:40:31 +00005966/// \brief Add overload candidates for overloaded operators that are
5967/// member functions.
5968///
5969/// Add the overloaded operator candidates that are member functions
5970/// for the operator Op that was used in an operator expression such
5971/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5972/// CandidateSet will store the added overload candidates. (C++
5973/// [over.match.oper]).
5974void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5975 SourceLocation OpLoc,
5976 Expr **Args, unsigned NumArgs,
5977 OverloadCandidateSet& CandidateSet,
5978 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005979 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5980
5981 // C++ [over.match.oper]p3:
5982 // For a unary operator @ with an operand of a type whose
5983 // cv-unqualified version is T1, and for a binary operator @ with
5984 // a left operand of a type whose cv-unqualified version is T1 and
5985 // a right operand of a type whose cv-unqualified version is T2,
5986 // three sets of candidate functions, designated member
5987 // candidates, non-member candidates and built-in candidates, are
5988 // constructed as follows:
5989 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005990
5991 // -- If T1 is a class type, the set of member candidates is the
5992 // result of the qualified lookup of T1::operator@
5993 // (13.3.1.1.1); otherwise, the set of member candidates is
5994 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005995 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005996 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005997 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005998 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005999
John McCalla24dc2e2009-11-17 02:14:36 +00006000 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
6001 LookupQualifiedName(Operators, T1Rec->getDecl());
6002 Operators.suppressDiagnostics();
6003
Mike Stump1eb44332009-09-09 15:08:12 +00006004 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00006005 OperEnd = Operators.end();
6006 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00006007 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00006008 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006009 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006010 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006011 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00006012 }
Douglas Gregor96176b32008-11-18 23:14:02 +00006013}
6014
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006015/// AddBuiltinCandidate - Add a candidate for a built-in
6016/// operator. ResultTy and ParamTys are the result and parameter types
6017/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006018/// arguments being passed to the candidate. IsAssignmentOperator
6019/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006020/// operator. NumContextualBoolArguments is the number of arguments
6021/// (at the beginning of the argument list) that will be contextually
6022/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00006023void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006024 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006025 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006026 bool IsAssignmentOperator,
6027 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00006028 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00006029 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00006030
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006031 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00006032 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00006033 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006034 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00006035 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006036 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006037 Candidate.BuiltinTypes.ResultTy = ResultTy;
6038 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6039 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
6040
6041 // Determine the implicit conversion sequences for each of the
6042 // arguments.
6043 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006044 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006045 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006046 // C++ [over.match.oper]p4:
6047 // For the built-in assignment operators, conversions of the
6048 // left operand are restricted as follows:
6049 // -- no temporaries are introduced to hold the left operand, and
6050 // -- no user-defined conversions are applied to the left
6051 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006052 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006053 //
6054 // We block these conversions by turning off user-defined
6055 // conversions, since that is the only way that initialization of
6056 // a reference to a non-class type can occur from something that
6057 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006058 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006059 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006060 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006061 Candidate.Conversions[ArgIdx]
6062 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006063 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006064 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006065 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006066 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006067 /*InOverloadResolution=*/false,
6068 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006069 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006070 }
John McCall1d318332010-01-12 00:44:57 +00006071 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006072 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006073 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006074 break;
6075 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006076 }
6077}
6078
6079/// BuiltinCandidateTypeSet - A set of types that will be used for the
6080/// candidate operator functions for built-in operators (C++
6081/// [over.built]). The types are separated into pointer types and
6082/// enumeration types.
6083class BuiltinCandidateTypeSet {
6084 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006085 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006086
6087 /// PointerTypes - The set of pointer types that will be used in the
6088 /// built-in candidates.
6089 TypeSet PointerTypes;
6090
Sebastian Redl78eb8742009-04-19 21:53:20 +00006091 /// MemberPointerTypes - The set of member pointer types that will be
6092 /// used in the built-in candidates.
6093 TypeSet MemberPointerTypes;
6094
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006095 /// EnumerationTypes - The set of enumeration types that will be
6096 /// used in the built-in candidates.
6097 TypeSet EnumerationTypes;
6098
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006099 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006100 /// candidates.
6101 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006102
6103 /// \brief A flag indicating non-record types are viable candidates
6104 bool HasNonRecordTypes;
6105
6106 /// \brief A flag indicating whether either arithmetic or enumeration types
6107 /// were present in the candidate set.
6108 bool HasArithmeticOrEnumeralTypes;
6109
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006110 /// \brief A flag indicating whether the nullptr type was present in the
6111 /// candidate set.
6112 bool HasNullPtrType;
6113
Douglas Gregor5842ba92009-08-24 15:23:48 +00006114 /// Sema - The semantic analysis instance where we are building the
6115 /// candidate type set.
6116 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006117
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006118 /// Context - The AST context in which we will build the type sets.
6119 ASTContext &Context;
6120
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006121 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6122 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006123 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006124
6125public:
6126 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006127 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006128
Mike Stump1eb44332009-09-09 15:08:12 +00006129 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006130 : HasNonRecordTypes(false),
6131 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006132 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006133 SemaRef(SemaRef),
6134 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006135
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006136 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006137 SourceLocation Loc,
6138 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006139 bool AllowExplicitConversions,
6140 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006141
6142 /// pointer_begin - First pointer type found;
6143 iterator pointer_begin() { return PointerTypes.begin(); }
6144
Sebastian Redl78eb8742009-04-19 21:53:20 +00006145 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006146 iterator pointer_end() { return PointerTypes.end(); }
6147
Sebastian Redl78eb8742009-04-19 21:53:20 +00006148 /// member_pointer_begin - First member pointer type found;
6149 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6150
6151 /// member_pointer_end - Past the last member pointer type found;
6152 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6153
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006154 /// enumeration_begin - First enumeration type found;
6155 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6156
Sebastian Redl78eb8742009-04-19 21:53:20 +00006157 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006158 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006159
Douglas Gregor26bcf672010-05-19 03:21:00 +00006160 iterator vector_begin() { return VectorTypes.begin(); }
6161 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006162
6163 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6164 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006165 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006166};
6167
Sebastian Redl78eb8742009-04-19 21:53:20 +00006168/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006169/// the set of pointer types along with any more-qualified variants of
6170/// that type. For example, if @p Ty is "int const *", this routine
6171/// will add "int const *", "int const volatile *", "int const
6172/// restrict *", and "int const volatile restrict *" to the set of
6173/// pointer types. Returns true if the add of @p Ty itself succeeded,
6174/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006175///
6176/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006177bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006178BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6179 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006180
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006181 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006182 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006183 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006184
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006185 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006186 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006187 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006188 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006189 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6190 PointeeTy = PTy->getPointeeType();
6191 buildObjCPtr = true;
6192 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006193 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006194 }
6195
Sebastian Redla9efada2009-11-18 20:39:26 +00006196 // Don't add qualified variants of arrays. For one, they're not allowed
6197 // (the qualifier would sink to the element type), and for another, the
6198 // only overload situation where it matters is subscript or pointer +- int,
6199 // and those shouldn't have qualifier variants anyway.
6200 if (PointeeTy->isArrayType())
6201 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006202
John McCall0953e762009-09-24 19:53:00 +00006203 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006204 bool hasVolatile = VisibleQuals.hasVolatile();
6205 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006206
John McCall0953e762009-09-24 19:53:00 +00006207 // Iterate through all strict supersets of BaseCVR.
6208 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6209 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006210 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006211 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006212
6213 // Skip over restrict if no restrict found anywhere in the types, or if
6214 // the type cannot be restrict-qualified.
6215 if ((CVR & Qualifiers::Restrict) &&
6216 (!hasRestrict ||
6217 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6218 continue;
6219
6220 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006221 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006222
6223 // Build qualified pointer type.
6224 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006225 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006226 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006227 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006228 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6229
6230 // Insert qualified pointer type.
6231 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006232 }
6233
6234 return true;
6235}
6236
Sebastian Redl78eb8742009-04-19 21:53:20 +00006237/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6238/// to the set of pointer types along with any more-qualified variants of
6239/// that type. For example, if @p Ty is "int const *", this routine
6240/// will add "int const *", "int const volatile *", "int const
6241/// restrict *", and "int const volatile restrict *" to the set of
6242/// pointer types. Returns true if the add of @p Ty itself succeeded,
6243/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006244///
6245/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006246bool
6247BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6248 QualType Ty) {
6249 // Insert this type.
6250 if (!MemberPointerTypes.insert(Ty))
6251 return false;
6252
John McCall0953e762009-09-24 19:53:00 +00006253 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6254 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006255
John McCall0953e762009-09-24 19:53:00 +00006256 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006257 // Don't add qualified variants of arrays. For one, they're not allowed
6258 // (the qualifier would sink to the element type), and for another, the
6259 // only overload situation where it matters is subscript or pointer +- int,
6260 // and those shouldn't have qualifier variants anyway.
6261 if (PointeeTy->isArrayType())
6262 return true;
John McCall0953e762009-09-24 19:53:00 +00006263 const Type *ClassTy = PointerTy->getClass();
6264
6265 // Iterate through all strict supersets of the pointee type's CVR
6266 // qualifiers.
6267 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6268 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6269 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006270
John McCall0953e762009-09-24 19:53:00 +00006271 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006272 MemberPointerTypes.insert(
6273 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006274 }
6275
6276 return true;
6277}
6278
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006279/// AddTypesConvertedFrom - Add each of the types to which the type @p
6280/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006281/// primarily interested in pointer types and enumeration types. We also
6282/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006283/// AllowUserConversions is true if we should look at the conversion
6284/// functions of a class type, and AllowExplicitConversions if we
6285/// should also include the explicit conversion functions of a class
6286/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006287void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006288BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006289 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006290 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006291 bool AllowExplicitConversions,
6292 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006293 // Only deal with canonical types.
6294 Ty = Context.getCanonicalType(Ty);
6295
6296 // Look through reference types; they aren't part of the type of an
6297 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006298 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006299 Ty = RefTy->getPointeeType();
6300
John McCall3b657512011-01-19 10:06:00 +00006301 // If we're dealing with an array type, decay to the pointer.
6302 if (Ty->isArrayType())
6303 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6304
6305 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006306 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006307
Chandler Carruth6a577462010-12-13 01:44:01 +00006308 // Flag if we ever add a non-record type.
6309 const RecordType *TyRec = Ty->getAs<RecordType>();
6310 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6311
Chandler Carruth6a577462010-12-13 01:44:01 +00006312 // Flag if we encounter an arithmetic type.
6313 HasArithmeticOrEnumeralTypes =
6314 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6315
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006316 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6317 PointerTypes.insert(Ty);
6318 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006319 // Insert our type, and its more-qualified variants, into the set
6320 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006321 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006322 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006323 } else if (Ty->isMemberPointerType()) {
6324 // Member pointers are far easier, since the pointee can't be converted.
6325 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6326 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006327 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006328 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006329 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006330 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006331 // We treat vector types as arithmetic types in many contexts as an
6332 // extension.
6333 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006334 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006335 } else if (Ty->isNullPtrType()) {
6336 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006337 } else if (AllowUserConversions && TyRec) {
6338 // No conversion functions in incomplete types.
6339 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6340 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006341
Chandler Carruth6a577462010-12-13 01:44:01 +00006342 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006343 std::pair<CXXRecordDecl::conversion_iterator,
6344 CXXRecordDecl::conversion_iterator>
6345 Conversions = ClassDecl->getVisibleConversionFunctions();
6346 for (CXXRecordDecl::conversion_iterator
6347 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006348 NamedDecl *D = I.getDecl();
6349 if (isa<UsingShadowDecl>(D))
6350 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006351
Chandler Carruth6a577462010-12-13 01:44:01 +00006352 // Skip conversion function templates; they don't tell us anything
6353 // about which builtin types we can convert to.
6354 if (isa<FunctionTemplateDecl>(D))
6355 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006356
Chandler Carruth6a577462010-12-13 01:44:01 +00006357 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6358 if (AllowExplicitConversions || !Conv->isExplicit()) {
6359 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6360 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006361 }
6362 }
6363 }
6364}
6365
Douglas Gregor19b7b152009-08-24 13:43:27 +00006366/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6367/// the volatile- and non-volatile-qualified assignment operators for the
6368/// given type to the candidate set.
6369static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6370 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006371 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006372 unsigned NumArgs,
6373 OverloadCandidateSet &CandidateSet) {
6374 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006375
Douglas Gregor19b7b152009-08-24 13:43:27 +00006376 // T& operator=(T&, T)
6377 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6378 ParamTypes[1] = T;
6379 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6380 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006381
Douglas Gregor19b7b152009-08-24 13:43:27 +00006382 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6383 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006384 ParamTypes[0]
6385 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006386 ParamTypes[1] = T;
6387 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006388 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006389 }
6390}
Mike Stump1eb44332009-09-09 15:08:12 +00006391
Sebastian Redl9994a342009-10-25 17:03:50 +00006392/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6393/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006394static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6395 Qualifiers VRQuals;
6396 const RecordType *TyRec;
6397 if (const MemberPointerType *RHSMPType =
6398 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006399 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006400 else
6401 TyRec = ArgExpr->getType()->getAs<RecordType>();
6402 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006403 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006404 VRQuals.addVolatile();
6405 VRQuals.addRestrict();
6406 return VRQuals;
6407 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006408
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006409 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006410 if (!ClassDecl->hasDefinition())
6411 return VRQuals;
6412
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006413 std::pair<CXXRecordDecl::conversion_iterator,
6414 CXXRecordDecl::conversion_iterator>
6415 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006416
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006417 for (CXXRecordDecl::conversion_iterator
6418 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006419 NamedDecl *D = I.getDecl();
6420 if (isa<UsingShadowDecl>(D))
6421 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6422 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006423 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6424 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6425 CanTy = ResTypeRef->getPointeeType();
6426 // Need to go down the pointer/mempointer chain and add qualifiers
6427 // as see them.
6428 bool done = false;
6429 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006430 if (CanTy.isRestrictQualified())
6431 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006432 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6433 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006434 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006435 CanTy->getAs<MemberPointerType>())
6436 CanTy = ResTypeMPtr->getPointeeType();
6437 else
6438 done = true;
6439 if (CanTy.isVolatileQualified())
6440 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006441 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6442 return VRQuals;
6443 }
6444 }
6445 }
6446 return VRQuals;
6447}
John McCall00071ec2010-11-13 05:51:15 +00006448
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006449namespace {
John McCall00071ec2010-11-13 05:51:15 +00006450
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006451/// \brief Helper class to manage the addition of builtin operator overload
6452/// candidates. It provides shared state and utility methods used throughout
6453/// the process, as well as a helper method to add each group of builtin
6454/// operator overloads from the standard to a candidate set.
6455class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006456 // Common instance state available to all overload candidate addition methods.
6457 Sema &S;
6458 Expr **Args;
6459 unsigned NumArgs;
6460 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006461 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006462 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006463 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006464
Chandler Carruth6d695582010-12-12 10:35:00 +00006465 // Define some constants used to index and iterate over the arithemetic types
6466 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006467 // The "promoted arithmetic types" are the arithmetic
6468 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006469 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006470 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006471 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006472 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006473 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006474 LastPromotedArithmeticType = 11;
6475 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006476
Chandler Carruth6d695582010-12-12 10:35:00 +00006477 /// \brief Get the canonical type for a given arithmetic type index.
6478 CanQualType getArithmeticType(unsigned index) {
6479 assert(index < NumArithmeticTypes);
6480 static CanQualType ASTContext::* const
6481 ArithmeticTypes[NumArithmeticTypes] = {
6482 // Start of promoted types.
6483 &ASTContext::FloatTy,
6484 &ASTContext::DoubleTy,
6485 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006486
Chandler Carruth6d695582010-12-12 10:35:00 +00006487 // Start of integral types.
6488 &ASTContext::IntTy,
6489 &ASTContext::LongTy,
6490 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006491 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006492 &ASTContext::UnsignedIntTy,
6493 &ASTContext::UnsignedLongTy,
6494 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006495 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006496 // End of promoted types.
6497
6498 &ASTContext::BoolTy,
6499 &ASTContext::CharTy,
6500 &ASTContext::WCharTy,
6501 &ASTContext::Char16Ty,
6502 &ASTContext::Char32Ty,
6503 &ASTContext::SignedCharTy,
6504 &ASTContext::ShortTy,
6505 &ASTContext::UnsignedCharTy,
6506 &ASTContext::UnsignedShortTy,
6507 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006508 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006509 };
6510 return S.Context.*ArithmeticTypes[index];
6511 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006512
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006513 /// \brief Gets the canonical type resulting from the usual arithemetic
6514 /// converions for the given arithmetic types.
6515 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6516 // Accelerator table for performing the usual arithmetic conversions.
6517 // The rules are basically:
6518 // - if either is floating-point, use the wider floating-point
6519 // - if same signedness, use the higher rank
6520 // - if same size, use unsigned of the higher rank
6521 // - use the larger type
6522 // These rules, together with the axiom that higher ranks are
6523 // never smaller, are sufficient to precompute all of these results
6524 // *except* when dealing with signed types of higher rank.
6525 // (we could precompute SLL x UI for all known platforms, but it's
6526 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006527 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006528 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006529 Dep=-1,
6530 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006531 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006532 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006533 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006534/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6535/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6536/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6537/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6538/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6539/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6540/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6541/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6542/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6543/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6544/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006545 };
6546
6547 assert(L < LastPromotedArithmeticType);
6548 assert(R < LastPromotedArithmeticType);
6549 int Idx = ConversionsTable[L][R];
6550
6551 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006552 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006553
6554 // Slow path: we need to compare widths.
6555 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006556 CanQualType LT = getArithmeticType(L),
6557 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006558 unsigned LW = S.Context.getIntWidth(LT),
6559 RW = S.Context.getIntWidth(RT);
6560
6561 // If they're different widths, use the signed type.
6562 if (LW > RW) return LT;
6563 else if (LW < RW) return RT;
6564
6565 // Otherwise, use the unsigned type of the signed type's rank.
6566 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6567 assert(L == SLL || R == SLL);
6568 return S.Context.UnsignedLongLongTy;
6569 }
6570
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006571 /// \brief Helper method to factor out the common pattern of adding overloads
6572 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006573 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006574 bool HasVolatile,
6575 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006576 QualType ParamTypes[2] = {
6577 S.Context.getLValueReferenceType(CandidateTy),
6578 S.Context.IntTy
6579 };
6580
6581 // Non-volatile version.
6582 if (NumArgs == 1)
6583 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6584 else
6585 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6586
6587 // Use a heuristic to reduce number of builtin candidates in the set:
6588 // add volatile version only if there are conversions to a volatile type.
6589 if (HasVolatile) {
6590 ParamTypes[0] =
6591 S.Context.getLValueReferenceType(
6592 S.Context.getVolatileType(CandidateTy));
6593 if (NumArgs == 1)
6594 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6595 else
6596 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6597 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006598
6599 // Add restrict version only if there are conversions to a restrict type
6600 // and our candidate type is a non-restrict-qualified pointer.
6601 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6602 !CandidateTy.isRestrictQualified()) {
6603 ParamTypes[0]
6604 = S.Context.getLValueReferenceType(
6605 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6606 if (NumArgs == 1)
6607 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6608 else
6609 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6610
6611 if (HasVolatile) {
6612 ParamTypes[0]
6613 = S.Context.getLValueReferenceType(
6614 S.Context.getCVRQualifiedType(CandidateTy,
6615 (Qualifiers::Volatile |
6616 Qualifiers::Restrict)));
6617 if (NumArgs == 1)
6618 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6619 CandidateSet);
6620 else
6621 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6622 }
6623 }
6624
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006625 }
6626
6627public:
6628 BuiltinOperatorOverloadBuilder(
6629 Sema &S, Expr **Args, unsigned NumArgs,
6630 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006631 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006632 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006633 OverloadCandidateSet &CandidateSet)
6634 : S(S), Args(Args), NumArgs(NumArgs),
6635 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006636 HasArithmeticOrEnumeralCandidateType(
6637 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006638 CandidateTypes(CandidateTypes),
6639 CandidateSet(CandidateSet) {
6640 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006641 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006642 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006643 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006644 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006645 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006646 assert(getArithmeticType(FirstPromotedArithmeticType)
6647 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006648 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006649 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006650 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006651 "Invalid last promoted arithmetic type");
6652 }
6653
6654 // C++ [over.built]p3:
6655 //
6656 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6657 // is either volatile or empty, there exist candidate operator
6658 // functions of the form
6659 //
6660 // VQ T& operator++(VQ T&);
6661 // T operator++(VQ T&, int);
6662 //
6663 // C++ [over.built]p4:
6664 //
6665 // For every pair (T, VQ), where T is an arithmetic type other
6666 // than bool, and VQ is either volatile or empty, there exist
6667 // candidate operator functions of the form
6668 //
6669 // VQ T& operator--(VQ T&);
6670 // T operator--(VQ T&, int);
6671 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006672 if (!HasArithmeticOrEnumeralCandidateType)
6673 return;
6674
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006675 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6676 Arith < NumArithmeticTypes; ++Arith) {
6677 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006678 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006679 VisibleTypeConversionsQuals.hasVolatile(),
6680 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006681 }
6682 }
6683
6684 // C++ [over.built]p5:
6685 //
6686 // For every pair (T, VQ), where T is a cv-qualified or
6687 // cv-unqualified object type, and VQ is either volatile or
6688 // empty, there exist candidate operator functions of the form
6689 //
6690 // T*VQ& operator++(T*VQ&);
6691 // T*VQ& operator--(T*VQ&);
6692 // T* operator++(T*VQ&, int);
6693 // T* operator--(T*VQ&, int);
6694 void addPlusPlusMinusMinusPointerOverloads() {
6695 for (BuiltinCandidateTypeSet::iterator
6696 Ptr = CandidateTypes[0].pointer_begin(),
6697 PtrEnd = CandidateTypes[0].pointer_end();
6698 Ptr != PtrEnd; ++Ptr) {
6699 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006700 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006701 continue;
6702
6703 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006704 (!(*Ptr).isVolatileQualified() &&
6705 VisibleTypeConversionsQuals.hasVolatile()),
6706 (!(*Ptr).isRestrictQualified() &&
6707 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006708 }
6709 }
6710
6711 // C++ [over.built]p6:
6712 // For every cv-qualified or cv-unqualified object type T, there
6713 // exist candidate operator functions of the form
6714 //
6715 // T& operator*(T*);
6716 //
6717 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006718 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006719 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006720 // T& operator*(T*);
6721 void addUnaryStarPointerOverloads() {
6722 for (BuiltinCandidateTypeSet::iterator
6723 Ptr = CandidateTypes[0].pointer_begin(),
6724 PtrEnd = CandidateTypes[0].pointer_end();
6725 Ptr != PtrEnd; ++Ptr) {
6726 QualType ParamTy = *Ptr;
6727 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006728 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6729 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006730
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006731 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6732 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6733 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006734
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006735 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6736 &ParamTy, Args, 1, CandidateSet);
6737 }
6738 }
6739
6740 // C++ [over.built]p9:
6741 // For every promoted arithmetic type T, there exist candidate
6742 // operator functions of the form
6743 //
6744 // T operator+(T);
6745 // T operator-(T);
6746 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006747 if (!HasArithmeticOrEnumeralCandidateType)
6748 return;
6749
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006750 for (unsigned Arith = FirstPromotedArithmeticType;
6751 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006752 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006753 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6754 }
6755
6756 // Extension: We also add these operators for vector types.
6757 for (BuiltinCandidateTypeSet::iterator
6758 Vec = CandidateTypes[0].vector_begin(),
6759 VecEnd = CandidateTypes[0].vector_end();
6760 Vec != VecEnd; ++Vec) {
6761 QualType VecTy = *Vec;
6762 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6763 }
6764 }
6765
6766 // C++ [over.built]p8:
6767 // For every type T, there exist candidate operator functions of
6768 // the form
6769 //
6770 // T* operator+(T*);
6771 void addUnaryPlusPointerOverloads() {
6772 for (BuiltinCandidateTypeSet::iterator
6773 Ptr = CandidateTypes[0].pointer_begin(),
6774 PtrEnd = CandidateTypes[0].pointer_end();
6775 Ptr != PtrEnd; ++Ptr) {
6776 QualType ParamTy = *Ptr;
6777 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6778 }
6779 }
6780
6781 // C++ [over.built]p10:
6782 // For every promoted integral type T, there exist candidate
6783 // operator functions of the form
6784 //
6785 // T operator~(T);
6786 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006787 if (!HasArithmeticOrEnumeralCandidateType)
6788 return;
6789
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006790 for (unsigned Int = FirstPromotedIntegralType;
6791 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006792 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006793 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6794 }
6795
6796 // Extension: We also add this operator for vector types.
6797 for (BuiltinCandidateTypeSet::iterator
6798 Vec = CandidateTypes[0].vector_begin(),
6799 VecEnd = CandidateTypes[0].vector_end();
6800 Vec != VecEnd; ++Vec) {
6801 QualType VecTy = *Vec;
6802 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6803 }
6804 }
6805
6806 // C++ [over.match.oper]p16:
6807 // For every pointer to member type T, there exist candidate operator
6808 // functions of the form
6809 //
6810 // bool operator==(T,T);
6811 // bool operator!=(T,T);
6812 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6813 /// Set of (canonical) types that we've already handled.
6814 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6815
6816 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6817 for (BuiltinCandidateTypeSet::iterator
6818 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6819 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6820 MemPtr != MemPtrEnd;
6821 ++MemPtr) {
6822 // Don't add the same builtin candidate twice.
6823 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6824 continue;
6825
6826 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6827 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6828 CandidateSet);
6829 }
6830 }
6831 }
6832
6833 // C++ [over.built]p15:
6834 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006835 // For every T, where T is an enumeration type, a pointer type, or
6836 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006837 //
6838 // bool operator<(T, T);
6839 // bool operator>(T, T);
6840 // bool operator<=(T, T);
6841 // bool operator>=(T, T);
6842 // bool operator==(T, T);
6843 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006844 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006845 // C++ [over.match.oper]p3:
6846 // [...]the built-in candidates include all of the candidate operator
6847 // functions defined in 13.6 that, compared to the given operator, [...]
6848 // do not have the same parameter-type-list as any non-template non-member
6849 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006850 //
Eli Friedman97c67392012-09-18 21:52:24 +00006851 // Note that in practice, this only affects enumeration types because there
6852 // aren't any built-in candidates of record type, and a user-defined operator
6853 // must have an operand of record or enumeration type. Also, the only other
6854 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006855 // cannot be overloaded for enumeration types, so this is the only place
6856 // where we must suppress candidates like this.
6857 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6858 UserDefinedBinaryOperators;
6859
6860 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6861 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6862 CandidateTypes[ArgIdx].enumeration_end()) {
6863 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6864 CEnd = CandidateSet.end();
6865 C != CEnd; ++C) {
6866 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6867 continue;
6868
Eli Friedman97c67392012-09-18 21:52:24 +00006869 if (C->Function->isFunctionTemplateSpecialization())
6870 continue;
6871
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006872 QualType FirstParamType =
6873 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6874 QualType SecondParamType =
6875 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6876
6877 // Skip if either parameter isn't of enumeral type.
6878 if (!FirstParamType->isEnumeralType() ||
6879 !SecondParamType->isEnumeralType())
6880 continue;
6881
6882 // Add this operator to the set of known user-defined operators.
6883 UserDefinedBinaryOperators.insert(
6884 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6885 S.Context.getCanonicalType(SecondParamType)));
6886 }
6887 }
6888 }
6889
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006890 /// Set of (canonical) types that we've already handled.
6891 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6892
6893 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6894 for (BuiltinCandidateTypeSet::iterator
6895 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6896 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6897 Ptr != PtrEnd; ++Ptr) {
6898 // Don't add the same builtin candidate twice.
6899 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6900 continue;
6901
6902 QualType ParamTypes[2] = { *Ptr, *Ptr };
6903 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6904 CandidateSet);
6905 }
6906 for (BuiltinCandidateTypeSet::iterator
6907 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6908 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6909 Enum != EnumEnd; ++Enum) {
6910 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6911
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006912 // Don't add the same builtin candidate twice, or if a user defined
6913 // candidate exists.
6914 if (!AddedTypes.insert(CanonType) ||
6915 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6916 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006917 continue;
6918
6919 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006920 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6921 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006922 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006923
6924 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6925 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6926 if (AddedTypes.insert(NullPtrTy) &&
6927 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6928 NullPtrTy))) {
6929 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6930 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6931 CandidateSet);
6932 }
6933 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006934 }
6935 }
6936
6937 // C++ [over.built]p13:
6938 //
6939 // For every cv-qualified or cv-unqualified object type T
6940 // there exist candidate operator functions of the form
6941 //
6942 // T* operator+(T*, ptrdiff_t);
6943 // T& operator[](T*, ptrdiff_t); [BELOW]
6944 // T* operator-(T*, ptrdiff_t);
6945 // T* operator+(ptrdiff_t, T*);
6946 // T& operator[](ptrdiff_t, T*); [BELOW]
6947 //
6948 // C++ [over.built]p14:
6949 //
6950 // For every T, where T is a pointer to object type, there
6951 // exist candidate operator functions of the form
6952 //
6953 // ptrdiff_t operator-(T, T);
6954 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6955 /// Set of (canonical) types that we've already handled.
6956 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6957
6958 for (int Arg = 0; Arg < 2; ++Arg) {
6959 QualType AsymetricParamTypes[2] = {
6960 S.Context.getPointerDiffType(),
6961 S.Context.getPointerDiffType(),
6962 };
6963 for (BuiltinCandidateTypeSet::iterator
6964 Ptr = CandidateTypes[Arg].pointer_begin(),
6965 PtrEnd = CandidateTypes[Arg].pointer_end();
6966 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006967 QualType PointeeTy = (*Ptr)->getPointeeType();
6968 if (!PointeeTy->isObjectType())
6969 continue;
6970
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006971 AsymetricParamTypes[Arg] = *Ptr;
6972 if (Arg == 0 || Op == OO_Plus) {
6973 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6974 // T* operator+(ptrdiff_t, T*);
6975 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6976 CandidateSet);
6977 }
6978 if (Op == OO_Minus) {
6979 // ptrdiff_t operator-(T, T);
6980 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6981 continue;
6982
6983 QualType ParamTypes[2] = { *Ptr, *Ptr };
6984 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6985 Args, 2, CandidateSet);
6986 }
6987 }
6988 }
6989 }
6990
6991 // C++ [over.built]p12:
6992 //
6993 // For every pair of promoted arithmetic types L and R, there
6994 // exist candidate operator functions of the form
6995 //
6996 // LR operator*(L, R);
6997 // LR operator/(L, R);
6998 // LR operator+(L, R);
6999 // LR operator-(L, R);
7000 // bool operator<(L, R);
7001 // bool operator>(L, R);
7002 // bool operator<=(L, R);
7003 // bool operator>=(L, R);
7004 // bool operator==(L, R);
7005 // bool operator!=(L, R);
7006 //
7007 // where LR is the result of the usual arithmetic conversions
7008 // between types L and R.
7009 //
7010 // C++ [over.built]p24:
7011 //
7012 // For every pair of promoted arithmetic types L and R, there exist
7013 // candidate operator functions of the form
7014 //
7015 // LR operator?(bool, L, R);
7016 //
7017 // where LR is the result of the usual arithmetic conversions
7018 // between types L and R.
7019 // Our candidates ignore the first parameter.
7020 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007021 if (!HasArithmeticOrEnumeralCandidateType)
7022 return;
7023
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007024 for (unsigned Left = FirstPromotedArithmeticType;
7025 Left < LastPromotedArithmeticType; ++Left) {
7026 for (unsigned Right = FirstPromotedArithmeticType;
7027 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007028 QualType LandR[2] = { getArithmeticType(Left),
7029 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007030 QualType Result =
7031 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007032 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007033 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7034 }
7035 }
7036
7037 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
7038 // conditional operator for vector types.
7039 for (BuiltinCandidateTypeSet::iterator
7040 Vec1 = CandidateTypes[0].vector_begin(),
7041 Vec1End = CandidateTypes[0].vector_end();
7042 Vec1 != Vec1End; ++Vec1) {
7043 for (BuiltinCandidateTypeSet::iterator
7044 Vec2 = CandidateTypes[1].vector_begin(),
7045 Vec2End = CandidateTypes[1].vector_end();
7046 Vec2 != Vec2End; ++Vec2) {
7047 QualType LandR[2] = { *Vec1, *Vec2 };
7048 QualType Result = S.Context.BoolTy;
7049 if (!isComparison) {
7050 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7051 Result = *Vec1;
7052 else
7053 Result = *Vec2;
7054 }
7055
7056 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7057 }
7058 }
7059 }
7060
7061 // C++ [over.built]p17:
7062 //
7063 // For every pair of promoted integral types L and R, there
7064 // exist candidate operator functions of the form
7065 //
7066 // LR operator%(L, R);
7067 // LR operator&(L, R);
7068 // LR operator^(L, R);
7069 // LR operator|(L, R);
7070 // L operator<<(L, R);
7071 // L operator>>(L, R);
7072 //
7073 // where LR is the result of the usual arithmetic conversions
7074 // between types L and R.
7075 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007076 if (!HasArithmeticOrEnumeralCandidateType)
7077 return;
7078
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007079 for (unsigned Left = FirstPromotedIntegralType;
7080 Left < LastPromotedIntegralType; ++Left) {
7081 for (unsigned Right = FirstPromotedIntegralType;
7082 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007083 QualType LandR[2] = { getArithmeticType(Left),
7084 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007085 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7086 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007087 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007088 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7089 }
7090 }
7091 }
7092
7093 // C++ [over.built]p20:
7094 //
7095 // For every pair (T, VQ), where T is an enumeration or
7096 // pointer to member type and VQ is either volatile or
7097 // empty, there exist candidate operator functions of the form
7098 //
7099 // VQ T& operator=(VQ T&, T);
7100 void addAssignmentMemberPointerOrEnumeralOverloads() {
7101 /// Set of (canonical) types that we've already handled.
7102 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7103
7104 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7105 for (BuiltinCandidateTypeSet::iterator
7106 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7107 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7108 Enum != EnumEnd; ++Enum) {
7109 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7110 continue;
7111
7112 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7113 CandidateSet);
7114 }
7115
7116 for (BuiltinCandidateTypeSet::iterator
7117 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7118 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7119 MemPtr != MemPtrEnd; ++MemPtr) {
7120 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7121 continue;
7122
7123 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7124 CandidateSet);
7125 }
7126 }
7127 }
7128
7129 // C++ [over.built]p19:
7130 //
7131 // For every pair (T, VQ), where T is any type and VQ is either
7132 // volatile or empty, there exist candidate operator functions
7133 // of the form
7134 //
7135 // T*VQ& operator=(T*VQ&, T*);
7136 //
7137 // C++ [over.built]p21:
7138 //
7139 // For every pair (T, VQ), where T is a cv-qualified or
7140 // cv-unqualified object type and VQ is either volatile or
7141 // empty, there exist candidate operator functions of the form
7142 //
7143 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7144 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7145 void addAssignmentPointerOverloads(bool isEqualOp) {
7146 /// Set of (canonical) types that we've already handled.
7147 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7148
7149 for (BuiltinCandidateTypeSet::iterator
7150 Ptr = CandidateTypes[0].pointer_begin(),
7151 PtrEnd = CandidateTypes[0].pointer_end();
7152 Ptr != PtrEnd; ++Ptr) {
7153 // If this is operator=, keep track of the builtin candidates we added.
7154 if (isEqualOp)
7155 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007156 else if (!(*Ptr)->getPointeeType()->isObjectType())
7157 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007158
7159 // non-volatile version
7160 QualType ParamTypes[2] = {
7161 S.Context.getLValueReferenceType(*Ptr),
7162 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7163 };
7164 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7165 /*IsAssigmentOperator=*/ isEqualOp);
7166
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007167 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7168 VisibleTypeConversionsQuals.hasVolatile();
7169 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007170 // volatile version
7171 ParamTypes[0] =
7172 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7173 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7174 /*IsAssigmentOperator=*/isEqualOp);
7175 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007176
7177 if (!(*Ptr).isRestrictQualified() &&
7178 VisibleTypeConversionsQuals.hasRestrict()) {
7179 // restrict version
7180 ParamTypes[0]
7181 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7182 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7183 /*IsAssigmentOperator=*/isEqualOp);
7184
7185 if (NeedVolatile) {
7186 // volatile restrict version
7187 ParamTypes[0]
7188 = S.Context.getLValueReferenceType(
7189 S.Context.getCVRQualifiedType(*Ptr,
7190 (Qualifiers::Volatile |
7191 Qualifiers::Restrict)));
7192 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7193 CandidateSet,
7194 /*IsAssigmentOperator=*/isEqualOp);
7195 }
7196 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007197 }
7198
7199 if (isEqualOp) {
7200 for (BuiltinCandidateTypeSet::iterator
7201 Ptr = CandidateTypes[1].pointer_begin(),
7202 PtrEnd = CandidateTypes[1].pointer_end();
7203 Ptr != PtrEnd; ++Ptr) {
7204 // Make sure we don't add the same candidate twice.
7205 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7206 continue;
7207
Chandler Carruth6df868e2010-12-12 08:17:55 +00007208 QualType ParamTypes[2] = {
7209 S.Context.getLValueReferenceType(*Ptr),
7210 *Ptr,
7211 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007212
7213 // non-volatile version
7214 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7215 /*IsAssigmentOperator=*/true);
7216
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007217 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7218 VisibleTypeConversionsQuals.hasVolatile();
7219 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007220 // volatile version
7221 ParamTypes[0] =
7222 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007223 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7224 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007225 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007226
7227 if (!(*Ptr).isRestrictQualified() &&
7228 VisibleTypeConversionsQuals.hasRestrict()) {
7229 // restrict version
7230 ParamTypes[0]
7231 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7232 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7233 CandidateSet, /*IsAssigmentOperator=*/true);
7234
7235 if (NeedVolatile) {
7236 // volatile restrict version
7237 ParamTypes[0]
7238 = S.Context.getLValueReferenceType(
7239 S.Context.getCVRQualifiedType(*Ptr,
7240 (Qualifiers::Volatile |
7241 Qualifiers::Restrict)));
7242 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7243 CandidateSet, /*IsAssigmentOperator=*/true);
7244
7245 }
7246 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007247 }
7248 }
7249 }
7250
7251 // C++ [over.built]p18:
7252 //
7253 // For every triple (L, VQ, R), where L is an arithmetic type,
7254 // VQ is either volatile or empty, and R is a promoted
7255 // arithmetic type, there exist candidate operator functions of
7256 // the form
7257 //
7258 // VQ L& operator=(VQ L&, R);
7259 // VQ L& operator*=(VQ L&, R);
7260 // VQ L& operator/=(VQ L&, R);
7261 // VQ L& operator+=(VQ L&, R);
7262 // VQ L& operator-=(VQ L&, R);
7263 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007264 if (!HasArithmeticOrEnumeralCandidateType)
7265 return;
7266
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007267 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7268 for (unsigned Right = FirstPromotedArithmeticType;
7269 Right < LastPromotedArithmeticType; ++Right) {
7270 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007271 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007272
7273 // Add this built-in operator as a candidate (VQ is empty).
7274 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007275 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007276 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7277 /*IsAssigmentOperator=*/isEqualOp);
7278
7279 // Add this built-in operator as a candidate (VQ is 'volatile').
7280 if (VisibleTypeConversionsQuals.hasVolatile()) {
7281 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007282 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007283 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007284 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7285 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007286 /*IsAssigmentOperator=*/isEqualOp);
7287 }
7288 }
7289 }
7290
7291 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7292 for (BuiltinCandidateTypeSet::iterator
7293 Vec1 = CandidateTypes[0].vector_begin(),
7294 Vec1End = CandidateTypes[0].vector_end();
7295 Vec1 != Vec1End; ++Vec1) {
7296 for (BuiltinCandidateTypeSet::iterator
7297 Vec2 = CandidateTypes[1].vector_begin(),
7298 Vec2End = CandidateTypes[1].vector_end();
7299 Vec2 != Vec2End; ++Vec2) {
7300 QualType ParamTypes[2];
7301 ParamTypes[1] = *Vec2;
7302 // Add this built-in operator as a candidate (VQ is empty).
7303 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7305 /*IsAssigmentOperator=*/isEqualOp);
7306
7307 // Add this built-in operator as a candidate (VQ is 'volatile').
7308 if (VisibleTypeConversionsQuals.hasVolatile()) {
7309 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7310 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007311 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7312 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007313 /*IsAssigmentOperator=*/isEqualOp);
7314 }
7315 }
7316 }
7317 }
7318
7319 // C++ [over.built]p22:
7320 //
7321 // For every triple (L, VQ, R), where L is an integral type, VQ
7322 // is either volatile or empty, and R is a promoted integral
7323 // type, there exist candidate operator functions of the form
7324 //
7325 // VQ L& operator%=(VQ L&, R);
7326 // VQ L& operator<<=(VQ L&, R);
7327 // VQ L& operator>>=(VQ L&, R);
7328 // VQ L& operator&=(VQ L&, R);
7329 // VQ L& operator^=(VQ L&, R);
7330 // VQ L& operator|=(VQ L&, R);
7331 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007332 if (!HasArithmeticOrEnumeralCandidateType)
7333 return;
7334
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007335 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7336 for (unsigned Right = FirstPromotedIntegralType;
7337 Right < LastPromotedIntegralType; ++Right) {
7338 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007339 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007340
7341 // Add this built-in operator as a candidate (VQ is empty).
7342 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007343 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007344 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7345 if (VisibleTypeConversionsQuals.hasVolatile()) {
7346 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007347 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007348 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7349 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7350 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7351 CandidateSet);
7352 }
7353 }
7354 }
7355 }
7356
7357 // C++ [over.operator]p23:
7358 //
7359 // There also exist candidate operator functions of the form
7360 //
7361 // bool operator!(bool);
7362 // bool operator&&(bool, bool);
7363 // bool operator||(bool, bool);
7364 void addExclaimOverload() {
7365 QualType ParamTy = S.Context.BoolTy;
7366 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7367 /*IsAssignmentOperator=*/false,
7368 /*NumContextualBoolArguments=*/1);
7369 }
7370 void addAmpAmpOrPipePipeOverload() {
7371 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7372 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7373 /*IsAssignmentOperator=*/false,
7374 /*NumContextualBoolArguments=*/2);
7375 }
7376
7377 // C++ [over.built]p13:
7378 //
7379 // For every cv-qualified or cv-unqualified object type T there
7380 // exist candidate operator functions of the form
7381 //
7382 // T* operator+(T*, ptrdiff_t); [ABOVE]
7383 // T& operator[](T*, ptrdiff_t);
7384 // T* operator-(T*, ptrdiff_t); [ABOVE]
7385 // T* operator+(ptrdiff_t, T*); [ABOVE]
7386 // T& operator[](ptrdiff_t, T*);
7387 void addSubscriptOverloads() {
7388 for (BuiltinCandidateTypeSet::iterator
7389 Ptr = CandidateTypes[0].pointer_begin(),
7390 PtrEnd = CandidateTypes[0].pointer_end();
7391 Ptr != PtrEnd; ++Ptr) {
7392 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7393 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007394 if (!PointeeType->isObjectType())
7395 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007396
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007397 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7398
7399 // T& operator[](T*, ptrdiff_t)
7400 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7401 }
7402
7403 for (BuiltinCandidateTypeSet::iterator
7404 Ptr = CandidateTypes[1].pointer_begin(),
7405 PtrEnd = CandidateTypes[1].pointer_end();
7406 Ptr != PtrEnd; ++Ptr) {
7407 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7408 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007409 if (!PointeeType->isObjectType())
7410 continue;
7411
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007412 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7413
7414 // T& operator[](ptrdiff_t, T*)
7415 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7416 }
7417 }
7418
7419 // C++ [over.built]p11:
7420 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7421 // C1 is the same type as C2 or is a derived class of C2, T is an object
7422 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7423 // there exist candidate operator functions of the form
7424 //
7425 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7426 //
7427 // where CV12 is the union of CV1 and CV2.
7428 void addArrowStarOverloads() {
7429 for (BuiltinCandidateTypeSet::iterator
7430 Ptr = CandidateTypes[0].pointer_begin(),
7431 PtrEnd = CandidateTypes[0].pointer_end();
7432 Ptr != PtrEnd; ++Ptr) {
7433 QualType C1Ty = (*Ptr);
7434 QualType C1;
7435 QualifierCollector Q1;
7436 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7437 if (!isa<RecordType>(C1))
7438 continue;
7439 // heuristic to reduce number of builtin candidates in the set.
7440 // Add volatile/restrict version only if there are conversions to a
7441 // volatile/restrict type.
7442 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7443 continue;
7444 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7445 continue;
7446 for (BuiltinCandidateTypeSet::iterator
7447 MemPtr = CandidateTypes[1].member_pointer_begin(),
7448 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7449 MemPtr != MemPtrEnd; ++MemPtr) {
7450 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7451 QualType C2 = QualType(mptr->getClass(), 0);
7452 C2 = C2.getUnqualifiedType();
7453 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7454 break;
7455 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7456 // build CV12 T&
7457 QualType T = mptr->getPointeeType();
7458 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7459 T.isVolatileQualified())
7460 continue;
7461 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7462 T.isRestrictQualified())
7463 continue;
7464 T = Q1.apply(S.Context, T);
7465 QualType ResultTy = S.Context.getLValueReferenceType(T);
7466 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7467 }
7468 }
7469 }
7470
7471 // Note that we don't consider the first argument, since it has been
7472 // contextually converted to bool long ago. The candidates below are
7473 // therefore added as binary.
7474 //
7475 // C++ [over.built]p25:
7476 // For every type T, where T is a pointer, pointer-to-member, or scoped
7477 // enumeration type, there exist candidate operator functions of the form
7478 //
7479 // T operator?(bool, T, T);
7480 //
7481 void addConditionalOperatorOverloads() {
7482 /// Set of (canonical) types that we've already handled.
7483 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7484
7485 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7486 for (BuiltinCandidateTypeSet::iterator
7487 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7488 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7489 Ptr != PtrEnd; ++Ptr) {
7490 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7491 continue;
7492
7493 QualType ParamTypes[2] = { *Ptr, *Ptr };
7494 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7495 }
7496
7497 for (BuiltinCandidateTypeSet::iterator
7498 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7499 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7500 MemPtr != MemPtrEnd; ++MemPtr) {
7501 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7502 continue;
7503
7504 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7505 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7506 }
7507
Richard Smith80ad52f2013-01-02 11:42:31 +00007508 if (S.getLangOpts().CPlusPlus11) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007509 for (BuiltinCandidateTypeSet::iterator
7510 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7511 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7512 Enum != EnumEnd; ++Enum) {
7513 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7514 continue;
7515
7516 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7517 continue;
7518
7519 QualType ParamTypes[2] = { *Enum, *Enum };
7520 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7521 }
7522 }
7523 }
7524 }
7525};
7526
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007527} // end anonymous namespace
7528
7529/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7530/// operator overloads to the candidate set (C++ [over.built]), based
7531/// on the operator @p Op and the arguments given. For example, if the
7532/// operator is a binary '+', this routine might add "int
7533/// operator+(int, int)" to cover integer addition.
7534void
7535Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7536 SourceLocation OpLoc,
7537 Expr **Args, unsigned NumArgs,
7538 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007539 // Find all of the types that the arguments can convert to, but only
7540 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007541 // that make use of these types. Also record whether we encounter non-record
7542 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007543 Qualifiers VisibleTypeConversionsQuals;
7544 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007545 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7546 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007547
7548 bool HasNonRecordCandidateType = false;
7549 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007550 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007551 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7552 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7553 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7554 OpLoc,
7555 true,
7556 (Op == OO_Exclaim ||
7557 Op == OO_AmpAmp ||
7558 Op == OO_PipePipe),
7559 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007560 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7561 CandidateTypes[ArgIdx].hasNonRecordTypes();
7562 HasArithmeticOrEnumeralCandidateType =
7563 HasArithmeticOrEnumeralCandidateType ||
7564 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007565 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007566
Chandler Carruth6a577462010-12-13 01:44:01 +00007567 // Exit early when no non-record types have been added to the candidate set
7568 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007569 //
7570 // We can't exit early for !, ||, or &&, since there we have always have
7571 // 'bool' overloads.
7572 if (!HasNonRecordCandidateType &&
7573 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007574 return;
7575
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007576 // Setup an object to manage the common state for building overloads.
7577 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7578 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007579 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007580 CandidateTypes, CandidateSet);
7581
7582 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007583 switch (Op) {
7584 case OO_None:
7585 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007586 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007587
Chandler Carruthabb71842010-12-12 08:51:33 +00007588 case OO_New:
7589 case OO_Delete:
7590 case OO_Array_New:
7591 case OO_Array_Delete:
7592 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007593 llvm_unreachable(
7594 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007595
7596 case OO_Comma:
7597 case OO_Arrow:
7598 // C++ [over.match.oper]p3:
7599 // -- For the operator ',', the unary operator '&', or the
7600 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007601 break;
7602
7603 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007604 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007605 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007606 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007607
7608 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007609 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007610 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007611 } else {
7612 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7613 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7614 }
Douglas Gregor74253732008-11-19 15:42:04 +00007615 break;
7616
Chandler Carruthabb71842010-12-12 08:51:33 +00007617 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007618 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007619 OpBuilder.addUnaryStarPointerOverloads();
7620 else
7621 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7622 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007623
Chandler Carruthabb71842010-12-12 08:51:33 +00007624 case OO_Slash:
7625 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007626 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007627
7628 case OO_PlusPlus:
7629 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007630 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7631 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007632 break;
7633
Douglas Gregor19b7b152009-08-24 13:43:27 +00007634 case OO_EqualEqual:
7635 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007636 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007637 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007638
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007639 case OO_Less:
7640 case OO_Greater:
7641 case OO_LessEqual:
7642 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007643 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007644 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7645 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007646
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007647 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007648 case OO_Caret:
7649 case OO_Pipe:
7650 case OO_LessLess:
7651 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007652 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007653 break;
7654
Chandler Carruthabb71842010-12-12 08:51:33 +00007655 case OO_Amp: // '&' is either unary or binary
7656 if (NumArgs == 1)
7657 // C++ [over.match.oper]p3:
7658 // -- For the operator ',', the unary operator '&', or the
7659 // operator '->', the built-in candidates set is empty.
7660 break;
7661
7662 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7663 break;
7664
7665 case OO_Tilde:
7666 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7667 break;
7668
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007669 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007670 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007671 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007672
7673 case OO_PlusEqual:
7674 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007675 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007676 // Fall through.
7677
7678 case OO_StarEqual:
7679 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007680 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007681 break;
7682
7683 case OO_PercentEqual:
7684 case OO_LessLessEqual:
7685 case OO_GreaterGreaterEqual:
7686 case OO_AmpEqual:
7687 case OO_CaretEqual:
7688 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007689 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007690 break;
7691
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007692 case OO_Exclaim:
7693 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007694 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007695
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007696 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007697 case OO_PipePipe:
7698 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007699 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007700
7701 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007702 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007703 break;
7704
7705 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007706 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007707 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007708
7709 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007710 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007711 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7712 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007713 }
7714}
7715
Douglas Gregorfa047642009-02-04 00:32:51 +00007716/// \brief Add function candidates found via argument-dependent lookup
7717/// to the set of overloading candidates.
7718///
7719/// This routine performs argument-dependent name lookup based on the
7720/// given function name (which may also be an operator name) and adds
7721/// all of the overload candidates found by ADL to the overload
7722/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007723void
Douglas Gregorfa047642009-02-04 00:32:51 +00007724Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007725 bool Operator, SourceLocation Loc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00007726 ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007727 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007728 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007729 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007730 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007731
John McCalla113e722010-01-26 06:04:06 +00007732 // FIXME: This approach for uniquing ADL results (and removing
7733 // redundant candidates from the set) relies on pointer-equality,
7734 // which means we need to key off the canonical decl. However,
7735 // always going back to the canonical decl might not get us the
7736 // right set of default arguments. What default arguments are
7737 // we supposed to consider on ADL candidates, anyway?
7738
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007739 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007740 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007741
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007742 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007743 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7744 CandEnd = CandidateSet.end();
7745 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007746 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007747 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007748 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007749 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007750 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007751
7752 // For each of the ADL candidates we found, add it to the overload
7753 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007754 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007755 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007756 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007757 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007758 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007759
Ahmed Charles13a140c2012-02-25 11:00:22 +00007760 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7761 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007762 } else
John McCall6e266892010-01-26 03:27:55 +00007763 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007764 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007765 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007766 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007767}
7768
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007769/// isBetterOverloadCandidate - Determines whether the first overload
7770/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007771bool
John McCall120d63c2010-08-24 20:38:10 +00007772isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007773 const OverloadCandidate &Cand1,
7774 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007775 SourceLocation Loc,
7776 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007777 // Define viable functions to be better candidates than non-viable
7778 // functions.
7779 if (!Cand2.Viable)
7780 return Cand1.Viable;
7781 else if (!Cand1.Viable)
7782 return false;
7783
Douglas Gregor88a35142008-12-22 05:46:06 +00007784 // C++ [over.match.best]p1:
7785 //
7786 // -- if F is a static member function, ICS1(F) is defined such
7787 // that ICS1(F) is neither better nor worse than ICS1(G) for
7788 // any function G, and, symmetrically, ICS1(G) is neither
7789 // better nor worse than ICS1(F).
7790 unsigned StartArg = 0;
7791 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7792 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007793
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007794 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007795 // A viable function F1 is defined to be a better function than another
7796 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007797 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007798 unsigned NumArgs = Cand1.NumConversions;
7799 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007800 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007801 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007802 switch (CompareImplicitConversionSequences(S,
7803 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007804 Cand2.Conversions[ArgIdx])) {
7805 case ImplicitConversionSequence::Better:
7806 // Cand1 has a better conversion sequence.
7807 HasBetterConversion = true;
7808 break;
7809
7810 case ImplicitConversionSequence::Worse:
7811 // Cand1 can't be better than Cand2.
7812 return false;
7813
7814 case ImplicitConversionSequence::Indistinguishable:
7815 // Do nothing.
7816 break;
7817 }
7818 }
7819
Mike Stump1eb44332009-09-09 15:08:12 +00007820 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007821 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007822 if (HasBetterConversion)
7823 return true;
7824
Mike Stump1eb44332009-09-09 15:08:12 +00007825 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007826 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007827 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007828 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7829 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007830
7831 // -- F1 and F2 are function template specializations, and the function
7832 // template for F1 is more specialized than the template for F2
7833 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007834 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007835 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007836 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007837 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007838 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7839 Cand2.Function->getPrimaryTemplate(),
7840 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007841 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007842 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007843 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007844 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007845 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007846
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007847 // -- the context is an initialization by user-defined conversion
7848 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7849 // from the return type of F1 to the destination type (i.e.,
7850 // the type of the entity being initialized) is a better
7851 // conversion sequence than the standard conversion sequence
7852 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007853 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007854 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007855 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007856 // First check whether we prefer one of the conversion functions over the
7857 // other. This only distinguishes the results in non-standard, extension
7858 // cases such as the conversion from a lambda closure type to a function
7859 // pointer or block.
7860 ImplicitConversionSequence::CompareKind FuncResult
7861 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7862 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7863 return FuncResult;
7864
John McCall120d63c2010-08-24 20:38:10 +00007865 switch (CompareStandardConversionSequences(S,
7866 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007867 Cand2.FinalConversion)) {
7868 case ImplicitConversionSequence::Better:
7869 // Cand1 has a better conversion sequence.
7870 return true;
7871
7872 case ImplicitConversionSequence::Worse:
7873 // Cand1 can't be better than Cand2.
7874 return false;
7875
7876 case ImplicitConversionSequence::Indistinguishable:
7877 // Do nothing
7878 break;
7879 }
7880 }
7881
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007882 return false;
7883}
7884
Mike Stump1eb44332009-09-09 15:08:12 +00007885/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007886/// within an overload candidate set.
7887///
James Dennettefce31f2012-06-22 08:10:18 +00007888/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007889/// which overload resolution occurs.
7890///
James Dennettefce31f2012-06-22 08:10:18 +00007891/// \param Best If overload resolution was successful or found a deleted
7892/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007893///
7894/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007895OverloadingResult
7896OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007897 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007898 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007899 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007900 Best = end();
7901 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7902 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007903 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007904 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007905 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007906 }
7907
7908 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007909 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007910 return OR_No_Viable_Function;
7911
7912 // Make sure that this function is better than every other viable
7913 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007914 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007915 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007916 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007917 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007918 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007919 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007920 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007921 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007922 }
Mike Stump1eb44332009-09-09 15:08:12 +00007923
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007924 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007925 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007926 (Best->Function->isDeleted() ||
7927 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007928 return OR_Deleted;
7929
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007930 return OR_Success;
7931}
7932
John McCall3c80f572010-01-12 02:15:36 +00007933namespace {
7934
7935enum OverloadCandidateKind {
7936 oc_function,
7937 oc_method,
7938 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007939 oc_function_template,
7940 oc_method_template,
7941 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007942 oc_implicit_default_constructor,
7943 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007944 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007945 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007946 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007947 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007948};
7949
John McCall220ccbf2010-01-13 00:25:19 +00007950OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7951 FunctionDecl *Fn,
7952 std::string &Description) {
7953 bool isTemplate = false;
7954
7955 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7956 isTemplate = true;
7957 Description = S.getTemplateArgumentBindingsText(
7958 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7959 }
John McCallb1622a12010-01-06 09:43:14 +00007960
7961 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007962 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007963 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007964
Sebastian Redlf677ea32011-02-05 19:23:19 +00007965 if (Ctor->getInheritedConstructor())
7966 return oc_implicit_inherited_constructor;
7967
Sean Hunt82713172011-05-25 23:16:36 +00007968 if (Ctor->isDefaultConstructor())
7969 return oc_implicit_default_constructor;
7970
7971 if (Ctor->isMoveConstructor())
7972 return oc_implicit_move_constructor;
7973
7974 assert(Ctor->isCopyConstructor() &&
7975 "unexpected sort of implicit constructor");
7976 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007977 }
7978
7979 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7980 // This actually gets spelled 'candidate function' for now, but
7981 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007982 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007983 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007984
Sean Hunt82713172011-05-25 23:16:36 +00007985 if (Meth->isMoveAssignmentOperator())
7986 return oc_implicit_move_assignment;
7987
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007988 if (Meth->isCopyAssignmentOperator())
7989 return oc_implicit_copy_assignment;
7990
7991 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7992 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007993 }
7994
John McCall220ccbf2010-01-13 00:25:19 +00007995 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007996}
7997
Sebastian Redlf677ea32011-02-05 19:23:19 +00007998void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7999 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
8000 if (!Ctor) return;
8001
8002 Ctor = Ctor->getInheritedConstructor();
8003 if (!Ctor) return;
8004
8005 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
8006}
8007
John McCall3c80f572010-01-12 02:15:36 +00008008} // end anonymous namespace
8009
8010// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00008011void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00008012 std::string FnDesc;
8013 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00008014 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
8015 << (unsigned) K << FnDesc;
8016 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
8017 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008018 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00008019}
8020
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008021//Notes the location of all overload candidates designated through
8022// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00008023void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008024 assert(OverloadedExpr->getType() == Context.OverloadTy);
8025
8026 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
8027 OverloadExpr *OvlExpr = Ovl.Expression;
8028
8029 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8030 IEnd = OvlExpr->decls_end();
8031 I != IEnd; ++I) {
8032 if (FunctionTemplateDecl *FunTmpl =
8033 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008034 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008035 } else if (FunctionDecl *Fun
8036 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00008037 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008038 }
8039 }
8040}
8041
John McCall1d318332010-01-12 00:44:57 +00008042/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8043/// "lead" diagnostic; it will be given two arguments, the source and
8044/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008045void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8046 Sema &S,
8047 SourceLocation CaretLoc,
8048 const PartialDiagnostic &PDiag) const {
8049 S.Diag(CaretLoc, PDiag)
8050 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008051 // FIXME: The note limiting machinery is borrowed from
8052 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8053 // refactoring here.
8054 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8055 unsigned CandsShown = 0;
8056 AmbiguousConversionSequence::const_iterator I, E;
8057 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8058 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8059 break;
8060 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008061 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008062 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008063 if (I != E)
8064 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008065}
8066
John McCall1d318332010-01-12 00:44:57 +00008067namespace {
8068
John McCalladbb8f82010-01-13 09:16:55 +00008069void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8070 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8071 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008072 assert(Cand->Function && "for now, candidate must be a function");
8073 FunctionDecl *Fn = Cand->Function;
8074
8075 // There's a conversion slot for the object argument if this is a
8076 // non-constructor method. Note that 'I' corresponds the
8077 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008078 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008079 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008080 if (I == 0)
8081 isObjectArgument = true;
8082 else
8083 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008084 }
8085
John McCall220ccbf2010-01-13 00:25:19 +00008086 std::string FnDesc;
8087 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8088
John McCalladbb8f82010-01-13 09:16:55 +00008089 Expr *FromExpr = Conv.Bad.FromExpr;
8090 QualType FromTy = Conv.Bad.getFromType();
8091 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008092
John McCall5920dbb2010-02-02 02:42:52 +00008093 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008094 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008095 Expr *E = FromExpr->IgnoreParens();
8096 if (isa<UnaryOperator>(E))
8097 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008098 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008099
8100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8101 << (unsigned) FnKind << FnDesc
8102 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8103 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008104 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008105 return;
8106 }
8107
John McCall258b2032010-01-23 08:10:49 +00008108 // Do some hand-waving analysis to see if the non-viability is due
8109 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008110 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8111 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8112 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8113 CToTy = RT->getPointeeType();
8114 else {
8115 // TODO: detect and diagnose the full richness of const mismatches.
8116 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8117 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8118 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8119 }
8120
8121 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8122 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008123 Qualifiers FromQs = CFromTy.getQualifiers();
8124 Qualifiers ToQs = CToTy.getQualifiers();
8125
8126 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8127 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8128 << (unsigned) FnKind << FnDesc
8129 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8130 << FromTy
8131 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8132 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008133 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008134 return;
8135 }
8136
John McCallf85e1932011-06-15 23:02:42 +00008137 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008138 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008139 << (unsigned) FnKind << FnDesc
8140 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8141 << FromTy
8142 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8143 << (unsigned) isObjectArgument << I+1;
8144 MaybeEmitInheritedConstructorNote(S, Fn);
8145 return;
8146 }
8147
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008148 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8149 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8150 << (unsigned) FnKind << FnDesc
8151 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8152 << FromTy
8153 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8154 << (unsigned) isObjectArgument << I+1;
8155 MaybeEmitInheritedConstructorNote(S, Fn);
8156 return;
8157 }
8158
John McCall651f3ee2010-01-14 03:28:57 +00008159 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8160 assert(CVR && "unexpected qualifiers mismatch");
8161
8162 if (isObjectArgument) {
8163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8164 << (unsigned) FnKind << FnDesc
8165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8166 << FromTy << (CVR - 1);
8167 } else {
8168 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8169 << (unsigned) FnKind << FnDesc
8170 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8171 << FromTy << (CVR - 1) << I+1;
8172 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008173 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008174 return;
8175 }
8176
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008177 // Special diagnostic for failure to convert an initializer list, since
8178 // telling the user that it has type void is not useful.
8179 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8180 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8181 << (unsigned) FnKind << FnDesc
8182 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8183 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8184 MaybeEmitInheritedConstructorNote(S, Fn);
8185 return;
8186 }
8187
John McCall258b2032010-01-23 08:10:49 +00008188 // Diagnose references or pointers to incomplete types differently,
8189 // since it's far from impossible that the incompleteness triggered
8190 // the failure.
8191 QualType TempFromTy = FromTy.getNonReferenceType();
8192 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8193 TempFromTy = PTy->getPointeeType();
8194 if (TempFromTy->isIncompleteType()) {
8195 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8196 << (unsigned) FnKind << FnDesc
8197 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8198 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008199 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008200 return;
8201 }
8202
Douglas Gregor85789812010-06-30 23:01:39 +00008203 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008204 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008205 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8206 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8207 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8208 FromPtrTy->getPointeeType()) &&
8209 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8210 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008211 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008212 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008213 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008214 }
8215 } else if (const ObjCObjectPointerType *FromPtrTy
8216 = FromTy->getAs<ObjCObjectPointerType>()) {
8217 if (const ObjCObjectPointerType *ToPtrTy
8218 = ToTy->getAs<ObjCObjectPointerType>())
8219 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8220 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8221 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8222 FromPtrTy->getPointeeType()) &&
8223 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008224 BaseToDerivedConversion = 2;
8225 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008226 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8227 !FromTy->isIncompleteType() &&
8228 !ToRefTy->getPointeeType()->isIncompleteType() &&
8229 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8230 BaseToDerivedConversion = 3;
8231 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8232 ToTy.getNonReferenceType().getCanonicalType() ==
8233 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008234 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8235 << (unsigned) FnKind << FnDesc
8236 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8237 << (unsigned) isObjectArgument << I + 1;
8238 MaybeEmitInheritedConstructorNote(S, Fn);
8239 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008240 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008241 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008242
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008243 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008244 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008245 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008246 << (unsigned) FnKind << FnDesc
8247 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008248 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008249 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008250 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008251 return;
8252 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008253
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008254 if (isa<ObjCObjectPointerType>(CFromTy) &&
8255 isa<PointerType>(CToTy)) {
8256 Qualifiers FromQs = CFromTy.getQualifiers();
8257 Qualifiers ToQs = CToTy.getQualifiers();
8258 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8259 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8260 << (unsigned) FnKind << FnDesc
8261 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8262 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8263 MaybeEmitInheritedConstructorNote(S, Fn);
8264 return;
8265 }
8266 }
8267
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008268 // Emit the generic diagnostic and, optionally, add the hints to it.
8269 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8270 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008271 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008272 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8273 << (unsigned) (Cand->Fix.Kind);
8274
8275 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008276 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8277 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008278 FDiag << *HI;
8279 S.Diag(Fn->getLocation(), FDiag);
8280
Sebastian Redlf677ea32011-02-05 19:23:19 +00008281 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008282}
8283
8284void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8285 unsigned NumFormalArgs) {
8286 // TODO: treat calls to a missing default constructor as a special case
8287
8288 FunctionDecl *Fn = Cand->Function;
8289 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8290
8291 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008292
Douglas Gregor439d3c32011-05-05 00:13:13 +00008293 // With invalid overloaded operators, it's possible that we think we
8294 // have an arity mismatch when it fact it looks like we have the
8295 // right number of arguments, because only overloaded operators have
8296 // the weird behavior of overloading member and non-member functions.
8297 // Just don't report anything.
8298 if (Fn->isInvalidDecl() &&
8299 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8300 return;
8301
John McCalladbb8f82010-01-13 09:16:55 +00008302 // at least / at most / exactly
8303 unsigned mode, modeCount;
8304 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008305 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8306 (Cand->FailureKind == ovl_fail_bad_deduction &&
8307 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008308 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008309 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008310 mode = 0; // "at least"
8311 else
8312 mode = 2; // "exactly"
8313 modeCount = MinParams;
8314 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008315 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8316 (Cand->FailureKind == ovl_fail_bad_deduction &&
8317 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008318 if (MinParams != FnTy->getNumArgs())
8319 mode = 1; // "at most"
8320 else
8321 mode = 2; // "exactly"
8322 modeCount = FnTy->getNumArgs();
8323 }
8324
8325 std::string Description;
8326 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8327
Richard Smithf7b80562012-05-11 05:16:41 +00008328 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8330 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8331 << Fn->getParamDecl(0) << NumFormalArgs;
8332 else
8333 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8334 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8335 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008336 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008337}
8338
John McCall342fec42010-02-01 18:53:26 +00008339/// Diagnose a failed template-argument deduction.
8340void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008341 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008342 FunctionDecl *Fn = Cand->Function; // pattern
8343
Douglas Gregora9333192010-05-08 17:41:32 +00008344 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008345 NamedDecl *ParamD;
8346 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8347 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8348 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008349 switch (Cand->DeductionFailure.Result) {
8350 case Sema::TDK_Success:
8351 llvm_unreachable("TDK_success while diagnosing bad deduction");
8352
8353 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008354 assert(ParamD && "no parameter found for incomplete deduction result");
8355 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8356 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008357 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008358 return;
8359 }
8360
John McCall57e97782010-08-05 09:05:08 +00008361 case Sema::TDK_Underqualified: {
8362 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8363 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8364
8365 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8366
8367 // Param will have been canonicalized, but it should just be a
8368 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008369 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008370 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008371 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008372 assert(S.Context.hasSameType(Param, NonCanonParam));
8373
8374 // Arg has also been canonicalized, but there's nothing we can do
8375 // about that. It also doesn't matter as much, because it won't
8376 // have any template parameters in it (because deduction isn't
8377 // done on dependent types).
8378 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8379
8380 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8381 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008382 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008383 return;
8384 }
8385
8386 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008387 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008388 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008389 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008390 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008391 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008392 which = 1;
8393 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008394 which = 2;
8395 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008396
Douglas Gregora9333192010-05-08 17:41:32 +00008397 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008398 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008399 << *Cand->DeductionFailure.getFirstArg()
8400 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008401 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008402 return;
8403 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008404
Douglas Gregorf1a84452010-05-08 19:15:54 +00008405 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008406 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008407 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008408 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008409 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8410 << ParamD->getDeclName();
8411 else {
8412 int index = 0;
8413 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8414 index = TTP->getIndex();
8415 else if (NonTypeTemplateParmDecl *NTTP
8416 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8417 index = NTTP->getIndex();
8418 else
8419 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008420 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008421 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8422 << (index + 1);
8423 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008424 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008425 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008426
Douglas Gregora18592e2010-05-08 18:13:28 +00008427 case Sema::TDK_TooManyArguments:
8428 case Sema::TDK_TooFewArguments:
8429 DiagnoseArityMismatch(S, Cand, NumArgs);
8430 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008431
8432 case Sema::TDK_InstantiationDepth:
8433 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008434 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008435 return;
8436
8437 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008438 // Format the template argument list into the argument string.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008439 SmallString<128> TemplateArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008440 if (TemplateArgumentList *Args =
8441 Cand->DeductionFailure.getTemplateArgumentList()) {
8442 TemplateArgString = " ";
8443 TemplateArgString += S.getTemplateArgumentBindingsText(
8444 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8445 }
8446
Richard Smith4493c0a2012-05-09 05:17:00 +00008447 // If this candidate was disabled by enable_if, say so.
8448 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8449 if (PDiag && PDiag->second.getDiagID() ==
8450 diag::err_typename_nested_not_found_enable_if) {
8451 // FIXME: Use the source range of the condition, and the fully-qualified
8452 // name of the enable_if template. These are both present in PDiag.
8453 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8454 << "'enable_if'" << TemplateArgString;
8455 return;
8456 }
8457
Richard Smithb8590f32012-05-07 09:03:25 +00008458 // Format the SFINAE diagnostic into the argument string.
8459 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8460 // formatted message in another diagnostic.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008461 SmallString<128> SFINAEArgString;
Richard Smithb8590f32012-05-07 09:03:25 +00008462 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008463 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008464 SFINAEArgString = ": ";
8465 R = SourceRange(PDiag->first, PDiag->first);
8466 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8467 }
8468
Douglas Gregorec20f462010-05-08 20:07:26 +00008469 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008470 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008471 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008472 return;
8473 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008474
Richard Smith0efa62f2013-01-31 04:03:12 +00008475 case Sema::TDK_FailedOverloadResolution: {
8476 OverloadExpr::FindResult R =
8477 OverloadExpr::find(Cand->DeductionFailure.getExpr());
8478 S.Diag(Fn->getLocation(),
8479 diag::note_ovl_candidate_failed_overload_resolution)
8480 << R.Expression->getName();
8481 return;
8482 }
8483
Richard Smith29805ca2013-01-31 05:19:49 +00008484 case Sema::TDK_NonDeducedMismatch:
8485 // FIXME: Provide a source location to indicate what we couldn't match.
8486 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_non_deduced_mismatch)
8487 << *Cand->DeductionFailure.getFirstArg()
8488 << *Cand->DeductionFailure.getSecondArg();
8489 return;
8490
John McCall342fec42010-02-01 18:53:26 +00008491 // TODO: diagnose these individually, then kill off
8492 // note_ovl_candidate_bad_deduction, which is uselessly vague.
Richard Smith29805ca2013-01-31 05:19:49 +00008493 case Sema::TDK_MiscellaneousDeductionFailure:
John McCall342fec42010-02-01 18:53:26 +00008494 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008495 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008496 return;
8497 }
8498}
8499
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008500/// CUDA: diagnose an invalid call across targets.
8501void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8502 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8503 FunctionDecl *Callee = Cand->Function;
8504
8505 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8506 CalleeTarget = S.IdentifyCUDATarget(Callee);
8507
8508 std::string FnDesc;
8509 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8510
8511 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8512 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8513}
8514
John McCall342fec42010-02-01 18:53:26 +00008515/// Generates a 'note' diagnostic for an overload candidate. We've
8516/// already generated a primary error at the call site.
8517///
8518/// It really does need to be a single diagnostic with its caret
8519/// pointed at the candidate declaration. Yes, this creates some
8520/// major challenges of technical writing. Yes, this makes pointing
8521/// out problems with specific arguments quite awkward. It's still
8522/// better than generating twenty screens of text for every failed
8523/// overload.
8524///
8525/// It would be great to be able to express per-candidate problems
8526/// more richly for those diagnostic clients that cared, but we'd
8527/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008528void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008529 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008530 FunctionDecl *Fn = Cand->Function;
8531
John McCall81201622010-01-08 04:41:39 +00008532 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008533 if (Cand->Viable && (Fn->isDeleted() ||
8534 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008535 std::string FnDesc;
8536 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008537
8538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008539 << FnKind << FnDesc
8540 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008541 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008542 return;
John McCall81201622010-01-08 04:41:39 +00008543 }
8544
John McCall220ccbf2010-01-13 00:25:19 +00008545 // We don't really have anything else to say about viable candidates.
8546 if (Cand->Viable) {
8547 S.NoteOverloadCandidate(Fn);
8548 return;
8549 }
John McCall1d318332010-01-12 00:44:57 +00008550
John McCalladbb8f82010-01-13 09:16:55 +00008551 switch (Cand->FailureKind) {
8552 case ovl_fail_too_many_arguments:
8553 case ovl_fail_too_few_arguments:
8554 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008555
John McCalladbb8f82010-01-13 09:16:55 +00008556 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008557 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008558
John McCall717e8912010-01-23 05:17:32 +00008559 case ovl_fail_trivial_conversion:
8560 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008561 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008562 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008563
John McCallb1bdc622010-02-25 01:37:24 +00008564 case ovl_fail_bad_conversion: {
8565 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008566 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008567 if (Cand->Conversions[I].isBad())
8568 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008569
John McCalladbb8f82010-01-13 09:16:55 +00008570 // FIXME: this currently happens when we're called from SemaInit
8571 // when user-conversion overload fails. Figure out how to handle
8572 // those conditions and diagnose them well.
8573 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008574 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008575
8576 case ovl_fail_bad_target:
8577 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008578 }
John McCalla1d7d622010-01-08 00:58:21 +00008579}
8580
8581void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8582 // Desugar the type of the surrogate down to a function type,
8583 // retaining as many typedefs as possible while still showing
8584 // the function type (and, therefore, its parameter types).
8585 QualType FnType = Cand->Surrogate->getConversionType();
8586 bool isLValueReference = false;
8587 bool isRValueReference = false;
8588 bool isPointer = false;
8589 if (const LValueReferenceType *FnTypeRef =
8590 FnType->getAs<LValueReferenceType>()) {
8591 FnType = FnTypeRef->getPointeeType();
8592 isLValueReference = true;
8593 } else if (const RValueReferenceType *FnTypeRef =
8594 FnType->getAs<RValueReferenceType>()) {
8595 FnType = FnTypeRef->getPointeeType();
8596 isRValueReference = true;
8597 }
8598 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8599 FnType = FnTypePtr->getPointeeType();
8600 isPointer = true;
8601 }
8602 // Desugar down to a function type.
8603 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8604 // Reconstruct the pointer/reference as appropriate.
8605 if (isPointer) FnType = S.Context.getPointerType(FnType);
8606 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8607 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8608
8609 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8610 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008611 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008612}
8613
8614void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008615 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008616 SourceLocation OpLoc,
8617 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008618 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008619 std::string TypeStr("operator");
8620 TypeStr += Opc;
8621 TypeStr += "(";
8622 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008623 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008624 TypeStr += ")";
8625 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8626 } else {
8627 TypeStr += ", ";
8628 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8629 TypeStr += ")";
8630 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8631 }
8632}
8633
8634void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8635 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008636 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008637 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8638 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008639 if (ICS.isBad()) break; // all meaningless after first invalid
8640 if (!ICS.isAmbiguous()) continue;
8641
John McCall120d63c2010-08-24 20:38:10 +00008642 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008643 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008644 }
8645}
8646
John McCall1b77e732010-01-15 23:32:50 +00008647SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8648 if (Cand->Function)
8649 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008650 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008651 return Cand->Surrogate->getLocation();
8652 return SourceLocation();
8653}
8654
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008655static unsigned
8656RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008657 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008658 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008659 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008660
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008661 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008662 case Sema::TDK_Incomplete:
8663 return 1;
8664
8665 case Sema::TDK_Underqualified:
8666 case Sema::TDK_Inconsistent:
8667 return 2;
8668
8669 case Sema::TDK_SubstitutionFailure:
8670 case Sema::TDK_NonDeducedMismatch:
Richard Smith29805ca2013-01-31 05:19:49 +00008671 case Sema::TDK_MiscellaneousDeductionFailure:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008672 return 3;
8673
8674 case Sema::TDK_InstantiationDepth:
8675 case Sema::TDK_FailedOverloadResolution:
8676 return 4;
8677
8678 case Sema::TDK_InvalidExplicitArguments:
8679 return 5;
8680
8681 case Sema::TDK_TooManyArguments:
8682 case Sema::TDK_TooFewArguments:
8683 return 6;
8684 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008685 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008686}
8687
John McCallbf65c0b2010-01-12 00:48:53 +00008688struct CompareOverloadCandidatesForDisplay {
8689 Sema &S;
8690 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008691
8692 bool operator()(const OverloadCandidate *L,
8693 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008694 // Fast-path this check.
8695 if (L == R) return false;
8696
John McCall81201622010-01-08 04:41:39 +00008697 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008698 if (L->Viable) {
8699 if (!R->Viable) return true;
8700
8701 // TODO: introduce a tri-valued comparison for overload
8702 // candidates. Would be more worthwhile if we had a sort
8703 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008704 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8705 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008706 } else if (R->Viable)
8707 return false;
John McCall81201622010-01-08 04:41:39 +00008708
John McCall1b77e732010-01-15 23:32:50 +00008709 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008710
John McCall1b77e732010-01-15 23:32:50 +00008711 // Criteria by which we can sort non-viable candidates:
8712 if (!L->Viable) {
8713 // 1. Arity mismatches come after other candidates.
8714 if (L->FailureKind == ovl_fail_too_many_arguments ||
8715 L->FailureKind == ovl_fail_too_few_arguments)
8716 return false;
8717 if (R->FailureKind == ovl_fail_too_many_arguments ||
8718 R->FailureKind == ovl_fail_too_few_arguments)
8719 return true;
John McCall81201622010-01-08 04:41:39 +00008720
John McCall717e8912010-01-23 05:17:32 +00008721 // 2. Bad conversions come first and are ordered by the number
8722 // of bad conversions and quality of good conversions.
8723 if (L->FailureKind == ovl_fail_bad_conversion) {
8724 if (R->FailureKind != ovl_fail_bad_conversion)
8725 return true;
8726
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008727 // The conversion that can be fixed with a smaller number of changes,
8728 // comes first.
8729 unsigned numLFixes = L->Fix.NumConversionsFixed;
8730 unsigned numRFixes = R->Fix.NumConversionsFixed;
8731 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8732 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008733 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008734 if (numLFixes < numRFixes)
8735 return true;
8736 else
8737 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008738 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008739
John McCall717e8912010-01-23 05:17:32 +00008740 // If there's any ordering between the defined conversions...
8741 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008742 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008743
8744 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008745 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008746 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008747 switch (CompareImplicitConversionSequences(S,
8748 L->Conversions[I],
8749 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008750 case ImplicitConversionSequence::Better:
8751 leftBetter++;
8752 break;
8753
8754 case ImplicitConversionSequence::Worse:
8755 leftBetter--;
8756 break;
8757
8758 case ImplicitConversionSequence::Indistinguishable:
8759 break;
8760 }
8761 }
8762 if (leftBetter > 0) return true;
8763 if (leftBetter < 0) return false;
8764
8765 } else if (R->FailureKind == ovl_fail_bad_conversion)
8766 return false;
8767
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008768 if (L->FailureKind == ovl_fail_bad_deduction) {
8769 if (R->FailureKind != ovl_fail_bad_deduction)
8770 return true;
8771
8772 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8773 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008774 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008775 } else if (R->FailureKind == ovl_fail_bad_deduction)
8776 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008777
John McCall1b77e732010-01-15 23:32:50 +00008778 // TODO: others?
8779 }
8780
8781 // Sort everything else by location.
8782 SourceLocation LLoc = GetLocationForCandidate(L);
8783 SourceLocation RLoc = GetLocationForCandidate(R);
8784
8785 // Put candidates without locations (e.g. builtins) at the end.
8786 if (LLoc.isInvalid()) return false;
8787 if (RLoc.isInvalid()) return true;
8788
8789 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008790 }
8791};
8792
John McCall717e8912010-01-23 05:17:32 +00008793/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008794/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008795void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008796 ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008797 assert(!Cand->Viable);
8798
8799 // Don't do anything on failures other than bad conversion.
8800 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8801
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008802 // We only want the FixIts if all the arguments can be corrected.
8803 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008804 // Use a implicit copy initialization to check conversion fixes.
8805 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008806
John McCall717e8912010-01-23 05:17:32 +00008807 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008808 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008809 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008810 while (true) {
8811 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8812 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008813 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008814 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008815 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008816 }
John McCall717e8912010-01-23 05:17:32 +00008817 }
8818
8819 if (ConvIdx == ConvCount)
8820 return;
8821
John McCallb1bdc622010-02-25 01:37:24 +00008822 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8823 "remaining conversion is initialized?");
8824
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008825 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008826 // operation somehow.
8827 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008828
8829 const FunctionProtoType* Proto;
8830 unsigned ArgIdx = ConvIdx;
8831
8832 if (Cand->IsSurrogate) {
8833 QualType ConvType
8834 = Cand->Surrogate->getConversionType().getNonReferenceType();
8835 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8836 ConvType = ConvPtrType->getPointeeType();
8837 Proto = ConvType->getAs<FunctionProtoType>();
8838 ArgIdx--;
8839 } else if (Cand->Function) {
8840 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8841 if (isa<CXXMethodDecl>(Cand->Function) &&
8842 !isa<CXXConstructorDecl>(Cand->Function))
8843 ArgIdx--;
8844 } else {
8845 // Builtin binary operator with a bad first conversion.
8846 assert(ConvCount <= 3);
8847 for (; ConvIdx != ConvCount; ++ConvIdx)
8848 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008849 = TryCopyInitialization(S, Args[ConvIdx],
8850 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008851 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008852 /*InOverloadResolution*/ true,
8853 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008854 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008855 return;
8856 }
8857
8858 // Fill in the rest of the conversions.
8859 unsigned NumArgsInProto = Proto->getNumArgs();
8860 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008861 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008862 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008863 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008864 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008865 /*InOverloadResolution=*/true,
8866 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008867 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008868 // Store the FixIt in the candidate if it exists.
8869 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008870 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008871 }
John McCall717e8912010-01-23 05:17:32 +00008872 else
8873 Cand->Conversions[ConvIdx].setEllipsis();
8874 }
8875}
8876
John McCalla1d7d622010-01-08 00:58:21 +00008877} // end anonymous namespace
8878
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008879/// PrintOverloadCandidates - When overload resolution fails, prints
8880/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008881/// set.
John McCall120d63c2010-08-24 20:38:10 +00008882void OverloadCandidateSet::NoteCandidates(Sema &S,
8883 OverloadCandidateDisplayKind OCD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00008884 ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008885 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008886 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008887 // Sort the candidates by viability and position. Sorting directly would
8888 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008889 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008890 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8891 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008892 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008893 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008894 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008895 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008896 if (Cand->Function || Cand->IsSurrogate)
8897 Cands.push_back(Cand);
8898 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8899 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008900 }
8901 }
8902
John McCallbf65c0b2010-01-12 00:48:53 +00008903 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008904 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008905
John McCall1d318332010-01-12 00:44:57 +00008906 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008907
Chris Lattner5f9e2722011-07-23 10:55:15 +00008908 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008909 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008910 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008911 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8912 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008913
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008914 // Set an arbitrary limit on the number of candidate functions we'll spam
8915 // the user with. FIXME: This limit should depend on details of the
8916 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008917 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008918 break;
8919 }
8920 ++CandsShown;
8921
John McCalla1d7d622010-01-08 00:58:21 +00008922 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008923 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008924 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008925 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008926 else {
8927 assert(Cand->Viable &&
8928 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008929 // Generally we only see ambiguities including viable builtin
8930 // operators if overload resolution got screwed up by an
8931 // ambiguous user-defined conversion.
8932 //
8933 // FIXME: It's quite possible for different conversions to see
8934 // different ambiguities, though.
8935 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008936 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008937 ReportedAmbiguousConversions = true;
8938 }
John McCalla1d7d622010-01-08 00:58:21 +00008939
John McCall1d318332010-01-12 00:44:57 +00008940 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008941 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008942 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008943 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008944
8945 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008946 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008947}
8948
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008949// [PossiblyAFunctionType] --> [Return]
8950// NonFunctionType --> NonFunctionType
8951// R (A) --> R(A)
8952// R (*)(A) --> R (A)
8953// R (&)(A) --> R (A)
8954// R (S::*)(A) --> R (A)
8955QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8956 QualType Ret = PossiblyAFunctionType;
8957 if (const PointerType *ToTypePtr =
8958 PossiblyAFunctionType->getAs<PointerType>())
8959 Ret = ToTypePtr->getPointeeType();
8960 else if (const ReferenceType *ToTypeRef =
8961 PossiblyAFunctionType->getAs<ReferenceType>())
8962 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008963 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008964 PossiblyAFunctionType->getAs<MemberPointerType>())
8965 Ret = MemTypePtr->getPointeeType();
8966 Ret =
8967 Context.getCanonicalType(Ret).getUnqualifiedType();
8968 return Ret;
8969}
Douglas Gregor904eed32008-11-10 20:40:00 +00008970
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008971// A helper class to help with address of function resolution
8972// - allows us to avoid passing around all those ugly parameters
8973class AddressOfFunctionResolver
8974{
8975 Sema& S;
8976 Expr* SourceExpr;
8977 const QualType& TargetType;
8978 QualType TargetFunctionType; // Extracted function type from target type
8979
8980 bool Complain;
8981 //DeclAccessPair& ResultFunctionAccessPair;
8982 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008983
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008984 bool TargetTypeIsNonStaticMemberFunction;
8985 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008986
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008987 OverloadExpr::FindResult OvlExprInfo;
8988 OverloadExpr *OvlExpr;
8989 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008990 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008991
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008992public:
8993 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8994 const QualType& TargetType, bool Complain)
8995 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8996 Complain(Complain), Context(S.getASTContext()),
8997 TargetTypeIsNonStaticMemberFunction(
8998 !!TargetType->getAs<MemberPointerType>()),
8999 FoundNonTemplateFunction(false),
9000 OvlExprInfo(OverloadExpr::find(SourceExpr)),
9001 OvlExpr(OvlExprInfo.Expression)
9002 {
9003 ExtractUnqualifiedFunctionTypeFromTargetType();
9004
9005 if (!TargetFunctionType->isFunctionType()) {
9006 if (OvlExpr->hasExplicitTemplateArgs()) {
9007 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00009008 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009009 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00009010
9011 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9012 if (!Method->isStatic()) {
9013 // If the target type is a non-function type and the function
9014 // found is a non-static member function, pretend as if that was
9015 // the target, it's the only possible type to end up with.
9016 TargetTypeIsNonStaticMemberFunction = true;
9017
9018 // And skip adding the function if its not in the proper form.
9019 // We'll diagnose this due to an empty set of functions.
9020 if (!OvlExprInfo.HasFormOfMemberPointer)
9021 return;
9022 }
9023 }
9024
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009025 Matches.push_back(std::make_pair(dap,Fn));
9026 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00009027 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009028 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00009029 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009030
9031 if (OvlExpr->hasExplicitTemplateArgs())
9032 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00009033
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009034 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
9035 // C++ [over.over]p4:
9036 // If more than one function is selected, [...]
9037 if (Matches.size() > 1) {
9038 if (FoundNonTemplateFunction)
9039 EliminateAllTemplateMatches();
9040 else
9041 EliminateAllExceptMostSpecializedTemplate();
9042 }
9043 }
9044 }
9045
9046private:
9047 bool isTargetTypeAFunction() const {
9048 return TargetFunctionType->isFunctionType();
9049 }
9050
9051 // [ToType] [Return]
9052
9053 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
9054 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
9055 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
9056 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
9057 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
9058 }
9059
9060 // return true if any matching specializations were found
9061 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9062 const DeclAccessPair& CurAccessFunPair) {
9063 if (CXXMethodDecl *Method
9064 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9065 // Skip non-static function templates when converting to pointer, and
9066 // static when converting to member pointer.
9067 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9068 return false;
9069 }
9070 else if (TargetTypeIsNonStaticMemberFunction)
9071 return false;
9072
9073 // C++ [over.over]p2:
9074 // If the name is a function template, template argument deduction is
9075 // done (14.8.2.2), and if the argument deduction succeeds, the
9076 // resulting template argument list is used to generate a single
9077 // function template specialization, which is added to the set of
9078 // overloaded functions considered.
9079 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009080 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009081 if (Sema::TemplateDeductionResult Result
9082 = S.DeduceTemplateArguments(FunctionTemplate,
9083 &OvlExplicitTemplateArgs,
9084 TargetFunctionType, Specialization,
9085 Info)) {
9086 // FIXME: make a note of the failed deduction for diagnostics.
9087 (void)Result;
9088 return false;
9089 }
9090
9091 // Template argument deduction ensures that we have an exact match.
9092 // This function template specicalization works.
9093 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9094 assert(TargetFunctionType
9095 == Context.getCanonicalType(Specialization->getType()));
9096 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9097 return true;
9098 }
9099
9100 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9101 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009102 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009103 // Skip non-static functions when converting to pointer, and static
9104 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009105 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9106 return false;
9107 }
9108 else if (TargetTypeIsNonStaticMemberFunction)
9109 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009110
Chandler Carruthbd647292009-12-29 06:17:27 +00009111 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009112 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009113 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9114 if (S.CheckCUDATarget(Caller, FunDecl))
9115 return false;
9116
Douglas Gregor43c79c22009-12-09 00:47:37 +00009117 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009118 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9119 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009120 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9121 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009122 Matches.push_back(std::make_pair(CurAccessFunPair,
9123 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009124 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009125 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009126 }
Mike Stump1eb44332009-09-09 15:08:12 +00009127 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009128
9129 return false;
9130 }
9131
9132 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9133 bool Ret = false;
9134
9135 // If the overload expression doesn't have the form of a pointer to
9136 // member, don't try to convert it to a pointer-to-member type.
9137 if (IsInvalidFormOfPointerToMemberFunction())
9138 return false;
9139
9140 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9141 E = OvlExpr->decls_end();
9142 I != E; ++I) {
9143 // Look through any using declarations to find the underlying function.
9144 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9145
9146 // C++ [over.over]p3:
9147 // Non-member functions and static member functions match
9148 // targets of type "pointer-to-function" or "reference-to-function."
9149 // Nonstatic member functions match targets of
9150 // type "pointer-to-member-function."
9151 // Note that according to DR 247, the containing class does not matter.
9152 if (FunctionTemplateDecl *FunctionTemplate
9153 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9154 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9155 Ret = true;
9156 }
9157 // If we have explicit template arguments supplied, skip non-templates.
9158 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9159 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9160 Ret = true;
9161 }
9162 assert(Ret || Matches.empty());
9163 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009164 }
9165
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009166 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009167 // [...] and any given function template specialization F1 is
9168 // eliminated if the set contains a second function template
9169 // specialization whose function template is more specialized
9170 // than the function template of F1 according to the partial
9171 // ordering rules of 14.5.5.2.
9172
9173 // The algorithm specified above is quadratic. We instead use a
9174 // two-pass algorithm (similar to the one used to identify the
9175 // best viable function in an overload set) that identifies the
9176 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009177
9178 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9179 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9180 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009181
John McCallc373d482010-01-27 01:50:18 +00009182 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009183 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9184 TPOC_Other, 0, SourceExpr->getLocStart(),
9185 S.PDiag(),
9186 S.PDiag(diag::err_addr_ovl_ambiguous)
9187 << Matches[0].second->getDeclName(),
9188 S.PDiag(diag::note_ovl_candidate)
9189 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009190 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009191
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009192 if (Result != MatchesCopy.end()) {
9193 // Make it the first and only element
9194 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9195 Matches[0].second = cast<FunctionDecl>(*Result);
9196 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009197 }
9198 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009199
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009200 void EliminateAllTemplateMatches() {
9201 // [...] any function template specializations in the set are
9202 // eliminated if the set also contains a non-template function, [...]
9203 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9204 if (Matches[I].second->getPrimaryTemplate() == 0)
9205 ++I;
9206 else {
9207 Matches[I] = Matches[--N];
9208 Matches.set_size(N);
9209 }
9210 }
9211 }
9212
9213public:
9214 void ComplainNoMatchesFound() const {
9215 assert(Matches.empty());
9216 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9217 << OvlExpr->getName() << TargetFunctionType
9218 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009219 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009220 }
9221
9222 bool IsInvalidFormOfPointerToMemberFunction() const {
9223 return TargetTypeIsNonStaticMemberFunction &&
9224 !OvlExprInfo.HasFormOfMemberPointer;
9225 }
9226
9227 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9228 // TODO: Should we condition this on whether any functions might
9229 // have matched, or is it more appropriate to do that in callers?
9230 // TODO: a fixit wouldn't hurt.
9231 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9232 << TargetType << OvlExpr->getSourceRange();
9233 }
9234
9235 void ComplainOfInvalidConversion() const {
9236 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9237 << OvlExpr->getName() << TargetType;
9238 }
9239
9240 void ComplainMultipleMatchesFound() const {
9241 assert(Matches.size() > 1);
9242 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9243 << OvlExpr->getName()
9244 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009245 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009246 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009247
9248 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9249
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009250 int getNumMatches() const { return Matches.size(); }
9251
9252 FunctionDecl* getMatchingFunctionDecl() const {
9253 if (Matches.size() != 1) return 0;
9254 return Matches[0].second;
9255 }
9256
9257 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9258 if (Matches.size() != 1) return 0;
9259 return &Matches[0].first;
9260 }
9261};
9262
9263/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9264/// an overloaded function (C++ [over.over]), where @p From is an
9265/// expression with overloaded function type and @p ToType is the type
9266/// we're trying to resolve to. For example:
9267///
9268/// @code
9269/// int f(double);
9270/// int f(int);
9271///
9272/// int (*pfd)(double) = f; // selects f(double)
9273/// @endcode
9274///
9275/// This routine returns the resulting FunctionDecl if it could be
9276/// resolved, and NULL otherwise. When @p Complain is true, this
9277/// routine will emit diagnostics if there is an error.
9278FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009279Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9280 QualType TargetType,
9281 bool Complain,
9282 DeclAccessPair &FoundResult,
9283 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009284 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009285
9286 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9287 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009288 int NumMatches = Resolver.getNumMatches();
9289 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009290 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009291 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9292 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9293 else
9294 Resolver.ComplainNoMatchesFound();
9295 }
9296 else if (NumMatches > 1 && Complain)
9297 Resolver.ComplainMultipleMatchesFound();
9298 else if (NumMatches == 1) {
9299 Fn = Resolver.getMatchingFunctionDecl();
9300 assert(Fn);
9301 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009302 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009303 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009304 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009305
9306 if (pHadMultipleCandidates)
9307 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009308 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009309}
9310
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009311/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009312/// resolve that overloaded function expression down to a single function.
9313///
9314/// This routine can only resolve template-ids that refer to a single function
9315/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009316/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009317/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009318FunctionDecl *
9319Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9320 bool Complain,
9321 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009322 // C++ [over.over]p1:
9323 // [...] [Note: any redundant set of parentheses surrounding the
9324 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009325 // C++ [over.over]p1:
9326 // [...] The overloaded function name can be preceded by the &
9327 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009328
Douglas Gregor4b52e252009-12-21 23:17:24 +00009329 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009330 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009331 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009332
9333 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009334 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009335
Douglas Gregor4b52e252009-12-21 23:17:24 +00009336 // Look through all of the overloaded functions, searching for one
9337 // whose type matches exactly.
9338 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009339 for (UnresolvedSetIterator I = ovl->decls_begin(),
9340 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009341 // C++0x [temp.arg.explicit]p3:
9342 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009343 // where deduction is not done, if a template argument list is
9344 // specified and it, along with any default template arguments,
9345 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009346 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009347 FunctionTemplateDecl *FunctionTemplate
9348 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009349
Douglas Gregor4b52e252009-12-21 23:17:24 +00009350 // C++ [over.over]p2:
9351 // If the name is a function template, template argument deduction is
9352 // done (14.8.2.2), and if the argument deduction succeeds, the
9353 // resulting template argument list is used to generate a single
9354 // function template specialization, which is added to the set of
9355 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009356 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009357 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009358 if (TemplateDeductionResult Result
9359 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9360 Specialization, Info)) {
9361 // FIXME: make a note of the failed deduction for diagnostics.
9362 (void)Result;
9363 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009364 }
9365
John McCall864c0412011-04-26 20:42:42 +00009366 assert(Specialization && "no specialization and no error?");
9367
Douglas Gregor4b52e252009-12-21 23:17:24 +00009368 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009369 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009370 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009371 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9372 << ovl->getName();
9373 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009374 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009375 return 0;
John McCall864c0412011-04-26 20:42:42 +00009376 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009377
John McCall864c0412011-04-26 20:42:42 +00009378 Matched = Specialization;
9379 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009380 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009381
Douglas Gregor4b52e252009-12-21 23:17:24 +00009382 return Matched;
9383}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009384
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009385
9386
9387
John McCall6dbba4f2011-10-11 23:14:30 +00009388// Resolve and fix an overloaded expression that can be resolved
9389// because it identifies a single function template specialization.
9390//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009391// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009392//
9393// Return true if it was logically possible to so resolve the
9394// expression, regardless of whether or not it succeeded. Always
9395// returns true if 'complain' is set.
9396bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9397 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9398 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009399 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009400 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009401 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009402
John McCall6dbba4f2011-10-11 23:14:30 +00009403 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009404
John McCall864c0412011-04-26 20:42:42 +00009405 DeclAccessPair found;
9406 ExprResult SingleFunctionExpression;
9407 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9408 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009409 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009410 SrcExpr = ExprError();
9411 return true;
9412 }
John McCall864c0412011-04-26 20:42:42 +00009413
9414 // It is only correct to resolve to an instance method if we're
9415 // resolving a form that's permitted to be a pointer to member.
9416 // Otherwise we'll end up making a bound member expression, which
9417 // is illegal in all the contexts we resolve like this.
9418 if (!ovl.HasFormOfMemberPointer &&
9419 isa<CXXMethodDecl>(fn) &&
9420 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009421 if (!complain) return false;
9422
9423 Diag(ovl.Expression->getExprLoc(),
9424 diag::err_bound_member_function)
9425 << 0 << ovl.Expression->getSourceRange();
9426
9427 // TODO: I believe we only end up here if there's a mix of
9428 // static and non-static candidates (otherwise the expression
9429 // would have 'bound member' type, not 'overload' type).
9430 // Ideally we would note which candidate was chosen and why
9431 // the static candidates were rejected.
9432 SrcExpr = ExprError();
9433 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009434 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009435
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009436 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009437 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009438 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009439
9440 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009441 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009442 SingleFunctionExpression =
9443 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009444 if (SingleFunctionExpression.isInvalid()) {
9445 SrcExpr = ExprError();
9446 return true;
9447 }
9448 }
John McCall864c0412011-04-26 20:42:42 +00009449 }
9450
9451 if (!SingleFunctionExpression.isUsable()) {
9452 if (complain) {
9453 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9454 << ovl.Expression->getName()
9455 << DestTypeForComplaining
9456 << OpRangeForComplaining
9457 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009458 NoteAllOverloadCandidates(SrcExpr.get());
9459
9460 SrcExpr = ExprError();
9461 return true;
9462 }
9463
9464 return false;
John McCall864c0412011-04-26 20:42:42 +00009465 }
9466
John McCall6dbba4f2011-10-11 23:14:30 +00009467 SrcExpr = SingleFunctionExpression;
9468 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009469}
9470
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009471/// \brief Add a single candidate to the overload set.
9472static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009473 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009474 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009475 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009476 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009477 bool PartialOverloading,
9478 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009479 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009480 if (isa<UsingShadowDecl>(Callee))
9481 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9482
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009483 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009484 if (ExplicitTemplateArgs) {
9485 assert(!KnownValid && "Explicit template arguments?");
9486 return;
9487 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009488 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9489 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009490 return;
John McCallba135432009-11-21 08:51:07 +00009491 }
9492
9493 if (FunctionTemplateDecl *FuncTemplate
9494 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009495 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009496 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009497 return;
9498 }
9499
Richard Smith2ced0442011-06-26 22:19:54 +00009500 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009501}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009502
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009503/// \brief Add the overload candidates named by callee and/or found by argument
9504/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009505void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009506 ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009507 OverloadCandidateSet &CandidateSet,
9508 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009509
9510#ifndef NDEBUG
9511 // Verify that ArgumentDependentLookup is consistent with the rules
9512 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009513 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009514 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9515 // and let Y be the lookup set produced by argument dependent
9516 // lookup (defined as follows). If X contains
9517 //
9518 // -- a declaration of a class member, or
9519 //
9520 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009521 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009522 //
9523 // -- a declaration that is neither a function or a function
9524 // template
9525 //
9526 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009527
John McCall3b4294e2009-12-16 12:17:52 +00009528 if (ULE->requiresADL()) {
9529 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9530 E = ULE->decls_end(); I != E; ++I) {
9531 assert(!(*I)->getDeclContext()->isRecord());
9532 assert(isa<UsingShadowDecl>(*I) ||
9533 !(*I)->getDeclContext()->isFunctionOrMethod());
9534 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009535 }
9536 }
9537#endif
9538
John McCall3b4294e2009-12-16 12:17:52 +00009539 // It would be nice to avoid this copy.
9540 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009541 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009542 if (ULE->hasExplicitTemplateArgs()) {
9543 ULE->copyTemplateArgumentsInto(TABuffer);
9544 ExplicitTemplateArgs = &TABuffer;
9545 }
9546
9547 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9548 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009549 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9550 CandidateSet, PartialOverloading,
9551 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009552
John McCall3b4294e2009-12-16 12:17:52 +00009553 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009554 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009555 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009556 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009557 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009558}
John McCall578b69b2009-12-16 08:11:27 +00009559
Richard Smithf50e88a2011-06-05 22:42:48 +00009560/// Attempt to recover from an ill-formed use of a non-dependent name in a
9561/// template, where the non-dependent name was declared after the template
9562/// was defined. This is common in code written for a compilers which do not
9563/// correctly implement two-stage name lookup.
9564///
9565/// Returns true if a viable candidate was found and a diagnostic was issued.
9566static bool
9567DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9568 const CXXScopeSpec &SS, LookupResult &R,
9569 TemplateArgumentListInfo *ExplicitTemplateArgs,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009570 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009571 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9572 return false;
9573
9574 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009575 if (DC->isTransparentContext())
9576 continue;
9577
Richard Smithf50e88a2011-06-05 22:42:48 +00009578 SemaRef.LookupQualifiedName(R, DC);
9579
9580 if (!R.empty()) {
9581 R.suppressDiagnostics();
9582
9583 if (isa<CXXRecordDecl>(DC)) {
9584 // Don't diagnose names we find in classes; we get much better
9585 // diagnostics for these from DiagnoseEmptyLookup.
9586 R.clear();
9587 return false;
9588 }
9589
9590 OverloadCandidateSet Candidates(FnLoc);
9591 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9592 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009593 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009594 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009595
9596 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009597 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009598 // No viable functions. Don't bother the user with notes for functions
9599 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009600 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009601 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009602 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009603
9604 // Find the namespaces where ADL would have looked, and suggest
9605 // declaring the function there instead.
9606 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9607 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009608 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009609 AssociatedNamespaces,
9610 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009611 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009612 DeclContext *Std = SemaRef.getStdNamespace();
9613 for (Sema::AssociatedNamespaceSet::iterator
9614 it = AssociatedNamespaces.begin(),
9615 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009616 // Never suggest declaring a function within namespace 'std'.
9617 if (Std && Std->Encloses(*it))
9618 continue;
9619
9620 // Never suggest declaring a function within a namespace with a reserved
9621 // name, like __gnu_cxx.
9622 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9623 if (NS &&
9624 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9625 continue;
9626
9627 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009628 }
9629
9630 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9631 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009632 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009633 SemaRef.Diag(Best->Function->getLocation(),
9634 diag::note_not_found_by_two_phase_lookup)
9635 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009636 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009637 SemaRef.Diag(Best->Function->getLocation(),
9638 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009639 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009640 } else {
9641 // FIXME: It would be useful to list the associated namespaces here,
9642 // but the diagnostics infrastructure doesn't provide a way to produce
9643 // a localized representation of a list of items.
9644 SemaRef.Diag(Best->Function->getLocation(),
9645 diag::note_not_found_by_two_phase_lookup)
9646 << R.getLookupName() << 2;
9647 }
9648
9649 // Try to recover by calling this function.
9650 return true;
9651 }
9652
9653 R.clear();
9654 }
9655
9656 return false;
9657}
9658
9659/// Attempt to recover from ill-formed use of a non-dependent operator in a
9660/// template, where the non-dependent operator was declared after the template
9661/// was defined.
9662///
9663/// Returns true if a viable candidate was found and a diagnostic was issued.
9664static bool
9665DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9666 SourceLocation OpLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00009667 ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009668 DeclarationName OpName =
9669 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9670 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9671 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009672 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009673}
9674
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009675namespace {
9676// Callback to limit the allowed keywords and to only accept typo corrections
9677// that are keywords or whose decls refer to functions (or template functions)
9678// that accept the given number of arguments.
9679class RecoveryCallCCC : public CorrectionCandidateCallback {
9680 public:
9681 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9682 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009683 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009684 WantRemainingKeywords = false;
9685 }
9686
9687 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9688 if (!candidate.getCorrectionDecl())
9689 return candidate.isKeyword();
9690
9691 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9692 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9693 FunctionDecl *FD = 0;
9694 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9695 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9696 FD = FTD->getTemplatedDecl();
9697 if (!HasExplicitTemplateArgs && !FD) {
9698 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9699 // If the Decl is neither a function nor a template function,
9700 // determine if it is a pointer or reference to a function. If so,
9701 // check against the number of arguments expected for the pointee.
9702 QualType ValType = cast<ValueDecl>(ND)->getType();
9703 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9704 ValType = ValType->getPointeeType();
9705 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9706 if (FPT->getNumArgs() == NumArgs)
9707 return true;
9708 }
9709 }
9710 if (FD && FD->getNumParams() >= NumArgs &&
9711 FD->getMinRequiredArguments() <= NumArgs)
9712 return true;
9713 }
9714 return false;
9715 }
9716
9717 private:
9718 unsigned NumArgs;
9719 bool HasExplicitTemplateArgs;
9720};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009721
9722// Callback that effectively disabled typo correction
9723class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9724 public:
9725 NoTypoCorrectionCCC() {
9726 WantTypeSpecifiers = false;
9727 WantExpressionKeywords = false;
9728 WantCXXNamedCasts = false;
9729 WantRemainingKeywords = false;
9730 }
9731
9732 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9733 return false;
9734 }
9735};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009736
9737class BuildRecoveryCallExprRAII {
9738 Sema &SemaRef;
9739public:
9740 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9741 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9742 SemaRef.IsBuildingRecoveryCallExpr = true;
9743 }
9744
9745 ~BuildRecoveryCallExprRAII() {
9746 SemaRef.IsBuildingRecoveryCallExpr = false;
9747 }
9748};
9749
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009750}
9751
John McCall578b69b2009-12-16 08:11:27 +00009752/// Attempts to recover from a call where no functions were found.
9753///
9754/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009755static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009756BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009757 UnresolvedLookupExpr *ULE,
9758 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009759 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009760 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009761 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009762 // Do not try to recover if it is already building a recovery call.
9763 // This stops infinite loops for template instantiations like
9764 //
9765 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9766 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9767 //
9768 if (SemaRef.IsBuildingRecoveryCallExpr)
9769 return ExprError();
9770 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009771
9772 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009773 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009774 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009775
John McCall3b4294e2009-12-16 12:17:52 +00009776 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009777 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009778 if (ULE->hasExplicitTemplateArgs()) {
9779 ULE->copyTemplateArgumentsInto(TABuffer);
9780 ExplicitTemplateArgs = &TABuffer;
9781 }
9782
John McCall578b69b2009-12-16 08:11:27 +00009783 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9784 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009785 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009786 NoTypoCorrectionCCC RejectAll;
9787 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9788 (CorrectionCandidateCallback*)&Validator :
9789 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009790 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009791 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009792 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009793 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009794 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009795 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009796
John McCall3b4294e2009-12-16 12:17:52 +00009797 assert(!R.empty() && "lookup results empty despite recovery");
9798
9799 // Build an implicit member call if appropriate. Just drop the
9800 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009801 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009802 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009803 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9804 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009805 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009806 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009807 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009808 else
9809 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9810
9811 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009812 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009813
9814 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009815 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009816 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009817 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009818 MultiExprArg(Args.data(), Args.size()),
9819 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009820}
Douglas Gregord7a95972010-06-08 17:35:15 +00009821
Sam Panzere1715b62012-08-21 00:52:01 +00009822/// \brief Constructs and populates an OverloadedCandidateSet from
9823/// the given function.
9824/// \returns true when an the ExprResult output parameter has been set.
9825bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9826 UnresolvedLookupExpr *ULE,
9827 Expr **Args, unsigned NumArgs,
9828 SourceLocation RParenLoc,
9829 OverloadCandidateSet *CandidateSet,
9830 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009831#ifndef NDEBUG
9832 if (ULE->requiresADL()) {
9833 // To do ADL, we must have found an unqualified name.
9834 assert(!ULE->getQualifier() && "qualified name with ADL");
9835
9836 // We don't perform ADL for implicit declarations of builtins.
9837 // Verify that this was correctly set up.
9838 FunctionDecl *F;
9839 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9840 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9841 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009842 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009843
John McCall3b4294e2009-12-16 12:17:52 +00009844 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009845 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009846 }
John McCall3b4294e2009-12-16 12:17:52 +00009847#endif
9848
John McCall5acb0c92011-10-17 18:40:02 +00009849 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009850 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9851 *Result = ExprError();
9852 return true;
9853 }
Douglas Gregor17330012009-02-04 15:01:18 +00009854
John McCall3b4294e2009-12-16 12:17:52 +00009855 // Add the functions denoted by the callee to the set of candidate
9856 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009857 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009858 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009859
9860 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009861 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9862 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009863 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009864 // In Microsoft mode, if we are inside a template class member function then
9865 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009866 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009867 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009868 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009869 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009870 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9871 llvm::makeArrayRef(Args, NumArgs),
9872 Context.DependentTy, VK_RValue,
9873 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009874 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009875 *Result = Owned(CE);
9876 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009877 }
Sam Panzere1715b62012-08-21 00:52:01 +00009878 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009879 }
John McCall578b69b2009-12-16 08:11:27 +00009880
John McCall5acb0c92011-10-17 18:40:02 +00009881 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009882 return false;
9883}
John McCall5acb0c92011-10-17 18:40:02 +00009884
Sam Panzere1715b62012-08-21 00:52:01 +00009885/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9886/// the completed call expression. If overload resolution fails, emits
9887/// diagnostics and returns ExprError()
9888static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9889 UnresolvedLookupExpr *ULE,
9890 SourceLocation LParenLoc,
9891 Expr **Args, unsigned NumArgs,
9892 SourceLocation RParenLoc,
9893 Expr *ExecConfig,
9894 OverloadCandidateSet *CandidateSet,
9895 OverloadCandidateSet::iterator *Best,
9896 OverloadingResult OverloadResult,
9897 bool AllowTypoCorrection) {
9898 if (CandidateSet->empty())
9899 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9900 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9901 RParenLoc, /*EmptyLookup=*/true,
9902 AllowTypoCorrection);
9903
9904 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009905 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009906 FunctionDecl *FDecl = (*Best)->Function;
9907 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9908 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9909 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9910 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9911 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9912 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009913 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009914
Richard Smithf50e88a2011-06-05 22:42:48 +00009915 case OR_No_Viable_Function: {
9916 // Try to recover by looking for viable functions which the user might
9917 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009918 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009919 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9920 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009921 /*EmptyLookup=*/false,
9922 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009923 if (!Recovery.isInvalid())
9924 return Recovery;
9925
Sam Panzere1715b62012-08-21 00:52:01 +00009926 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009927 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009928 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009929 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9930 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009931 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009932 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009933
9934 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009935 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009936 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009937 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9938 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009939 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009940
Sam Panzere1715b62012-08-21 00:52:01 +00009941 case OR_Deleted: {
9942 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9943 << (*Best)->Function->isDeleted()
9944 << ULE->getName()
9945 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9946 << Fn->getSourceRange();
9947 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9948 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009949
Sam Panzere1715b62012-08-21 00:52:01 +00009950 // We emitted an error for the unvailable/deleted function call but keep
9951 // the call in the AST.
9952 FunctionDecl *FDecl = (*Best)->Function;
9953 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9954 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9955 RParenLoc, ExecConfig);
9956 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009957 }
9958
Douglas Gregorff331c12010-07-25 18:17:45 +00009959 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009960 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009961}
9962
Sam Panzere1715b62012-08-21 00:52:01 +00009963/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9964/// (which eventually refers to the declaration Func) and the call
9965/// arguments Args/NumArgs, attempt to resolve the function call down
9966/// to a specific function. If overload resolution succeeds, returns
9967/// the call expression produced by overload resolution.
9968/// Otherwise, emits diagnostics and returns ExprError.
9969ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9970 UnresolvedLookupExpr *ULE,
9971 SourceLocation LParenLoc,
9972 Expr **Args, unsigned NumArgs,
9973 SourceLocation RParenLoc,
9974 Expr *ExecConfig,
9975 bool AllowTypoCorrection) {
9976 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9977 ExprResult result;
9978
9979 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9980 &CandidateSet, &result))
9981 return result;
9982
9983 OverloadCandidateSet::iterator Best;
9984 OverloadingResult OverloadResult =
9985 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9986
9987 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9988 RParenLoc, ExecConfig, &CandidateSet,
9989 &Best, OverloadResult,
9990 AllowTypoCorrection);
9991}
9992
John McCall6e266892010-01-26 03:27:55 +00009993static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009994 return Functions.size() > 1 ||
9995 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9996}
9997
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009998/// \brief Create a unary operation that may resolve to an overloaded
9999/// operator.
10000///
10001/// \param OpLoc The location of the operator itself (e.g., '*').
10002///
10003/// \param OpcIn The UnaryOperator::Opcode that describes this
10004/// operator.
10005///
James Dennett40ae6662012-06-22 08:52:37 +000010006/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010007/// considered by overload resolution. The caller needs to build this
10008/// set based on the context using, e.g.,
10009/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10010/// set should not contain any member functions; those will be added
10011/// by CreateOverloadedUnaryOp().
10012///
James Dennett8da16872012-06-22 10:32:46 +000010013/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010014ExprResult
John McCall6e266892010-01-26 03:27:55 +000010015Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
10016 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +000010017 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010018 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010019
10020 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
10021 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
10022 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +000010023 // TODO: provide better source location info.
10024 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010025
John McCall5acb0c92011-10-17 18:40:02 +000010026 if (checkPlaceholderForOverload(*this, Input))
10027 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010028
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010029 Expr *Args[2] = { Input, 0 };
10030 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +000010031
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010032 // For post-increment and post-decrement, add the implicit '0' as
10033 // the second argument, so that we know this is a post-increment or
10034 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +000010035 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010036 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +000010037 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
10038 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010039 NumArgs = 2;
10040 }
10041
10042 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010043 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +000010044 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010045 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010046 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010047 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +000010048 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010049
John McCallc373d482010-01-27 01:50:18 +000010050 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +000010051 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010052 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010053 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010054 /*ADL*/ true, IsOverloaded(Fns),
10055 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010056 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010057 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010058 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010059 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010060 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010061 }
10062
10063 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010064 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010065
10066 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010067 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10068 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010069
10070 // Add operator candidates that are member functions.
10071 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10072
John McCall6e266892010-01-26 03:27:55 +000010073 // Add candidates from ADL.
10074 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010075 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010076 /*ExplicitTemplateArgs*/ 0,
10077 CandidateSet);
10078
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010079 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010080 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010081
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010082 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10083
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010084 // Perform overload resolution.
10085 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010086 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010087 case OR_Success: {
10088 // We found a built-in operator or an overloaded operator.
10089 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010090
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010091 if (FnDecl) {
10092 // We matched an overloaded operator. Build a call to that
10093 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010094
Eli Friedman5f2987c2012-02-02 03:46:19 +000010095 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010096
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010097 // Convert the arguments.
10098 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010099 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010100
John Wiegley429bb272011-04-08 18:41:53 +000010101 ExprResult InputRes =
10102 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10103 Best->FoundDecl, Method);
10104 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010105 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010106 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010107 } else {
10108 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010109 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010110 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010111 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010112 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010113 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010114 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010115 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010116 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010117 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010118 }
10119
John McCallb697e082010-05-06 18:15:07 +000010120 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10121
John McCallf89e55a2010-11-18 06:31:45 +000010122 // Determine the result type.
10123 QualType ResultTy = FnDecl->getResultType();
10124 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10125 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010126
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010127 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010128 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010129 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010130 if (FnExpr.isInvalid())
10131 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010132
Eli Friedman4c3b8962009-11-18 03:58:17 +000010133 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010134 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010135 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010136 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010137 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010138
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010139 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010140 FnDecl))
10141 return ExprError();
10142
John McCall9ae2f072010-08-23 23:25:46 +000010143 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010144 } else {
10145 // We matched a built-in operator. Convert the arguments, then
10146 // break out so that we will build the appropriate built-in
10147 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010148 ExprResult InputRes =
10149 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10150 Best->Conversions[0], AA_Passing);
10151 if (InputRes.isInvalid())
10152 return ExprError();
10153 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010154 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010155 }
John Wiegley429bb272011-04-08 18:41:53 +000010156 }
10157
10158 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010159 // This is an erroneous use of an operator which can be overloaded by
10160 // a non-member function. Check for non-member operators which were
10161 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010162 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10163 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010164 // FIXME: Recover by calling the found function.
10165 return ExprError();
10166
John Wiegley429bb272011-04-08 18:41:53 +000010167 // No viable function; fall through to handling this as a
10168 // built-in operator, which will produce an error message for us.
10169 break;
10170
10171 case OR_Ambiguous:
10172 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10173 << UnaryOperator::getOpcodeStr(Opc)
10174 << Input->getType()
10175 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010176 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10177 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010178 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10179 return ExprError();
10180
10181 case OR_Deleted:
10182 Diag(OpLoc, diag::err_ovl_deleted_oper)
10183 << Best->Function->isDeleted()
10184 << UnaryOperator::getOpcodeStr(Opc)
10185 << getDeletedOrUnavailableSuffix(Best->Function)
10186 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010187 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10188 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010189 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010190 return ExprError();
10191 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010192
10193 // Either we found no viable overloaded operator or we matched a
10194 // built-in operator. In either case, fall through to trying to
10195 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010196 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010197}
10198
Douglas Gregor063daf62009-03-13 18:40:31 +000010199/// \brief Create a binary operation that may resolve to an overloaded
10200/// operator.
10201///
10202/// \param OpLoc The location of the operator itself (e.g., '+').
10203///
10204/// \param OpcIn The BinaryOperator::Opcode that describes this
10205/// operator.
10206///
James Dennett40ae6662012-06-22 08:52:37 +000010207/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010208/// considered by overload resolution. The caller needs to build this
10209/// set based on the context using, e.g.,
10210/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10211/// set should not contain any member functions; those will be added
10212/// by CreateOverloadedBinOp().
10213///
10214/// \param LHS Left-hand argument.
10215/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010216ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010217Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010218 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010219 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010220 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010221 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010222 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010223
10224 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10225 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10226 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10227
10228 // If either side is type-dependent, create an appropriate dependent
10229 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010230 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010231 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010232 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010233 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010234 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010235 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010236 Context.DependentTy,
10237 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010238 OpLoc,
10239 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010240
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010241 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10242 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010243 VK_LValue,
10244 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010245 Context.DependentTy,
10246 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010247 OpLoc,
10248 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010249 }
John McCall6e266892010-01-26 03:27:55 +000010250
10251 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010252 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010253 // TODO: provide better source location info in DNLoc component.
10254 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010255 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010256 = UnresolvedLookupExpr::Create(Context, NamingClass,
10257 NestedNameSpecifierLoc(), OpNameInfo,
10258 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010259 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010260 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10261 Context.DependentTy, VK_RValue,
10262 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010263 }
10264
John McCall5acb0c92011-10-17 18:40:02 +000010265 // Always do placeholder-like conversions on the RHS.
10266 if (checkPlaceholderForOverload(*this, Args[1]))
10267 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010268
John McCall3c3b7f92011-10-25 17:37:35 +000010269 // Do placeholder-like conversion on the LHS; note that we should
10270 // not get here with a PseudoObject LHS.
10271 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010272 if (checkPlaceholderForOverload(*this, Args[0]))
10273 return ExprError();
10274
Sebastian Redl275c2b42009-11-18 23:10:33 +000010275 // If this is the assignment operator, we only perform overload resolution
10276 // if the left-hand side is a class or enumeration type. This is actually
10277 // a hack. The standard requires that we do overload resolution between the
10278 // various built-in candidates, but as DR507 points out, this can lead to
10279 // problems. So we do it this way, which pretty much follows what GCC does.
10280 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010281 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010282 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010283
John McCall0e800c92010-12-04 08:14:53 +000010284 // If this is the .* operator, which is not overloadable, just
10285 // create a built-in binary operator.
10286 if (Opc == BO_PtrMemD)
10287 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10288
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010289 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010290 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010291
10292 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010293 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010294
10295 // Add operator candidates that are member functions.
10296 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10297
John McCall6e266892010-01-26 03:27:55 +000010298 // Add candidates from ADL.
10299 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010300 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010301 /*ExplicitTemplateArgs*/ 0,
10302 CandidateSet);
10303
Douglas Gregor063daf62009-03-13 18:40:31 +000010304 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010305 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010306
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010307 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10308
Douglas Gregor063daf62009-03-13 18:40:31 +000010309 // Perform overload resolution.
10310 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010311 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010312 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010313 // We found a built-in operator or an overloaded operator.
10314 FunctionDecl *FnDecl = Best->Function;
10315
10316 if (FnDecl) {
10317 // We matched an overloaded operator. Build a call to that
10318 // operator.
10319
Eli Friedman5f2987c2012-02-02 03:46:19 +000010320 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010321
Douglas Gregor063daf62009-03-13 18:40:31 +000010322 // Convert the arguments.
10323 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010324 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010325 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010326
Chandler Carruth6df868e2010-12-12 08:17:55 +000010327 ExprResult Arg1 =
10328 PerformCopyInitialization(
10329 InitializedEntity::InitializeParameter(Context,
10330 FnDecl->getParamDecl(0)),
10331 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010332 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010333 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010334
John Wiegley429bb272011-04-08 18:41:53 +000010335 ExprResult Arg0 =
10336 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10337 Best->FoundDecl, Method);
10338 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010339 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010340 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010341 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010342 } else {
10343 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010344 ExprResult Arg0 = PerformCopyInitialization(
10345 InitializedEntity::InitializeParameter(Context,
10346 FnDecl->getParamDecl(0)),
10347 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010348 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010349 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010350
Chandler Carruth6df868e2010-12-12 08:17:55 +000010351 ExprResult Arg1 =
10352 PerformCopyInitialization(
10353 InitializedEntity::InitializeParameter(Context,
10354 FnDecl->getParamDecl(1)),
10355 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010356 if (Arg1.isInvalid())
10357 return ExprError();
10358 Args[0] = LHS = Arg0.takeAs<Expr>();
10359 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010360 }
10361
John McCallb697e082010-05-06 18:15:07 +000010362 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10363
John McCallf89e55a2010-11-18 06:31:45 +000010364 // Determine the result type.
10365 QualType ResultTy = FnDecl->getResultType();
10366 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10367 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010368
10369 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010370 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10371 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010372 if (FnExpr.isInvalid())
10373 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010374
John McCall9ae2f072010-08-23 23:25:46 +000010375 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010376 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010377 Args, ResultTy, VK, OpLoc,
10378 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010379
10380 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010381 FnDecl))
10382 return ExprError();
10383
Nick Lewycky9b7ea0d2013-01-24 02:03:08 +000010384 ArrayRef<const Expr *> ArgsArray(Args, 2);
10385 // Cut off the implicit 'this'.
10386 if (isa<CXXMethodDecl>(FnDecl))
10387 ArgsArray = ArgsArray.slice(1);
10388 checkCall(FnDecl, ArgsArray, 0, isa<CXXMethodDecl>(FnDecl), OpLoc,
10389 TheCall->getSourceRange(), VariadicDoesNotApply);
10390
John McCall9ae2f072010-08-23 23:25:46 +000010391 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010392 } else {
10393 // We matched a built-in operator. Convert the arguments, then
10394 // break out so that we will build the appropriate built-in
10395 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010396 ExprResult ArgsRes0 =
10397 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10398 Best->Conversions[0], AA_Passing);
10399 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010400 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010401 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010402
John Wiegley429bb272011-04-08 18:41:53 +000010403 ExprResult ArgsRes1 =
10404 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10405 Best->Conversions[1], AA_Passing);
10406 if (ArgsRes1.isInvalid())
10407 return ExprError();
10408 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010409 break;
10410 }
10411 }
10412
Douglas Gregor33074752009-09-30 21:46:01 +000010413 case OR_No_Viable_Function: {
10414 // C++ [over.match.oper]p9:
10415 // If the operator is the operator , [...] and there are no
10416 // viable functions, then the operator is assumed to be the
10417 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010418 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010419 break;
10420
Chandler Carruth6df868e2010-12-12 08:17:55 +000010421 // For class as left operand for assignment or compound assigment
10422 // operator do not fall through to handling in built-in, but report that
10423 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010424 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010425 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010426 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010427 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10428 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010429 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010430 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010431 // This is an erroneous use of an operator which can be overloaded by
10432 // a non-member function. Check for non-member operators which were
10433 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010434 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010435 // FIXME: Recover by calling the found function.
10436 return ExprError();
10437
Douglas Gregor33074752009-09-30 21:46:01 +000010438 // No viable function; try to create a built-in operation, which will
10439 // produce an error. Then, show the non-viable candidates.
10440 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010441 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010442 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010443 "C++ binary operator overloading is missing candidates!");
10444 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010445 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010446 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010447 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010448 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010449
10450 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010451 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010452 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010453 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010454 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010455 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010456 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010457 return ExprError();
10458
10459 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010460 if (isImplicitlyDeleted(Best->Function)) {
10461 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10462 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010463 << Context.getRecordType(Method->getParent())
10464 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010465
Richard Smith0f46e642012-12-28 12:23:24 +000010466 // The user probably meant to call this special member. Just
10467 // explain why it's deleted.
10468 NoteDeletedFunction(Method);
10469 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010470 } else {
10471 Diag(OpLoc, diag::err_ovl_deleted_oper)
10472 << Best->Function->isDeleted()
10473 << BinaryOperator::getOpcodeStr(Opc)
10474 << getDeletedOrUnavailableSuffix(Best->Function)
10475 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10476 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010477 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010478 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010479 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010480 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010481
Douglas Gregor33074752009-09-30 21:46:01 +000010482 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010483 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010484}
10485
John McCall60d7b3a2010-08-24 06:29:42 +000010486ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010487Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10488 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010489 Expr *Base, Expr *Idx) {
10490 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010491 DeclarationName OpName =
10492 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10493
10494 // If either side is type-dependent, create an appropriate dependent
10495 // expression.
10496 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10497
John McCallc373d482010-01-27 01:50:18 +000010498 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010499 // CHECKME: no 'operator' keyword?
10500 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10501 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010502 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010503 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010504 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010505 /*ADL*/ true, /*Overloaded*/ false,
10506 UnresolvedSetIterator(),
10507 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010508 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010509
Sebastian Redlf322ed62009-10-29 20:17:01 +000010510 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010511 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010512 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010513 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010514 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010515 }
10516
John McCall5acb0c92011-10-17 18:40:02 +000010517 // Handle placeholders on both operands.
10518 if (checkPlaceholderForOverload(*this, Args[0]))
10519 return ExprError();
10520 if (checkPlaceholderForOverload(*this, Args[1]))
10521 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010522
Sebastian Redlf322ed62009-10-29 20:17:01 +000010523 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010524 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010525
10526 // Subscript can only be overloaded as a member function.
10527
10528 // Add operator candidates that are member functions.
10529 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10530
10531 // Add builtin operator candidates.
10532 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10533
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010534 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10535
Sebastian Redlf322ed62009-10-29 20:17:01 +000010536 // Perform overload resolution.
10537 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010538 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010539 case OR_Success: {
10540 // We found a built-in operator or an overloaded operator.
10541 FunctionDecl *FnDecl = Best->Function;
10542
10543 if (FnDecl) {
10544 // We matched an overloaded operator. Build a call to that
10545 // operator.
10546
Eli Friedman5f2987c2012-02-02 03:46:19 +000010547 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010548
John McCall9aa472c2010-03-19 07:35:19 +000010549 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010550 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010551
Sebastian Redlf322ed62009-10-29 20:17:01 +000010552 // Convert the arguments.
10553 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010554 ExprResult Arg0 =
10555 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10556 Best->FoundDecl, Method);
10557 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010558 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010559 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010560
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010561 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010562 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010563 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010564 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010565 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010566 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010567 Owned(Args[1]));
10568 if (InputInit.isInvalid())
10569 return ExprError();
10570
10571 Args[1] = InputInit.takeAs<Expr>();
10572
Sebastian Redlf322ed62009-10-29 20:17:01 +000010573 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010574 QualType ResultTy = FnDecl->getResultType();
10575 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10576 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010577
10578 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010579 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10580 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010581 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10582 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010583 OpLocInfo.getLoc(),
10584 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010585 if (FnExpr.isInvalid())
10586 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010587
John McCall9ae2f072010-08-23 23:25:46 +000010588 CXXOperatorCallExpr *TheCall =
10589 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010590 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010591 ResultTy, VK, RLoc,
10592 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010593
John McCall9ae2f072010-08-23 23:25:46 +000010594 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010595 FnDecl))
10596 return ExprError();
10597
John McCall9ae2f072010-08-23 23:25:46 +000010598 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010599 } else {
10600 // We matched a built-in operator. Convert the arguments, then
10601 // break out so that we will build the appropriate built-in
10602 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010603 ExprResult ArgsRes0 =
10604 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10605 Best->Conversions[0], AA_Passing);
10606 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010607 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010608 Args[0] = ArgsRes0.take();
10609
10610 ExprResult ArgsRes1 =
10611 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10612 Best->Conversions[1], AA_Passing);
10613 if (ArgsRes1.isInvalid())
10614 return ExprError();
10615 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010616
10617 break;
10618 }
10619 }
10620
10621 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010622 if (CandidateSet.empty())
10623 Diag(LLoc, diag::err_ovl_no_oper)
10624 << Args[0]->getType() << /*subscript*/ 0
10625 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10626 else
10627 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10628 << Args[0]->getType()
10629 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010630 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010631 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010632 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010633 }
10634
10635 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010636 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010637 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010638 << Args[0]->getType() << Args[1]->getType()
10639 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010640 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010641 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010642 return ExprError();
10643
10644 case OR_Deleted:
10645 Diag(LLoc, diag::err_ovl_deleted_oper)
10646 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010647 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010648 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010649 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010650 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010651 return ExprError();
10652 }
10653
10654 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010655 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010656}
10657
Douglas Gregor88a35142008-12-22 05:46:06 +000010658/// BuildCallToMemberFunction - Build a call to a member
10659/// function. MemExpr is the expression that refers to the member
10660/// function (and includes the object parameter), Args/NumArgs are the
10661/// arguments to the function call (not including the object
10662/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010663/// expression refers to a non-static member function or an overloaded
10664/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010665ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010666Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10667 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010668 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010669 assert(MemExprE->getType() == Context.BoundMemberTy ||
10670 MemExprE->getType() == Context.OverloadTy);
10671
Douglas Gregor88a35142008-12-22 05:46:06 +000010672 // Dig out the member expression. This holds both the object
10673 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010674 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010675
John McCall864c0412011-04-26 20:42:42 +000010676 // Determine whether this is a call to a pointer-to-member function.
10677 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10678 assert(op->getType() == Context.BoundMemberTy);
10679 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10680
10681 QualType fnType =
10682 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10683
10684 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10685 QualType resultType = proto->getCallResultType(Context);
10686 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10687
10688 // Check that the object type isn't more qualified than the
10689 // member function we're calling.
10690 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10691
10692 QualType objectType = op->getLHS()->getType();
10693 if (op->getOpcode() == BO_PtrMemI)
10694 objectType = objectType->castAs<PointerType>()->getPointeeType();
10695 Qualifiers objectQuals = objectType.getQualifiers();
10696
10697 Qualifiers difference = objectQuals - funcQuals;
10698 difference.removeObjCGCAttr();
10699 difference.removeAddressSpace();
10700 if (difference) {
10701 std::string qualsString = difference.getAsString();
10702 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10703 << fnType.getUnqualifiedType()
10704 << qualsString
10705 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10706 }
10707
10708 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010709 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10710 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010711 resultType, valueKind, RParenLoc);
10712
10713 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010714 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010715 call, 0))
10716 return ExprError();
10717
10718 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10719 return ExprError();
10720
10721 return MaybeBindToTemporary(call);
10722 }
10723
John McCall5acb0c92011-10-17 18:40:02 +000010724 UnbridgedCastsSet UnbridgedCasts;
10725 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10726 return ExprError();
10727
John McCall129e2df2009-11-30 22:42:35 +000010728 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010729 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010730 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010731 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010732 if (isa<MemberExpr>(NakedMemExpr)) {
10733 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010734 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010735 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010736 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010737 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010738 } else {
10739 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010740 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010741
John McCall701c89e2009-12-03 04:06:58 +000010742 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010743 Expr::Classification ObjectClassification
10744 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10745 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010746
Douglas Gregor88a35142008-12-22 05:46:06 +000010747 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010748 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010749
John McCallaa81e162009-12-01 22:10:20 +000010750 // FIXME: avoid copy.
10751 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10752 if (UnresExpr->hasExplicitTemplateArgs()) {
10753 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10754 TemplateArgs = &TemplateArgsBuffer;
10755 }
10756
John McCall129e2df2009-11-30 22:42:35 +000010757 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10758 E = UnresExpr->decls_end(); I != E; ++I) {
10759
John McCall701c89e2009-12-03 04:06:58 +000010760 NamedDecl *Func = *I;
10761 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10762 if (isa<UsingShadowDecl>(Func))
10763 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10764
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010765
Francois Pichetdbee3412011-01-18 05:04:39 +000010766 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010767 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010768 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10769 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010770 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010771 // If explicit template arguments were provided, we can't call a
10772 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010773 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010774 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010775
John McCall9aa472c2010-03-19 07:35:19 +000010776 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010777 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010778 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010779 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010780 } else {
John McCall129e2df2009-11-30 22:42:35 +000010781 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010782 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010783 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010784 llvm::makeArrayRef(Args, NumArgs),
10785 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010786 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010787 }
Douglas Gregordec06662009-08-21 18:42:58 +000010788 }
Mike Stump1eb44332009-09-09 15:08:12 +000010789
John McCall129e2df2009-11-30 22:42:35 +000010790 DeclarationName DeclName = UnresExpr->getMemberName();
10791
John McCall5acb0c92011-10-17 18:40:02 +000010792 UnbridgedCasts.restore();
10793
Douglas Gregor88a35142008-12-22 05:46:06 +000010794 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010795 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010796 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010797 case OR_Success:
10798 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010799 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010800 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010801 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010802 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010803 break;
10804
10805 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010806 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010807 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010808 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010809 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10810 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010811 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010812 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010813
10814 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010815 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010816 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010817 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10818 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010819 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010820 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010821
10822 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010823 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010824 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010825 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010826 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010827 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010828 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10829 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010830 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010831 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010832 }
10833
John McCall6bb80172010-03-30 21:47:33 +000010834 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010835
John McCallaa81e162009-12-01 22:10:20 +000010836 // If overload resolution picked a static member, build a
10837 // non-member call based on that function.
10838 if (Method->isStatic()) {
10839 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10840 Args, NumArgs, RParenLoc);
10841 }
10842
John McCall129e2df2009-11-30 22:42:35 +000010843 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010844 }
10845
John McCallf89e55a2010-11-18 06:31:45 +000010846 QualType ResultType = Method->getResultType();
10847 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10848 ResultType = ResultType.getNonLValueExprType(Context);
10849
Douglas Gregor88a35142008-12-22 05:46:06 +000010850 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010851 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010852 new (Context) CXXMemberCallExpr(Context, MemExprE,
10853 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010854 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010855
Anders Carlssoneed3e692009-10-10 00:06:20 +000010856 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010857 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010858 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010859 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010860
Douglas Gregor88a35142008-12-22 05:46:06 +000010861 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010862 // We only need to do this if there was actually an overload; otherwise
10863 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010864 if (!Method->isStatic()) {
10865 ExprResult ObjectArg =
10866 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10867 FoundDecl, Method);
10868 if (ObjectArg.isInvalid())
10869 return ExprError();
10870 MemExpr->setBase(ObjectArg.take());
10871 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010872
10873 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010874 const FunctionProtoType *Proto =
10875 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010876 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010877 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010878 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010879
Eli Friedmane61eb042012-02-18 04:48:30 +000010880 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10881
Richard Smith831421f2012-06-25 20:30:08 +000010882 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010883 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010884
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010885 if ((isa<CXXConstructorDecl>(CurContext) ||
10886 isa<CXXDestructorDecl>(CurContext)) &&
10887 TheCall->getMethodDecl()->isPure()) {
10888 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10889
Chandler Carruthae198062011-06-27 08:31:58 +000010890 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010891 Diag(MemExpr->getLocStart(),
10892 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10893 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10894 << MD->getParent()->getDeclName();
10895
10896 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010897 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010898 }
John McCall9ae2f072010-08-23 23:25:46 +000010899 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010900}
10901
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010902/// BuildCallToObjectOfClassType - Build a call to an object of class
10903/// type (C++ [over.call.object]), which can end up invoking an
10904/// overloaded function call operator (@c operator()) or performing a
10905/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010906ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010907Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010908 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010909 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010910 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010911 if (checkPlaceholderForOverload(*this, Obj))
10912 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010913 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010914
10915 UnbridgedCastsSet UnbridgedCasts;
10916 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10917 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010918
John Wiegley429bb272011-04-08 18:41:53 +000010919 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10920 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010921
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010922 // C++ [over.call.object]p1:
10923 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010924 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010925 // candidate functions includes at least the function call
10926 // operators of T. The function call operators of T are obtained by
10927 // ordinary lookup of the name operator() in the context of
10928 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010929 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010930 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010931
John Wiegley429bb272011-04-08 18:41:53 +000010932 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010933 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010934 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010935
John McCalla24dc2e2009-11-17 02:14:36 +000010936 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10937 LookupQualifiedName(R, Record->getDecl());
10938 R.suppressDiagnostics();
10939
Douglas Gregor593564b2009-11-15 07:48:03 +000010940 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010941 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010942 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10943 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010944 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010945 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010946
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010947 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010948 // In addition, for each (non-explicit in C++0x) conversion function
10949 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010950 //
10951 // operator conversion-type-id () cv-qualifier;
10952 //
10953 // where cv-qualifier is the same cv-qualification as, or a
10954 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010955 // denotes the type "pointer to function of (P1,...,Pn) returning
10956 // R", or the type "reference to pointer to function of
10957 // (P1,...,Pn) returning R", or the type "reference to function
10958 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010959 // is also considered as a candidate function. Similarly,
10960 // surrogate call functions are added to the set of candidate
10961 // functions for each conversion function declared in an
10962 // accessible base class provided the function is not hidden
10963 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010964 std::pair<CXXRecordDecl::conversion_iterator,
10965 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010966 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010967 for (CXXRecordDecl::conversion_iterator
10968 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010969 NamedDecl *D = *I;
10970 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10971 if (isa<UsingShadowDecl>(D))
10972 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010973
Douglas Gregor4a27d702009-10-21 06:18:39 +000010974 // Skip over templated conversion functions; they aren't
10975 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010976 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010977 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010978
John McCall701c89e2009-12-03 04:06:58 +000010979 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010980 if (!Conv->isExplicit()) {
10981 // Strip the reference type (if any) and then the pointer type (if
10982 // any) to get down to what might be a function type.
10983 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10984 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10985 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010986
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010987 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10988 {
10989 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010990 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10991 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010992 }
10993 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010994 }
Mike Stump1eb44332009-09-09 15:08:12 +000010995
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010996 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10997
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010998 // Perform overload resolution.
10999 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000011000 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000011001 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011002 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011003 // Overload resolution succeeded; we'll build the appropriate call
11004 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011005 break;
11006
11007 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000011008 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000011009 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000011010 << Object.get()->getType() << /*call*/ 1
11011 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000011012 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000011013 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000011014 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011015 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011016 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11017 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011018 break;
11019
11020 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011021 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011022 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000011023 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011024 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
11025 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011026 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011027
11028 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000011029 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011030 diag::err_ovl_deleted_object_call)
11031 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000011032 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011033 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000011034 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011035 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
11036 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011037 break;
Mike Stump1eb44332009-09-09 15:08:12 +000011038 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011039
Douglas Gregorff331c12010-07-25 18:17:45 +000011040 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011041 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011042
John McCall5acb0c92011-10-17 18:40:02 +000011043 UnbridgedCasts.restore();
11044
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011045 if (Best->Function == 0) {
11046 // Since there is no function declaration, this is one of the
11047 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000011048 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011049 = cast<CXXConversionDecl>(
11050 Best->Conversions[0].UserDefined.ConversionFunction);
11051
John Wiegley429bb272011-04-08 18:41:53 +000011052 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011053 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011054
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011055 // We selected one of the surrogate functions that converts the
11056 // object parameter to a function pointer. Perform the conversion
11057 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011058
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000011059 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000011060 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011061 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
11062 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011063 if (Call.isInvalid())
11064 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000011065 // Record usage of conversion in an implicit cast.
11066 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11067 CK_UserDefinedConversion,
11068 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011069
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011070 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011071 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011072 }
11073
Eli Friedman5f2987c2012-02-02 03:46:19 +000011074 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011075 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011076 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011077
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011078 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11079 // that calls this method, using Object for the implicit object
11080 // parameter and passing along the remaining arguments.
11081 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011082
11083 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011084 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011085 return ExprError();
11086
Chandler Carruth6df868e2010-12-12 08:17:55 +000011087 const FunctionProtoType *Proto =
11088 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011089
11090 unsigned NumArgsInProto = Proto->getNumArgs();
11091 unsigned NumArgsToCheck = NumArgs;
11092
11093 // Build the full argument list for the method call (the
11094 // implicit object parameter is placed at the beginning of the
11095 // list).
11096 Expr **MethodArgs;
11097 if (NumArgs < NumArgsInProto) {
11098 NumArgsToCheck = NumArgsInProto;
11099 MethodArgs = new Expr*[NumArgsInProto + 1];
11100 } else {
11101 MethodArgs = new Expr*[NumArgs + 1];
11102 }
John Wiegley429bb272011-04-08 18:41:53 +000011103 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011104 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11105 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011106
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011107 DeclarationNameInfo OpLocInfo(
11108 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11109 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011110 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011111 HadMultipleCandidates,
11112 OpLocInfo.getLoc(),
11113 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011114 if (NewFn.isInvalid())
11115 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011116
11117 // Once we've built TheCall, all of the expressions are properly
11118 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011119 QualType ResultTy = Method->getResultType();
11120 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11121 ResultTy = ResultTy.getNonLValueExprType(Context);
11122
John McCall9ae2f072010-08-23 23:25:46 +000011123 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011124 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011125 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011126 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011127 delete [] MethodArgs;
11128
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011129 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011130 Method))
11131 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011132
Douglas Gregor518fda12009-01-13 05:10:00 +000011133 // We may have default arguments. If so, we need to allocate more
11134 // slots in the call for them.
11135 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011136 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011137 else if (NumArgs > NumArgsInProto)
11138 NumArgsToCheck = NumArgsInProto;
11139
Chris Lattner312531a2009-04-12 08:11:20 +000011140 bool IsError = false;
11141
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011142 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011143 ExprResult ObjRes =
11144 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11145 Best->FoundDecl, Method);
11146 if (ObjRes.isInvalid())
11147 IsError = true;
11148 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011149 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011150 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011151
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011152 // Check the argument types.
11153 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011154 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011155 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011156 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011157
Douglas Gregor518fda12009-01-13 05:10:00 +000011158 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011159
John McCall60d7b3a2010-08-24 06:29:42 +000011160 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011161 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011162 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011163 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011164 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011165
Anders Carlsson3faa4862010-01-29 18:43:53 +000011166 IsError |= InputInit.isInvalid();
11167 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011168 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011169 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011170 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11171 if (DefArg.isInvalid()) {
11172 IsError = true;
11173 break;
11174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011175
Douglas Gregord47c47d2009-11-09 19:27:57 +000011176 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011177 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011178
11179 TheCall->setArg(i + 1, Arg);
11180 }
11181
11182 // If this is a variadic call, handle args passed through "...".
11183 if (Proto->isVariadic()) {
11184 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011185 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011186 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11187 IsError |= Arg.isInvalid();
11188 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011189 }
11190 }
11191
Chris Lattner312531a2009-04-12 08:11:20 +000011192 if (IsError) return true;
11193
Eli Friedmane61eb042012-02-18 04:48:30 +000011194 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11195
Richard Smith831421f2012-06-25 20:30:08 +000011196 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011197 return true;
11198
John McCall182f7092010-08-24 06:09:16 +000011199 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011200}
11201
Douglas Gregor8ba10742008-11-20 16:27:02 +000011202/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011203/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011204/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011205ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011206Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011207 assert(Base->getType()->isRecordType() &&
11208 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011209
John McCall5acb0c92011-10-17 18:40:02 +000011210 if (checkPlaceholderForOverload(*this, Base))
11211 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011212
John McCall5769d612010-02-08 23:07:23 +000011213 SourceLocation Loc = Base->getExprLoc();
11214
Douglas Gregor8ba10742008-11-20 16:27:02 +000011215 // C++ [over.ref]p1:
11216 //
11217 // [...] An expression x->m is interpreted as (x.operator->())->m
11218 // for a class object x of type T if T::operator->() exists and if
11219 // the operator is selected as the best match function by the
11220 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011221 DeclarationName OpName =
11222 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011223 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011224 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011225
John McCall5769d612010-02-08 23:07:23 +000011226 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011227 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011228 return ExprError();
11229
John McCalla24dc2e2009-11-17 02:14:36 +000011230 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11231 LookupQualifiedName(R, BaseRecord->getDecl());
11232 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011233
11234 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011235 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011236 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11237 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011238 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011239
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011240 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11241
Douglas Gregor8ba10742008-11-20 16:27:02 +000011242 // Perform overload resolution.
11243 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011244 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011245 case OR_Success:
11246 // Overload resolution succeeded; we'll build the call below.
11247 break;
11248
11249 case OR_No_Viable_Function:
11250 if (CandidateSet.empty())
11251 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011252 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011253 else
11254 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011255 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011256 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011257 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011258
11259 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011260 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11261 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011262 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011263 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011264
11265 case OR_Deleted:
11266 Diag(OpLoc, diag::err_ovl_deleted_oper)
11267 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011268 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011269 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011270 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011271 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011272 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011273 }
11274
Eli Friedman5f2987c2012-02-02 03:46:19 +000011275 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011276 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011277 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011278
Douglas Gregor8ba10742008-11-20 16:27:02 +000011279 // Convert the object parameter.
11280 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011281 ExprResult BaseResult =
11282 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11283 Best->FoundDecl, Method);
11284 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011285 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011286 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011287
Douglas Gregor8ba10742008-11-20 16:27:02 +000011288 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011289 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011290 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011291 if (FnExpr.isInvalid())
11292 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011293
John McCallf89e55a2010-11-18 06:31:45 +000011294 QualType ResultTy = Method->getResultType();
11295 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11296 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011297 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011298 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011299 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011300
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011301 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011302 Method))
11303 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011304
11305 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011306}
11307
Richard Smith36f5cfe2012-03-09 08:00:36 +000011308/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11309/// a literal operator described by the provided lookup results.
11310ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11311 DeclarationNameInfo &SuffixInfo,
11312 ArrayRef<Expr*> Args,
11313 SourceLocation LitEndLoc,
11314 TemplateArgumentListInfo *TemplateArgs) {
11315 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011316
Richard Smith36f5cfe2012-03-09 08:00:36 +000011317 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11318 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11319 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011320
Richard Smith36f5cfe2012-03-09 08:00:36 +000011321 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11322
Richard Smith36f5cfe2012-03-09 08:00:36 +000011323 // Perform overload resolution. This will usually be trivial, but might need
11324 // to perform substitutions for a literal operator template.
11325 OverloadCandidateSet::iterator Best;
11326 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11327 case OR_Success:
11328 case OR_Deleted:
11329 break;
11330
11331 case OR_No_Viable_Function:
11332 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11333 << R.getLookupName();
11334 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11335 return ExprError();
11336
11337 case OR_Ambiguous:
11338 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11339 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11340 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011341 }
11342
Richard Smith36f5cfe2012-03-09 08:00:36 +000011343 FunctionDecl *FD = Best->Function;
11344 MarkFunctionReferenced(UDSuffixLoc, FD);
11345 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011346
Richard Smith36f5cfe2012-03-09 08:00:36 +000011347 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11348 SuffixInfo.getLoc(),
11349 SuffixInfo.getInfo());
11350 if (Fn.isInvalid())
11351 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011352
11353 // Check the argument types. This should almost always be a no-op, except
11354 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011355 Expr *ConvArgs[2];
11356 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11357 ExprResult InputInit = PerformCopyInitialization(
11358 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11359 SourceLocation(), Args[ArgIdx]);
11360 if (InputInit.isInvalid())
11361 return true;
11362 ConvArgs[ArgIdx] = InputInit.take();
11363 }
11364
Richard Smith9fcce652012-03-07 08:35:16 +000011365 QualType ResultTy = FD->getResultType();
11366 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11367 ResultTy = ResultTy.getNonLValueExprType(Context);
11368
Richard Smith9fcce652012-03-07 08:35:16 +000011369 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011370 new (Context) UserDefinedLiteral(Context, Fn.take(),
11371 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011372 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11373
11374 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11375 return ExprError();
11376
Richard Smith831421f2012-06-25 20:30:08 +000011377 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011378 return ExprError();
11379
11380 return MaybeBindToTemporary(UDL);
11381}
11382
Sam Panzere1715b62012-08-21 00:52:01 +000011383/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11384/// given LookupResult is non-empty, it is assumed to describe a member which
11385/// will be invoked. Otherwise, the function will be found via argument
11386/// dependent lookup.
11387/// CallExpr is set to a valid expression and FRS_Success returned on success,
11388/// otherwise CallExpr is set to ExprError() and some non-success value
11389/// is returned.
11390Sema::ForRangeStatus
11391Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11392 SourceLocation RangeLoc, VarDecl *Decl,
11393 BeginEndFunction BEF,
11394 const DeclarationNameInfo &NameInfo,
11395 LookupResult &MemberLookup,
11396 OverloadCandidateSet *CandidateSet,
11397 Expr *Range, ExprResult *CallExpr) {
11398 CandidateSet->clear();
11399 if (!MemberLookup.empty()) {
11400 ExprResult MemberRef =
11401 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11402 /*IsPtr=*/false, CXXScopeSpec(),
11403 /*TemplateKWLoc=*/SourceLocation(),
11404 /*FirstQualifierInScope=*/0,
11405 MemberLookup,
11406 /*TemplateArgs=*/0);
11407 if (MemberRef.isInvalid()) {
11408 *CallExpr = ExprError();
11409 Diag(Range->getLocStart(), diag::note_in_for_range)
11410 << RangeLoc << BEF << Range->getType();
11411 return FRS_DiagnosticIssued;
11412 }
11413 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11414 if (CallExpr->isInvalid()) {
11415 *CallExpr = ExprError();
11416 Diag(Range->getLocStart(), diag::note_in_for_range)
11417 << RangeLoc << BEF << Range->getType();
11418 return FRS_DiagnosticIssued;
11419 }
11420 } else {
11421 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011422 UnresolvedLookupExpr *Fn =
11423 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11424 NestedNameSpecifierLoc(), NameInfo,
11425 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011426 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011427
11428 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11429 CandidateSet, CallExpr);
11430 if (CandidateSet->empty() || CandidateSetError) {
11431 *CallExpr = ExprError();
11432 return FRS_NoViableFunction;
11433 }
11434 OverloadCandidateSet::iterator Best;
11435 OverloadingResult OverloadResult =
11436 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11437
11438 if (OverloadResult == OR_No_Viable_Function) {
11439 *CallExpr = ExprError();
11440 return FRS_NoViableFunction;
11441 }
11442 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11443 Loc, 0, CandidateSet, &Best,
11444 OverloadResult,
11445 /*AllowTypoCorrection=*/false);
11446 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11447 *CallExpr = ExprError();
11448 Diag(Range->getLocStart(), diag::note_in_for_range)
11449 << RangeLoc << BEF << Range->getType();
11450 return FRS_DiagnosticIssued;
11451 }
11452 }
11453 return FRS_Success;
11454}
11455
11456
Douglas Gregor904eed32008-11-10 20:40:00 +000011457/// FixOverloadedFunctionReference - E is an expression that refers to
11458/// a C++ overloaded function (possibly with some parentheses and
11459/// perhaps a '&' around it). We have resolved the overloaded function
11460/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011461/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011462Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011463 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011464 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011465 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11466 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011467 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011468 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011469
Douglas Gregor699ee522009-11-20 19:42:02 +000011470 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011471 }
11472
Douglas Gregor699ee522009-11-20 19:42:02 +000011473 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011474 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11475 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011476 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011477 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011478 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011479 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011480 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011481 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011482
11483 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011484 ICE->getCastKind(),
11485 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011486 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011487 }
11488
Douglas Gregor699ee522009-11-20 19:42:02 +000011489 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011490 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011491 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011492 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11493 if (Method->isStatic()) {
11494 // Do nothing: static member functions aren't any different
11495 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011496 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011497 // Fix the sub expression, which really has to be an
11498 // UnresolvedLookupExpr holding an overloaded member function
11499 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011500 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11501 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011502 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011503 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011504
John McCallba135432009-11-21 08:51:07 +000011505 assert(isa<DeclRefExpr>(SubExpr)
11506 && "fixed to something other than a decl ref");
11507 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11508 && "fixed to a member ref with no nested name qualifier");
11509
11510 // We have taken the address of a pointer to member
11511 // function. Perform the computation here so that we get the
11512 // appropriate pointer to member type.
11513 QualType ClassType
11514 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11515 QualType MemPtrType
11516 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11517
John McCallf89e55a2010-11-18 06:31:45 +000011518 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11519 VK_RValue, OK_Ordinary,
11520 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011521 }
11522 }
John McCall6bb80172010-03-30 21:47:33 +000011523 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11524 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011525 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011526 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011527
John McCall2de56d12010-08-25 11:45:40 +000011528 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011529 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011530 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011531 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011532 }
John McCallba135432009-11-21 08:51:07 +000011533
11534 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011535 // FIXME: avoid copy.
11536 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011537 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011538 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11539 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011540 }
11541
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011542 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11543 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011544 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011545 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011546 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011547 ULE->getNameLoc(),
11548 Fn->getType(),
11549 VK_LValue,
11550 Found.getDecl(),
11551 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011552 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011553 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11554 return DRE;
John McCallba135432009-11-21 08:51:07 +000011555 }
11556
John McCall129e2df2009-11-30 22:42:35 +000011557 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011558 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011559 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11560 if (MemExpr->hasExplicitTemplateArgs()) {
11561 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11562 TemplateArgs = &TemplateArgsBuffer;
11563 }
John McCalld5532b62009-11-23 01:53:49 +000011564
John McCallaa81e162009-12-01 22:10:20 +000011565 Expr *Base;
11566
John McCallf89e55a2010-11-18 06:31:45 +000011567 // If we're filling in a static method where we used to have an
11568 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011569 if (MemExpr->isImplicitAccess()) {
11570 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011571 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11572 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011573 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011574 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011575 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011576 MemExpr->getMemberLoc(),
11577 Fn->getType(),
11578 VK_LValue,
11579 Found.getDecl(),
11580 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011581 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011582 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11583 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011584 } else {
11585 SourceLocation Loc = MemExpr->getMemberLoc();
11586 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011587 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011588 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011589 Base = new (Context) CXXThisExpr(Loc,
11590 MemExpr->getBaseType(),
11591 /*isImplicit=*/true);
11592 }
John McCallaa81e162009-12-01 22:10:20 +000011593 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011594 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011595
John McCallf5307512011-04-27 00:36:17 +000011596 ExprValueKind valueKind;
11597 QualType type;
11598 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11599 valueKind = VK_LValue;
11600 type = Fn->getType();
11601 } else {
11602 valueKind = VK_RValue;
11603 type = Context.BoundMemberTy;
11604 }
11605
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011606 MemberExpr *ME = MemberExpr::Create(Context, Base,
11607 MemExpr->isArrow(),
11608 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011609 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011610 Fn,
11611 Found,
11612 MemExpr->getMemberNameInfo(),
11613 TemplateArgs,
11614 type, valueKind, OK_Ordinary);
11615 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011616 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011617 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011618 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011619
John McCall3fa5cae2010-10-26 07:05:15 +000011620 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011621}
11622
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011623ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011624 DeclAccessPair Found,
11625 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011626 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011627}
11628
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011629} // end namespace clang