blob: 007ea0fdcdab44c7a0c985494f6828e31cec0e39 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000044 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000052}
53
John McCall120d63c2010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor60d62c22008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202}
203
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000242bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregorf9af5242011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000261/// Skip any implicit casts which could be either part of a narrowing conversion
262/// or after one in an implicit conversion.
263static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
264 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
265 switch (ICE->getCastKind()) {
266 case CK_NoOp:
267 case CK_IntegralCast:
268 case CK_IntegralToBoolean:
269 case CK_IntegralToFloating:
270 case CK_FloatingToIntegral:
271 case CK_FloatingToBoolean:
272 case CK_FloatingCast:
273 Converted = ICE->getSubExpr();
274 continue;
275
276 default:
277 return Converted;
278 }
279 }
280
281 return Converted;
282}
283
284/// Check if this standard conversion sequence represents a narrowing
285/// conversion, according to C++11 [dcl.init.list]p7.
286///
287/// \param Ctx The AST context.
288/// \param Converted The result of applying this standard conversion sequence.
289/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
290/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000291/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
292/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000293NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000294StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
295 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000296 APValue &ConstantValue,
297 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000298 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000299
300 // C++11 [dcl.init.list]p7:
301 // A narrowing conversion is an implicit conversion ...
302 QualType FromType = getToType(0);
303 QualType ToType = getToType(1);
304 switch (Second) {
305 // -- from a floating-point type to an integer type, or
306 //
307 // -- from an integer type or unscoped enumeration type to a floating-point
308 // type, except where the source is a constant expression and the actual
309 // value after conversion will fit into the target type and will produce
310 // the original value when converted back to the original type, or
311 case ICK_Floating_Integral:
312 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
313 return NK_Type_Narrowing;
314 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
315 llvm::APSInt IntConstantValue;
316 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
317 if (Initializer &&
318 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
319 // Convert the integer to the floating type.
320 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
321 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
322 llvm::APFloat::rmNearestTiesToEven);
323 // And back.
324 llvm::APSInt ConvertedValue = IntConstantValue;
325 bool ignored;
326 Result.convertToInteger(ConvertedValue,
327 llvm::APFloat::rmTowardZero, &ignored);
328 // If the resulting value is different, this was a narrowing conversion.
329 if (IntConstantValue != ConvertedValue) {
330 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000331 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000332 return NK_Constant_Narrowing;
333 }
334 } else {
335 // Variables are always narrowings.
336 return NK_Variable_Narrowing;
337 }
338 }
339 return NK_Not_Narrowing;
340
341 // -- from long double to double or float, or from double to float, except
342 // where the source is a constant expression and the actual value after
343 // conversion is within the range of values that can be represented (even
344 // if it cannot be represented exactly), or
345 case ICK_Floating_Conversion:
346 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
347 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
348 // FromType is larger than ToType.
349 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
350 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
351 // Constant!
352 assert(ConstantValue.isFloat());
353 llvm::APFloat FloatVal = ConstantValue.getFloat();
354 // Convert the source value into the target type.
355 bool ignored;
356 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
357 Ctx.getFloatTypeSemantics(ToType),
358 llvm::APFloat::rmNearestTiesToEven, &ignored);
359 // If there was no overflow, the source value is within the range of
360 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000361 if (ConvertStatus & llvm::APFloat::opOverflow) {
362 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000363 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000364 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000365 } else {
366 return NK_Variable_Narrowing;
367 }
368 }
369 return NK_Not_Narrowing;
370
371 // -- from an integer type or unscoped enumeration type to an integer type
372 // that cannot represent all the values of the original type, except where
373 // the source is a constant expression and the actual value after
374 // conversion will fit into the target type and will produce the original
375 // value when converted back to the original type.
376 case ICK_Boolean_Conversion: // Bools are integers too.
377 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
378 // Boolean conversions can be from pointers and pointers to members
379 // [conv.bool], and those aren't considered narrowing conversions.
380 return NK_Not_Narrowing;
381 } // Otherwise, fall through to the integral case.
382 case ICK_Integral_Conversion: {
383 assert(FromType->isIntegralOrUnscopedEnumerationType());
384 assert(ToType->isIntegralOrUnscopedEnumerationType());
385 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
386 const unsigned FromWidth = Ctx.getIntWidth(FromType);
387 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
388 const unsigned ToWidth = Ctx.getIntWidth(ToType);
389
390 if (FromWidth > ToWidth ||
391 (FromWidth == ToWidth && FromSigned != ToSigned)) {
392 // Not all values of FromType can be represented in ToType.
393 llvm::APSInt InitializerValue;
394 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
395 if (Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
396 ConstantValue = APValue(InitializerValue);
397
398 // Add a bit to the InitializerValue so we don't have to worry about
399 // signed vs. unsigned comparisons.
400 InitializerValue = InitializerValue.extend(
401 InitializerValue.getBitWidth() + 1);
402 // Convert the initializer to and from the target width and signed-ness.
403 llvm::APSInt ConvertedValue = InitializerValue;
404 ConvertedValue = ConvertedValue.trunc(ToWidth);
405 ConvertedValue.setIsSigned(ToSigned);
406 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
407 ConvertedValue.setIsSigned(InitializerValue.isSigned());
408 // If the result is different, this was a narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000409 if (ConvertedValue != InitializerValue) {
410 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000411 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000412 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000413 } else {
414 // Variables are always narrowings.
415 return NK_Variable_Narrowing;
416 }
417 }
418 return NK_Not_Narrowing;
419 }
420
421 default:
422 // Other kinds of conversions are not narrowings.
423 return NK_Not_Narrowing;
424 }
425}
426
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000427/// DebugPrint - Print this standard conversion sequence to standard
428/// error. Useful for debugging overloading issues.
429void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000430 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000431 bool PrintedSomething = false;
432 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000433 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000434 PrintedSomething = true;
435 }
436
437 if (Second != ICK_Identity) {
438 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000439 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000440 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000441 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000442
443 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000444 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000445 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000446 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000447 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000448 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000449 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000450 PrintedSomething = true;
451 }
452
453 if (Third != ICK_Identity) {
454 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000455 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000456 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000458 PrintedSomething = true;
459 }
460
461 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000462 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000463 }
464}
465
466/// DebugPrint - Print this user-defined conversion sequence to standard
467/// error. Useful for debugging overloading issues.
468void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000469 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000470 if (Before.First || Before.Second || Before.Third) {
471 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000472 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000473 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000474 if (ConversionFunction)
475 OS << '\'' << *ConversionFunction << '\'';
476 else
477 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000478 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000479 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480 After.DebugPrint();
481 }
482}
483
484/// DebugPrint - Print this implicit conversion sequence to standard
485/// error. Useful for debugging overloading issues.
486void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000487 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488 switch (ConversionKind) {
489 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 Standard.DebugPrint();
492 break;
493 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000494 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000495 UserDefined.DebugPrint();
496 break;
497 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000498 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 break;
John McCall1d318332010-01-12 00:44:57 +0000500 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000501 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000502 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000503 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000504 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 break;
506 }
507
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000508 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000509}
510
John McCall1d318332010-01-12 00:44:57 +0000511void AmbiguousConversionSequence::construct() {
512 new (&conversions()) ConversionSet();
513}
514
515void AmbiguousConversionSequence::destruct() {
516 conversions().~ConversionSet();
517}
518
519void
520AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
521 FromTypePtr = O.FromTypePtr;
522 ToTypePtr = O.ToTypePtr;
523 new (&conversions()) ConversionSet(O.conversions());
524}
525
Douglas Gregora9333192010-05-08 17:41:32 +0000526namespace {
527 // Structure used by OverloadCandidate::DeductionFailureInfo to store
528 // template parameter and template argument information.
529 struct DFIParamWithArguments {
530 TemplateParameter Param;
531 TemplateArgument FirstArg;
532 TemplateArgument SecondArg;
533 };
534}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000535
Douglas Gregora9333192010-05-08 17:41:32 +0000536/// \brief Convert from Sema's representation of template deduction information
537/// to the form used in overload-candidate information.
538OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000539static MakeDeductionFailureInfo(ASTContext &Context,
540 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000541 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000542 OverloadCandidate::DeductionFailureInfo Result;
543 Result.Result = static_cast<unsigned>(TDK);
544 Result.Data = 0;
545 switch (TDK) {
546 case Sema::TDK_Success:
547 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000548 case Sema::TDK_TooManyArguments:
549 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000550 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000551
Douglas Gregora9333192010-05-08 17:41:32 +0000552 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000553 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000554 Result.Data = Info.Param.getOpaqueValue();
555 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000556
Douglas Gregora9333192010-05-08 17:41:32 +0000557 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000558 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000559 // FIXME: Should allocate from normal heap so that we can free this later.
560 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000561 Saved->Param = Info.Param;
562 Saved->FirstArg = Info.FirstArg;
563 Saved->SecondArg = Info.SecondArg;
564 Result.Data = Saved;
565 break;
566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000567
Douglas Gregora9333192010-05-08 17:41:32 +0000568 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000569 Result.Data = Info.take();
570 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000571
Douglas Gregora9333192010-05-08 17:41:32 +0000572 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000573 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000574 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000575 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000576
Douglas Gregora9333192010-05-08 17:41:32 +0000577 return Result;
578}
John McCall1d318332010-01-12 00:44:57 +0000579
Douglas Gregora9333192010-05-08 17:41:32 +0000580void OverloadCandidate::DeductionFailureInfo::Destroy() {
581 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
582 case Sema::TDK_Success:
583 case Sema::TDK_InstantiationDepth:
584 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000585 case Sema::TDK_TooManyArguments:
586 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000587 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000588 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000589
Douglas Gregora9333192010-05-08 17:41:32 +0000590 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000591 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000592 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000593 Data = 0;
594 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000595
596 case Sema::TDK_SubstitutionFailure:
597 // FIXME: Destroy the template arugment list?
598 Data = 0;
599 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000600
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000601 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000602 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000603 case Sema::TDK_FailedOverloadResolution:
604 break;
605 }
606}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000607
608TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000609OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
610 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
611 case Sema::TDK_Success:
612 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000613 case Sema::TDK_TooManyArguments:
614 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000615 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000616 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000617
Douglas Gregora9333192010-05-08 17:41:32 +0000618 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000619 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000620 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000621
622 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000623 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000624 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000625
Douglas Gregora9333192010-05-08 17:41:32 +0000626 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000627 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000628 case Sema::TDK_FailedOverloadResolution:
629 break;
630 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000631
Douglas Gregora9333192010-05-08 17:41:32 +0000632 return TemplateParameter();
633}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000634
Douglas Gregorec20f462010-05-08 20:07:26 +0000635TemplateArgumentList *
636OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
637 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
638 case Sema::TDK_Success:
639 case Sema::TDK_InstantiationDepth:
640 case Sema::TDK_TooManyArguments:
641 case Sema::TDK_TooFewArguments:
642 case Sema::TDK_Incomplete:
643 case Sema::TDK_InvalidExplicitArguments:
644 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000645 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000646 return 0;
647
648 case Sema::TDK_SubstitutionFailure:
649 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000650
Douglas Gregorec20f462010-05-08 20:07:26 +0000651 // Unhandled
652 case Sema::TDK_NonDeducedMismatch:
653 case Sema::TDK_FailedOverloadResolution:
654 break;
655 }
656
657 return 0;
658}
659
Douglas Gregora9333192010-05-08 17:41:32 +0000660const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
661 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
662 case Sema::TDK_Success:
663 case Sema::TDK_InstantiationDepth:
664 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000665 case Sema::TDK_TooManyArguments:
666 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000667 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000668 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000669 return 0;
670
Douglas Gregora9333192010-05-08 17:41:32 +0000671 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000672 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000673 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000674
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000675 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000676 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000677 case Sema::TDK_FailedOverloadResolution:
678 break;
679 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000680
Douglas Gregora9333192010-05-08 17:41:32 +0000681 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000682}
Douglas Gregora9333192010-05-08 17:41:32 +0000683
684const TemplateArgument *
685OverloadCandidate::DeductionFailureInfo::getSecondArg() {
686 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
687 case Sema::TDK_Success:
688 case Sema::TDK_InstantiationDepth:
689 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000690 case Sema::TDK_TooManyArguments:
691 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000692 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000693 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000694 return 0;
695
Douglas Gregora9333192010-05-08 17:41:32 +0000696 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000697 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000698 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
699
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000700 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000701 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000702 case Sema::TDK_FailedOverloadResolution:
703 break;
704 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000705
Douglas Gregora9333192010-05-08 17:41:32 +0000706 return 0;
707}
708
709void OverloadCandidateSet::clear() {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000710 for (iterator i = begin(), e = end(); i != e; ++i)
711 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
712 i->Conversions[ii].~ImplicitConversionSequence();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000713 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000714 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000715 Functions.clear();
716}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000717
John McCall5acb0c92011-10-17 18:40:02 +0000718namespace {
719 class UnbridgedCastsSet {
720 struct Entry {
721 Expr **Addr;
722 Expr *Saved;
723 };
724 SmallVector<Entry, 2> Entries;
725
726 public:
727 void save(Sema &S, Expr *&E) {
728 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
729 Entry entry = { &E, E };
730 Entries.push_back(entry);
731 E = S.stripARCUnbridgedCast(E);
732 }
733
734 void restore() {
735 for (SmallVectorImpl<Entry>::iterator
736 i = Entries.begin(), e = Entries.end(); i != e; ++i)
737 *i->Addr = i->Saved;
738 }
739 };
740}
741
742/// checkPlaceholderForOverload - Do any interesting placeholder-like
743/// preprocessing on the given expression.
744///
745/// \param unbridgedCasts a collection to which to add unbridged casts;
746/// without this, they will be immediately diagnosed as errors
747///
748/// Return true on unrecoverable error.
749static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
750 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000751 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
752 // We can't handle overloaded expressions here because overload
753 // resolution might reasonably tweak them.
754 if (placeholder->getKind() == BuiltinType::Overload) return false;
755
756 // If the context potentially accepts unbridged ARC casts, strip
757 // the unbridged cast and add it to the collection for later restoration.
758 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
759 unbridgedCasts) {
760 unbridgedCasts->save(S, E);
761 return false;
762 }
763
764 // Go ahead and check everything else.
765 ExprResult result = S.CheckPlaceholderExpr(E);
766 if (result.isInvalid())
767 return true;
768
769 E = result.take();
770 return false;
771 }
772
773 // Nothing to do.
774 return false;
775}
776
777/// checkArgPlaceholdersForOverload - Check a set of call operands for
778/// placeholders.
779static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
780 unsigned numArgs,
781 UnbridgedCastsSet &unbridged) {
782 for (unsigned i = 0; i != numArgs; ++i)
783 if (checkPlaceholderForOverload(S, args[i], &unbridged))
784 return true;
785
786 return false;
787}
788
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000790// overload of the declarations in Old. This routine returns false if
791// New and Old cannot be overloaded, e.g., if New has the same
792// signature as some function in Old (C++ 1.3.10) or if the Old
793// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000794// it does return false, MatchedDecl will point to the decl that New
795// cannot be overloaded with. This decl may be a UsingShadowDecl on
796// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797//
798// Example: Given the following input:
799//
800// void f(int, float); // #1
801// void f(int, int); // #2
802// int f(int, int); // #3
803//
804// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000805// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000806//
John McCall51fa86f2009-12-02 08:47:38 +0000807// When we process #2, Old contains only the FunctionDecl for #1. By
808// comparing the parameter types, we see that #1 and #2 are overloaded
809// (since they have different signatures), so this routine returns
810// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000811//
John McCall51fa86f2009-12-02 08:47:38 +0000812// When we process #3, Old is an overload set containing #1 and #2. We
813// compare the signatures of #3 to #1 (they're overloaded, so we do
814// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
815// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816// signature), IsOverload returns false and MatchedDecl will be set to
817// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000818//
819// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
820// into a class by a using declaration. The rules for whether to hide
821// shadow declarations ignore some properties which otherwise figure
822// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000823Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000824Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
825 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000826 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000827 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000828 NamedDecl *OldD = *I;
829
830 bool OldIsUsingDecl = false;
831 if (isa<UsingShadowDecl>(OldD)) {
832 OldIsUsingDecl = true;
833
834 // We can always introduce two using declarations into the same
835 // context, even if they have identical signatures.
836 if (NewIsUsingDecl) continue;
837
838 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
839 }
840
841 // If either declaration was introduced by a using declaration,
842 // we'll need to use slightly different rules for matching.
843 // Essentially, these rules are the normal rules, except that
844 // function templates hide function templates with different
845 // return types or template parameter lists.
846 bool UseMemberUsingDeclRules =
847 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
848
John McCall51fa86f2009-12-02 08:47:38 +0000849 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000850 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
851 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
852 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
853 continue;
854 }
855
John McCall871b2e72009-12-09 03:35:25 +0000856 Match = *I;
857 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000858 }
John McCall51fa86f2009-12-02 08:47:38 +0000859 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000860 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
861 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
862 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
863 continue;
864 }
865
John McCall871b2e72009-12-09 03:35:25 +0000866 Match = *I;
867 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000868 }
John McCalld7945c62010-11-10 03:01:53 +0000869 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000870 // We can overload with these, which can show up when doing
871 // redeclaration checks for UsingDecls.
872 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000873 } else if (isa<TagDecl>(OldD)) {
874 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000875 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
876 // Optimistically assume that an unresolved using decl will
877 // overload; if it doesn't, we'll have to diagnose during
878 // template instantiation.
879 } else {
John McCall68263142009-11-18 22:49:29 +0000880 // (C++ 13p1):
881 // Only function declarations can be overloaded; object and type
882 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000883 Match = *I;
884 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000885 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000886 }
John McCall68263142009-11-18 22:49:29 +0000887
John McCall871b2e72009-12-09 03:35:25 +0000888 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000889}
890
John McCallad00b772010-06-16 08:42:20 +0000891bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
892 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000893 // If both of the functions are extern "C", then they are not
894 // overloads.
895 if (Old->isExternC() && New->isExternC())
896 return false;
897
John McCall68263142009-11-18 22:49:29 +0000898 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
899 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
900
901 // C++ [temp.fct]p2:
902 // A function template can be overloaded with other function templates
903 // and with normal (non-template) functions.
904 if ((OldTemplate == 0) != (NewTemplate == 0))
905 return true;
906
907 // Is the function New an overload of the function Old?
908 QualType OldQType = Context.getCanonicalType(Old->getType());
909 QualType NewQType = Context.getCanonicalType(New->getType());
910
911 // Compare the signatures (C++ 1.3.10) of the two functions to
912 // determine whether they are overloads. If we find any mismatch
913 // in the signature, they are overloads.
914
915 // If either of these functions is a K&R-style function (no
916 // prototype), then we consider them to have matching signatures.
917 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
918 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
919 return false;
920
John McCallf4c73712011-01-19 06:33:43 +0000921 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
922 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000923
924 // The signature of a function includes the types of its
925 // parameters (C++ 1.3.10), which includes the presence or absence
926 // of the ellipsis; see C++ DR 357).
927 if (OldQType != NewQType &&
928 (OldType->getNumArgs() != NewType->getNumArgs() ||
929 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000930 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000931 return true;
932
933 // C++ [temp.over.link]p4:
934 // The signature of a function template consists of its function
935 // signature, its return type and its template parameter list. The names
936 // of the template parameters are significant only for establishing the
937 // relationship between the template parameters and the rest of the
938 // signature.
939 //
940 // We check the return type and template parameter lists for function
941 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000942 //
943 // However, we don't consider either of these when deciding whether
944 // a member introduced by a shadow declaration is hidden.
945 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000946 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
947 OldTemplate->getTemplateParameters(),
948 false, TPL_TemplateMatch) ||
949 OldType->getResultType() != NewType->getResultType()))
950 return true;
951
952 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000953 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000954 //
955 // As part of this, also check whether one of the member functions
956 // is static, in which case they are not overloads (C++
957 // 13.1p2). While not part of the definition of the signature,
958 // this check is important to determine whether these functions
959 // can be overloaded.
960 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
961 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
962 if (OldMethod && NewMethod &&
963 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000964 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000965 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
966 if (!UseUsingDeclRules &&
967 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
968 (OldMethod->getRefQualifier() == RQ_None ||
969 NewMethod->getRefQualifier() == RQ_None)) {
970 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000971 // - Member function declarations with the same name and the same
972 // parameter-type-list as well as member function template
973 // declarations with the same name, the same parameter-type-list, and
974 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000975 // them, but not all, have a ref-qualifier (8.3.5).
976 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
977 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
978 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
979 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000980
John McCall68263142009-11-18 22:49:29 +0000981 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000982 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000983
John McCall68263142009-11-18 22:49:29 +0000984 // The signatures match; this is not an overload.
985 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000986}
987
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000988/// \brief Checks availability of the function depending on the current
989/// function context. Inside an unavailable function, unavailability is ignored.
990///
991/// \returns true if \arg FD is unavailable and current context is inside
992/// an available function, false otherwise.
993bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
994 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
995}
996
Sebastian Redlcf15cef2011-12-22 18:58:38 +0000997/// \brief Tries a user-defined conversion from From to ToType.
998///
999/// Produces an implicit conversion sequence for when a standard conversion
1000/// is not an option. See TryImplicitConversion for more information.
1001static ImplicitConversionSequence
1002TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1003 bool SuppressUserConversions,
1004 bool AllowExplicit,
1005 bool InOverloadResolution,
1006 bool CStyle,
1007 bool AllowObjCWritebackConversion) {
1008 ImplicitConversionSequence ICS;
1009
1010 if (SuppressUserConversions) {
1011 // We're not in the case above, so there is no conversion that
1012 // we can perform.
1013 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1014 return ICS;
1015 }
1016
1017 // Attempt user-defined conversion.
1018 OverloadCandidateSet Conversions(From->getExprLoc());
1019 OverloadingResult UserDefResult
1020 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1021 AllowExplicit);
1022
1023 if (UserDefResult == OR_Success) {
1024 ICS.setUserDefined();
1025 // C++ [over.ics.user]p4:
1026 // A conversion of an expression of class type to the same class
1027 // type is given Exact Match rank, and a conversion of an
1028 // expression of class type to a base class of that type is
1029 // given Conversion rank, in spite of the fact that a copy
1030 // constructor (i.e., a user-defined conversion function) is
1031 // called for those cases.
1032 if (CXXConstructorDecl *Constructor
1033 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1034 QualType FromCanon
1035 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1036 QualType ToCanon
1037 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1038 if (Constructor->isCopyConstructor() &&
1039 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1040 // Turn this into a "standard" conversion sequence, so that it
1041 // gets ranked with standard conversion sequences.
1042 ICS.setStandard();
1043 ICS.Standard.setAsIdentityConversion();
1044 ICS.Standard.setFromType(From->getType());
1045 ICS.Standard.setAllToTypes(ToType);
1046 ICS.Standard.CopyConstructor = Constructor;
1047 if (ToCanon != FromCanon)
1048 ICS.Standard.Second = ICK_Derived_To_Base;
1049 }
1050 }
1051
1052 // C++ [over.best.ics]p4:
1053 // However, when considering the argument of a user-defined
1054 // conversion function that is a candidate by 13.3.1.3 when
1055 // invoked for the copying of the temporary in the second step
1056 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1057 // 13.3.1.6 in all cases, only standard conversion sequences and
1058 // ellipsis conversion sequences are allowed.
1059 if (SuppressUserConversions && ICS.isUserDefined()) {
1060 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1061 }
1062 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1063 ICS.setAmbiguous();
1064 ICS.Ambiguous.setFromType(From->getType());
1065 ICS.Ambiguous.setToType(ToType);
1066 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1067 Cand != Conversions.end(); ++Cand)
1068 if (Cand->Viable)
1069 ICS.Ambiguous.addConversion(Cand->Function);
1070 } else {
1071 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1072 }
1073
1074 return ICS;
1075}
1076
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001077/// TryImplicitConversion - Attempt to perform an implicit conversion
1078/// from the given expression (Expr) to the given type (ToType). This
1079/// function returns an implicit conversion sequence that can be used
1080/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001081///
1082/// void f(float f);
1083/// void g(int i) { f(i); }
1084///
1085/// this routine would produce an implicit conversion sequence to
1086/// describe the initialization of f from i, which will be a standard
1087/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1088/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1089//
1090/// Note that this routine only determines how the conversion can be
1091/// performed; it does not actually perform the conversion. As such,
1092/// it will not produce any diagnostics if no conversion is available,
1093/// but will instead return an implicit conversion sequence of kind
1094/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001095///
1096/// If @p SuppressUserConversions, then user-defined conversions are
1097/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001098/// If @p AllowExplicit, then explicit user-defined conversions are
1099/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001100///
1101/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1102/// writeback conversion, which allows __autoreleasing id* parameters to
1103/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001104static ImplicitConversionSequence
1105TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1106 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001107 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001108 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001109 bool CStyle,
1110 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001111 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001112 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001113 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001114 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001115 return ICS;
1116 }
1117
David Blaikie4e4d0842012-03-11 07:00:24 +00001118 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001119 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001120 return ICS;
1121 }
1122
Douglas Gregor604eb652010-08-11 02:15:33 +00001123 // C++ [over.ics.user]p4:
1124 // A conversion of an expression of class type to the same class
1125 // type is given Exact Match rank, and a conversion of an
1126 // expression of class type to a base class of that type is
1127 // given Conversion rank, in spite of the fact that a copy/move
1128 // constructor (i.e., a user-defined conversion function) is
1129 // called for those cases.
1130 QualType FromType = From->getType();
1131 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001132 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1133 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001134 ICS.setStandard();
1135 ICS.Standard.setAsIdentityConversion();
1136 ICS.Standard.setFromType(FromType);
1137 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001138
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001139 // We don't actually check at this point whether there is a valid
1140 // copy/move constructor, since overloading just assumes that it
1141 // exists. When we actually perform initialization, we'll find the
1142 // appropriate constructor to copy the returned object, if needed.
1143 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001144
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001145 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001146 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001147 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001148
Douglas Gregor604eb652010-08-11 02:15:33 +00001149 return ICS;
1150 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001151
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001152 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1153 AllowExplicit, InOverloadResolution, CStyle,
1154 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001155}
1156
John McCallf85e1932011-06-15 23:02:42 +00001157ImplicitConversionSequence
1158Sema::TryImplicitConversion(Expr *From, QualType ToType,
1159 bool SuppressUserConversions,
1160 bool AllowExplicit,
1161 bool InOverloadResolution,
1162 bool CStyle,
1163 bool AllowObjCWritebackConversion) {
1164 return clang::TryImplicitConversion(*this, From, ToType,
1165 SuppressUserConversions, AllowExplicit,
1166 InOverloadResolution, CStyle,
1167 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001168}
1169
Douglas Gregor575c63a2010-04-16 22:27:05 +00001170/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001171/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001172/// converted expression. Flavor is the kind of conversion we're
1173/// performing, used in the error message. If @p AllowExplicit,
1174/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001175ExprResult
1176Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001177 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001178 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001179 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001180}
1181
John Wiegley429bb272011-04-08 18:41:53 +00001182ExprResult
1183Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001184 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001185 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001186 if (checkPlaceholderForOverload(*this, From))
1187 return ExprError();
1188
John McCallf85e1932011-06-15 23:02:42 +00001189 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1190 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001191 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001192 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001193
John McCall120d63c2010-08-24 20:38:10 +00001194 ICS = clang::TryImplicitConversion(*this, From, ToType,
1195 /*SuppressUserConversions=*/false,
1196 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001197 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001198 /*CStyle=*/false,
1199 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001200 return PerformImplicitConversion(From, ToType, ICS, Action);
1201}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001202
1203/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001204/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001205bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1206 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001207 if (Context.hasSameUnqualifiedType(FromType, ToType))
1208 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001209
John McCall00ccbef2010-12-21 00:44:39 +00001210 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1211 // where F adds one of the following at most once:
1212 // - a pointer
1213 // - a member pointer
1214 // - a block pointer
1215 CanQualType CanTo = Context.getCanonicalType(ToType);
1216 CanQualType CanFrom = Context.getCanonicalType(FromType);
1217 Type::TypeClass TyClass = CanTo->getTypeClass();
1218 if (TyClass != CanFrom->getTypeClass()) return false;
1219 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1220 if (TyClass == Type::Pointer) {
1221 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1222 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1223 } else if (TyClass == Type::BlockPointer) {
1224 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1225 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1226 } else if (TyClass == Type::MemberPointer) {
1227 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1228 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1229 } else {
1230 return false;
1231 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001232
John McCall00ccbef2010-12-21 00:44:39 +00001233 TyClass = CanTo->getTypeClass();
1234 if (TyClass != CanFrom->getTypeClass()) return false;
1235 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1236 return false;
1237 }
1238
1239 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1240 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1241 if (!EInfo.getNoReturn()) return false;
1242
1243 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1244 assert(QualType(FromFn, 0).isCanonical());
1245 if (QualType(FromFn, 0) != CanTo) return false;
1246
1247 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001248 return true;
1249}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001250
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001251/// \brief Determine whether the conversion from FromType to ToType is a valid
1252/// vector conversion.
1253///
1254/// \param ICK Will be set to the vector conversion kind, if this is a vector
1255/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001256static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1257 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001258 // We need at least one of these types to be a vector type to have a vector
1259 // conversion.
1260 if (!ToType->isVectorType() && !FromType->isVectorType())
1261 return false;
1262
1263 // Identical types require no conversions.
1264 if (Context.hasSameUnqualifiedType(FromType, ToType))
1265 return false;
1266
1267 // There are no conversions between extended vector types, only identity.
1268 if (ToType->isExtVectorType()) {
1269 // There are no conversions between extended vector types other than the
1270 // identity conversion.
1271 if (FromType->isExtVectorType())
1272 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001273
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001274 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001275 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001276 ICK = ICK_Vector_Splat;
1277 return true;
1278 }
1279 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001280
1281 // We can perform the conversion between vector types in the following cases:
1282 // 1)vector types are equivalent AltiVec and GCC vector types
1283 // 2)lax vector conversions are permitted and the vector types are of the
1284 // same size
1285 if (ToType->isVectorType() && FromType->isVectorType()) {
1286 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001287 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001288 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001289 ICK = ICK_Vector_Conversion;
1290 return true;
1291 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001292 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001293
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001294 return false;
1295}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001296
Douglas Gregor7d000652012-04-12 20:48:09 +00001297static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1298 bool InOverloadResolution,
1299 StandardConversionSequence &SCS,
1300 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001301
Douglas Gregor60d62c22008-10-31 16:23:19 +00001302/// IsStandardConversion - Determines whether there is a standard
1303/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1304/// expression From to the type ToType. Standard conversion sequences
1305/// only consider non-class types; for conversions that involve class
1306/// types, use TryImplicitConversion. If a conversion exists, SCS will
1307/// contain the standard conversion sequence required to perform this
1308/// conversion and this routine will return true. Otherwise, this
1309/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001310static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1311 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001312 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001313 bool CStyle,
1314 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001315 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001316
Douglas Gregor60d62c22008-10-31 16:23:19 +00001317 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001318 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001319 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001320 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001321 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001322 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001323
Douglas Gregorf9201e02009-02-11 23:02:49 +00001324 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001325 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001326 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001327 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001328 return false;
1329
Mike Stump1eb44332009-09-09 15:08:12 +00001330 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001331 }
1332
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001333 // The first conversion can be an lvalue-to-rvalue conversion,
1334 // array-to-pointer conversion, or function-to-pointer conversion
1335 // (C++ 4p1).
1336
John McCall120d63c2010-08-24 20:38:10 +00001337 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001338 DeclAccessPair AccessPair;
1339 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001340 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001341 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001342 // We were able to resolve the address of the overloaded function,
1343 // so we can convert to the type of that function.
1344 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001345
1346 // we can sometimes resolve &foo<int> regardless of ToType, so check
1347 // if the type matches (identity) or we are converting to bool
1348 if (!S.Context.hasSameUnqualifiedType(
1349 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1350 QualType resultTy;
1351 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001352 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001353 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1354 // otherwise, only a boolean conversion is standard
1355 if (!ToType->isBooleanType())
1356 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001357 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001358
Chandler Carruth90434232011-03-29 08:08:18 +00001359 // Check if the "from" expression is taking the address of an overloaded
1360 // function and recompute the FromType accordingly. Take advantage of the
1361 // fact that non-static member functions *must* have such an address-of
1362 // expression.
1363 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1364 if (Method && !Method->isStatic()) {
1365 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1366 "Non-unary operator on non-static member address");
1367 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1368 == UO_AddrOf &&
1369 "Non-address-of operator on non-static member address");
1370 const Type *ClassType
1371 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1372 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001373 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1374 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1375 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001376 "Non-address-of operator for overloaded function expression");
1377 FromType = S.Context.getPointerType(FromType);
1378 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001379
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001380 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001381 assert(S.Context.hasSameType(
1382 FromType,
1383 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001384 } else {
1385 return false;
1386 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001387 }
John McCall21480112011-08-30 00:57:29 +00001388 // Lvalue-to-rvalue conversion (C++11 4.1):
1389 // A glvalue (3.10) of a non-function, non-array type T can
1390 // be converted to a prvalue.
1391 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001392 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001393 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001394 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001395 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001396
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001397 // C11 6.3.2.1p2:
1398 // ... if the lvalue has atomic type, the value has the non-atomic version
1399 // of the type of the lvalue ...
1400 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1401 FromType = Atomic->getValueType();
1402
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001403 // If T is a non-class type, the type of the rvalue is the
1404 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001405 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1406 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001407 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001408 } else if (FromType->isArrayType()) {
1409 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001410 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001411
1412 // An lvalue or rvalue of type "array of N T" or "array of unknown
1413 // bound of T" can be converted to an rvalue of type "pointer to
1414 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001415 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001416
John McCall120d63c2010-08-24 20:38:10 +00001417 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001418 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001419 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001420
1421 // For the purpose of ranking in overload resolution
1422 // (13.3.3.1.1), this conversion is considered an
1423 // array-to-pointer conversion followed by a qualification
1424 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001425 SCS.Second = ICK_Identity;
1426 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001427 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001428 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001429 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001431 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001432 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001433 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001434
1435 // An lvalue of function type T can be converted to an rvalue of
1436 // type "pointer to T." The result is a pointer to the
1437 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001438 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001439 } else {
1440 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001441 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001442 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001443 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001444
1445 // The second conversion can be an integral promotion, floating
1446 // point promotion, integral conversion, floating point conversion,
1447 // floating-integral conversion, pointer conversion,
1448 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001449 // For overloading in C, this can also be a "compatible-type"
1450 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001451 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001452 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001453 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001454 // The unqualified versions of the types are the same: there's no
1455 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001456 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001457 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001458 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001459 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001460 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001461 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001462 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001463 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001464 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001465 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001466 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001467 SCS.Second = ICK_Complex_Promotion;
1468 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001469 } else if (ToType->isBooleanType() &&
1470 (FromType->isArithmeticType() ||
1471 FromType->isAnyPointerType() ||
1472 FromType->isBlockPointerType() ||
1473 FromType->isMemberPointerType() ||
1474 FromType->isNullPtrType())) {
1475 // Boolean conversions (C++ 4.12).
1476 SCS.Second = ICK_Boolean_Conversion;
1477 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001478 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001479 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001480 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001481 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001482 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001483 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001484 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001485 SCS.Second = ICK_Complex_Conversion;
1486 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001487 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1488 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001489 // Complex-real conversions (C99 6.3.1.7)
1490 SCS.Second = ICK_Complex_Real;
1491 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001492 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001493 // Floating point conversions (C++ 4.8).
1494 SCS.Second = ICK_Floating_Conversion;
1495 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001496 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001497 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001498 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001499 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001500 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001501 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001502 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001503 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001504 SCS.Second = ICK_Block_Pointer_Conversion;
1505 } else if (AllowObjCWritebackConversion &&
1506 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1507 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001508 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1509 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001510 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001511 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001512 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001513 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001514 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001515 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001516 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001517 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001518 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001519 SCS.Second = SecondICK;
1520 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001521 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001522 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001523 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001524 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001525 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001526 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001527 // Treat a conversion that strips "noreturn" as an identity conversion.
1528 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001529 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1530 InOverloadResolution,
1531 SCS, CStyle)) {
1532 SCS.Second = ICK_TransparentUnionConversion;
1533 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001534 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1535 CStyle)) {
1536 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001537 // appropriately.
1538 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001539 } else {
1540 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001541 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001542 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001543 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001544
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001545 QualType CanonFrom;
1546 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001547 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001548 bool ObjCLifetimeConversion;
1549 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1550 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001551 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001552 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001553 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001554 CanonFrom = S.Context.getCanonicalType(FromType);
1555 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001556 } else {
1557 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001558 SCS.Third = ICK_Identity;
1559
Mike Stump1eb44332009-09-09 15:08:12 +00001560 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001561 // [...] Any difference in top-level cv-qualification is
1562 // subsumed by the initialization itself and does not constitute
1563 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001564 CanonFrom = S.Context.getCanonicalType(FromType);
1565 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001566 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001567 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001568 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001569 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1570 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001571 FromType = ToType;
1572 CanonFrom = CanonTo;
1573 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001574 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001575 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001576
1577 // If we have not converted the argument type to the parameter type,
1578 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001579 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001580 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001581
Douglas Gregor60d62c22008-10-31 16:23:19 +00001582 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001583}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001584
1585static bool
1586IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1587 QualType &ToType,
1588 bool InOverloadResolution,
1589 StandardConversionSequence &SCS,
1590 bool CStyle) {
1591
1592 const RecordType *UT = ToType->getAsUnionType();
1593 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1594 return false;
1595 // The field to initialize within the transparent union.
1596 RecordDecl *UD = UT->getDecl();
1597 // It's compatible if the expression matches any of the fields.
1598 for (RecordDecl::field_iterator it = UD->field_begin(),
1599 itend = UD->field_end();
1600 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001601 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1602 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001603 ToType = it->getType();
1604 return true;
1605 }
1606 }
1607 return false;
1608}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001609
1610/// IsIntegralPromotion - Determines whether the conversion from the
1611/// expression From (whose potentially-adjusted type is FromType) to
1612/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1613/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001614bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001615 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001616 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001617 if (!To) {
1618 return false;
1619 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001620
1621 // An rvalue of type char, signed char, unsigned char, short int, or
1622 // unsigned short int can be converted to an rvalue of type int if
1623 // int can represent all the values of the source type; otherwise,
1624 // the source rvalue can be converted to an rvalue of type unsigned
1625 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001626 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1627 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001628 if (// We can promote any signed, promotable integer type to an int
1629 (FromType->isSignedIntegerType() ||
1630 // We can promote any unsigned integer type whose size is
1631 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001632 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001633 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001634 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001635 }
1636
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001637 return To->getKind() == BuiltinType::UInt;
1638 }
1639
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001640 // C++0x [conv.prom]p3:
1641 // A prvalue of an unscoped enumeration type whose underlying type is not
1642 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1643 // following types that can represent all the values of the enumeration
1644 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1645 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001646 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001647 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001648 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001649 // with lowest integer conversion rank (4.13) greater than the rank of long
1650 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001651 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001652 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1653 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1654 // provided for a scoped enumeration.
1655 if (FromEnumType->getDecl()->isScoped())
1656 return false;
1657
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001658 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001659 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001660 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001661 return Context.hasSameUnqualifiedType(ToType,
1662 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001663 }
John McCall842aef82009-12-09 09:09:27 +00001664
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001665 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001666 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1667 // to an rvalue a prvalue of the first of the following types that can
1668 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001669 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001670 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001671 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001672 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001673 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001674 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001675 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676 // Determine whether the type we're converting from is signed or
1677 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001678 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001679 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001680
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001681 // The types we'll try to promote to, in the appropriate
1682 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001683 QualType PromoteTypes[6] = {
1684 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001685 Context.LongTy, Context.UnsignedLongTy ,
1686 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001687 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001688 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001689 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1690 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001691 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001692 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1693 // We found the type that we can promote to. If this is the
1694 // type we wanted, we have a promotion. Otherwise, no
1695 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001696 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001697 }
1698 }
1699 }
1700
1701 // An rvalue for an integral bit-field (9.6) can be converted to an
1702 // rvalue of type int if int can represent all the values of the
1703 // bit-field; otherwise, it can be converted to unsigned int if
1704 // unsigned int can represent all the values of the bit-field. If
1705 // the bit-field is larger yet, no integral promotion applies to
1706 // it. If the bit-field has an enumerated type, it is treated as any
1707 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001708 // FIXME: We should delay checking of bit-fields until we actually perform the
1709 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001710 using llvm::APSInt;
1711 if (From)
1712 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001713 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001714 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001715 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1716 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1717 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Douglas Gregor86f19402008-12-20 23:49:58 +00001719 // Are we promoting to an int from a bitfield that fits in an int?
1720 if (BitWidth < ToSize ||
1721 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1722 return To->getKind() == BuiltinType::Int;
1723 }
Mike Stump1eb44332009-09-09 15:08:12 +00001724
Douglas Gregor86f19402008-12-20 23:49:58 +00001725 // Are we promoting to an unsigned int from an unsigned bitfield
1726 // that fits into an unsigned int?
1727 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1728 return To->getKind() == BuiltinType::UInt;
1729 }
Mike Stump1eb44332009-09-09 15:08:12 +00001730
Douglas Gregor86f19402008-12-20 23:49:58 +00001731 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001732 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001733 }
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001735 // An rvalue of type bool can be converted to an rvalue of type int,
1736 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001737 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001738 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001739 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001740
1741 return false;
1742}
1743
1744/// IsFloatingPointPromotion - Determines whether the conversion from
1745/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1746/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001747bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001748 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1749 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001750 /// An rvalue of type float can be converted to an rvalue of type
1751 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001752 if (FromBuiltin->getKind() == BuiltinType::Float &&
1753 ToBuiltin->getKind() == BuiltinType::Double)
1754 return true;
1755
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001756 // C99 6.3.1.5p1:
1757 // When a float is promoted to double or long double, or a
1758 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001759 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001760 (FromBuiltin->getKind() == BuiltinType::Float ||
1761 FromBuiltin->getKind() == BuiltinType::Double) &&
1762 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1763 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001764
1765 // Half can be promoted to float.
1766 if (FromBuiltin->getKind() == BuiltinType::Half &&
1767 ToBuiltin->getKind() == BuiltinType::Float)
1768 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001769 }
1770
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001771 return false;
1772}
1773
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001774/// \brief Determine if a conversion is a complex promotion.
1775///
1776/// A complex promotion is defined as a complex -> complex conversion
1777/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001778/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001779bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001780 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001781 if (!FromComplex)
1782 return false;
1783
John McCall183700f2009-09-21 23:43:11 +00001784 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001785 if (!ToComplex)
1786 return false;
1787
1788 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001789 ToComplex->getElementType()) ||
1790 IsIntegralPromotion(0, FromComplex->getElementType(),
1791 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001792}
1793
Douglas Gregorcb7de522008-11-26 23:31:11 +00001794/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1795/// the pointer type FromPtr to a pointer to type ToPointee, with the
1796/// same type qualifiers as FromPtr has on its pointee type. ToType,
1797/// if non-empty, will be a pointer to ToType that may or may not have
1798/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001799///
Mike Stump1eb44332009-09-09 15:08:12 +00001800static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001801BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001802 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001803 ASTContext &Context,
1804 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001805 assert((FromPtr->getTypeClass() == Type::Pointer ||
1806 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1807 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001808
John McCallf85e1932011-06-15 23:02:42 +00001809 /// Conversions to 'id' subsume cv-qualifier conversions.
1810 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001811 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001812
1813 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001814 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001815 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001816 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001817
John McCallf85e1932011-06-15 23:02:42 +00001818 if (StripObjCLifetime)
1819 Quals.removeObjCLifetime();
1820
Mike Stump1eb44332009-09-09 15:08:12 +00001821 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001822 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001823 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001824 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001825 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001826
1827 // Build a pointer to ToPointee. It has the right qualifiers
1828 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001829 if (isa<ObjCObjectPointerType>(ToType))
1830 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001831 return Context.getPointerType(ToPointee);
1832 }
1833
1834 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001835 QualType QualifiedCanonToPointee
1836 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001837
Douglas Gregorda80f742010-12-01 21:43:58 +00001838 if (isa<ObjCObjectPointerType>(ToType))
1839 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1840 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001841}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001842
Mike Stump1eb44332009-09-09 15:08:12 +00001843static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001844 bool InOverloadResolution,
1845 ASTContext &Context) {
1846 // Handle value-dependent integral null pointer constants correctly.
1847 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1848 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001849 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001850 return !InOverloadResolution;
1851
Douglas Gregorce940492009-09-25 04:25:58 +00001852 return Expr->isNullPointerConstant(Context,
1853 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1854 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001855}
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001857/// IsPointerConversion - Determines whether the conversion of the
1858/// expression From, which has the (possibly adjusted) type FromType,
1859/// can be converted to the type ToType via a pointer conversion (C++
1860/// 4.10). If so, returns true and places the converted type (that
1861/// might differ from ToType in its cv-qualifiers at some level) into
1862/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001863///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001864/// This routine also supports conversions to and from block pointers
1865/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1866/// pointers to interfaces. FIXME: Once we've determined the
1867/// appropriate overloading rules for Objective-C, we may want to
1868/// split the Objective-C checks into a different routine; however,
1869/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001870/// conversions, so for now they live here. IncompatibleObjC will be
1871/// set if the conversion is an allowed Objective-C conversion that
1872/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001873bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001874 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001875 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001876 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001877 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001878 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1879 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001880 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001881
Mike Stump1eb44332009-09-09 15:08:12 +00001882 // Conversion from a null pointer constant to any Objective-C pointer type.
1883 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001884 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001885 ConvertedType = ToType;
1886 return true;
1887 }
1888
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001889 // Blocks: Block pointers can be converted to void*.
1890 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001891 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001892 ConvertedType = ToType;
1893 return true;
1894 }
1895 // Blocks: A null pointer constant can be converted to a block
1896 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001897 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001898 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001899 ConvertedType = ToType;
1900 return true;
1901 }
1902
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001903 // If the left-hand-side is nullptr_t, the right side can be a null
1904 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001905 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001906 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001907 ConvertedType = ToType;
1908 return true;
1909 }
1910
Ted Kremenek6217b802009-07-29 21:53:49 +00001911 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001912 if (!ToTypePtr)
1913 return false;
1914
1915 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001916 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001917 ConvertedType = ToType;
1918 return true;
1919 }
Sebastian Redl07779722008-10-31 14:43:28 +00001920
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001921 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001922 // , including objective-c pointers.
1923 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001924 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001925 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001926 ConvertedType = BuildSimilarlyQualifiedPointerType(
1927 FromType->getAs<ObjCObjectPointerType>(),
1928 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001929 ToType, Context);
1930 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001931 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001932 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001933 if (!FromTypePtr)
1934 return false;
1935
1936 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001937
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001938 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001939 // pointer conversion, so don't do all of the work below.
1940 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1941 return false;
1942
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001943 // An rvalue of type "pointer to cv T," where T is an object type,
1944 // can be converted to an rvalue of type "pointer to cv void" (C++
1945 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001946 if (FromPointeeType->isIncompleteOrObjectType() &&
1947 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001948 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001949 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001950 ToType, Context,
1951 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001952 return true;
1953 }
1954
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001955 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001956 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001957 ToPointeeType->isVoidType()) {
1958 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1959 ToPointeeType,
1960 ToType, Context);
1961 return true;
1962 }
1963
Douglas Gregorf9201e02009-02-11 23:02:49 +00001964 // When we're overloading in C, we allow a special kind of pointer
1965 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00001966 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001967 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001968 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001969 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001970 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001971 return true;
1972 }
1973
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001974 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001975 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001976 // An rvalue of type "pointer to cv D," where D is a class type,
1977 // can be converted to an rvalue of type "pointer to cv B," where
1978 // B is a base class (clause 10) of D. If B is an inaccessible
1979 // (clause 11) or ambiguous (10.2) base class of D, a program that
1980 // necessitates this conversion is ill-formed. The result of the
1981 // conversion is a pointer to the base class sub-object of the
1982 // derived class object. The null pointer value is converted to
1983 // the null pointer value of the destination type.
1984 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001985 // Note that we do not check for ambiguity or inaccessibility
1986 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001987 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001988 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001989 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001990 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001991 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001992 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001993 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001994 ToType, Context);
1995 return true;
1996 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001997
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001998 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1999 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2000 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2001 ToPointeeType,
2002 ToType, Context);
2003 return true;
2004 }
2005
Douglas Gregorc7887512008-12-19 19:13:09 +00002006 return false;
2007}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002008
2009/// \brief Adopt the given qualifiers for the given type.
2010static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2011 Qualifiers TQs = T.getQualifiers();
2012
2013 // Check whether qualifiers already match.
2014 if (TQs == Qs)
2015 return T;
2016
2017 if (Qs.compatiblyIncludes(TQs))
2018 return Context.getQualifiedType(T, Qs);
2019
2020 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2021}
Douglas Gregorc7887512008-12-19 19:13:09 +00002022
2023/// isObjCPointerConversion - Determines whether this is an
2024/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2025/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002026bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002027 QualType& ConvertedType,
2028 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002029 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002030 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002031
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002032 // The set of qualifiers on the type we're converting from.
2033 Qualifiers FromQualifiers = FromType.getQualifiers();
2034
Steve Naroff14108da2009-07-10 23:34:53 +00002035 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002036 const ObjCObjectPointerType* ToObjCPtr =
2037 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002038 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002039 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002040
Steve Naroff14108da2009-07-10 23:34:53 +00002041 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002042 // If the pointee types are the same (ignoring qualifications),
2043 // then this is not a pointer conversion.
2044 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2045 FromObjCPtr->getPointeeType()))
2046 return false;
2047
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002048 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002049 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002050 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002051 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002052 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002053 return true;
2054 }
2055 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002056 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002057 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002058 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002059 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002060 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002061 return true;
2062 }
2063 // Objective C++: We're able to convert from a pointer to an
2064 // interface to a pointer to a different interface.
2065 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002066 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2067 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002068 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002069 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2070 FromObjCPtr->getPointeeType()))
2071 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002072 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002073 ToObjCPtr->getPointeeType(),
2074 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002075 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002076 return true;
2077 }
2078
2079 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2080 // Okay: this is some kind of implicit downcast of Objective-C
2081 // interfaces, which is permitted. However, we're going to
2082 // complain about it.
2083 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002084 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002085 ToObjCPtr->getPointeeType(),
2086 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002087 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002088 return true;
2089 }
Mike Stump1eb44332009-09-09 15:08:12 +00002090 }
Steve Naroff14108da2009-07-10 23:34:53 +00002091 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002092 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002093 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002094 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002096 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002097 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002098 // to a block pointer type.
2099 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002100 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002101 return true;
2102 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002103 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002104 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002105 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002106 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002107 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002108 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002109 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002110 return true;
2111 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002112 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002113 return false;
2114
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002115 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002116 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002117 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002118 else if (const BlockPointerType *FromBlockPtr =
2119 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002120 FromPointeeType = FromBlockPtr->getPointeeType();
2121 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002122 return false;
2123
Douglas Gregorc7887512008-12-19 19:13:09 +00002124 // If we have pointers to pointers, recursively check whether this
2125 // is an Objective-C conversion.
2126 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2127 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2128 IncompatibleObjC)) {
2129 // We always complain about this conversion.
2130 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002131 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002132 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002133 return true;
2134 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002135 // Allow conversion of pointee being objective-c pointer to another one;
2136 // as in I* to id.
2137 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2138 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2139 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2140 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002141
Douglas Gregorda80f742010-12-01 21:43:58 +00002142 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002143 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002144 return true;
2145 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002146
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002147 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002148 // differences in the argument and result types are in Objective-C
2149 // pointer conversions. If so, we permit the conversion (but
2150 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002151 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002152 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002153 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002154 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002155 if (FromFunctionType && ToFunctionType) {
2156 // If the function types are exactly the same, this isn't an
2157 // Objective-C pointer conversion.
2158 if (Context.getCanonicalType(FromPointeeType)
2159 == Context.getCanonicalType(ToPointeeType))
2160 return false;
2161
2162 // Perform the quick checks that will tell us whether these
2163 // function types are obviously different.
2164 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2165 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2166 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2167 return false;
2168
2169 bool HasObjCConversion = false;
2170 if (Context.getCanonicalType(FromFunctionType->getResultType())
2171 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2172 // Okay, the types match exactly. Nothing to do.
2173 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2174 ToFunctionType->getResultType(),
2175 ConvertedType, IncompatibleObjC)) {
2176 // Okay, we have an Objective-C pointer conversion.
2177 HasObjCConversion = true;
2178 } else {
2179 // Function types are too different. Abort.
2180 return false;
2181 }
Mike Stump1eb44332009-09-09 15:08:12 +00002182
Douglas Gregorc7887512008-12-19 19:13:09 +00002183 // Check argument types.
2184 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2185 ArgIdx != NumArgs; ++ArgIdx) {
2186 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2187 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2188 if (Context.getCanonicalType(FromArgType)
2189 == Context.getCanonicalType(ToArgType)) {
2190 // Okay, the types match exactly. Nothing to do.
2191 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2192 ConvertedType, IncompatibleObjC)) {
2193 // Okay, we have an Objective-C pointer conversion.
2194 HasObjCConversion = true;
2195 } else {
2196 // Argument types are too different. Abort.
2197 return false;
2198 }
2199 }
2200
2201 if (HasObjCConversion) {
2202 // We had an Objective-C conversion. Allow this pointer
2203 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002204 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002205 IncompatibleObjC = true;
2206 return true;
2207 }
2208 }
2209
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002210 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002211}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002212
John McCallf85e1932011-06-15 23:02:42 +00002213/// \brief Determine whether this is an Objective-C writeback conversion,
2214/// used for parameter passing when performing automatic reference counting.
2215///
2216/// \param FromType The type we're converting form.
2217///
2218/// \param ToType The type we're converting to.
2219///
2220/// \param ConvertedType The type that will be produced after applying
2221/// this conversion.
2222bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2223 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002224 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002225 Context.hasSameUnqualifiedType(FromType, ToType))
2226 return false;
2227
2228 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2229 QualType ToPointee;
2230 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2231 ToPointee = ToPointer->getPointeeType();
2232 else
2233 return false;
2234
2235 Qualifiers ToQuals = ToPointee.getQualifiers();
2236 if (!ToPointee->isObjCLifetimeType() ||
2237 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002238 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002239 return false;
2240
2241 // Argument must be a pointer to __strong to __weak.
2242 QualType FromPointee;
2243 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2244 FromPointee = FromPointer->getPointeeType();
2245 else
2246 return false;
2247
2248 Qualifiers FromQuals = FromPointee.getQualifiers();
2249 if (!FromPointee->isObjCLifetimeType() ||
2250 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2251 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2252 return false;
2253
2254 // Make sure that we have compatible qualifiers.
2255 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2256 if (!ToQuals.compatiblyIncludes(FromQuals))
2257 return false;
2258
2259 // Remove qualifiers from the pointee type we're converting from; they
2260 // aren't used in the compatibility check belong, and we'll be adding back
2261 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2262 FromPointee = FromPointee.getUnqualifiedType();
2263
2264 // The unqualified form of the pointee types must be compatible.
2265 ToPointee = ToPointee.getUnqualifiedType();
2266 bool IncompatibleObjC;
2267 if (Context.typesAreCompatible(FromPointee, ToPointee))
2268 FromPointee = ToPointee;
2269 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2270 IncompatibleObjC))
2271 return false;
2272
2273 /// \brief Construct the type we're converting to, which is a pointer to
2274 /// __autoreleasing pointee.
2275 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2276 ConvertedType = Context.getPointerType(FromPointee);
2277 return true;
2278}
2279
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002280bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2281 QualType& ConvertedType) {
2282 QualType ToPointeeType;
2283 if (const BlockPointerType *ToBlockPtr =
2284 ToType->getAs<BlockPointerType>())
2285 ToPointeeType = ToBlockPtr->getPointeeType();
2286 else
2287 return false;
2288
2289 QualType FromPointeeType;
2290 if (const BlockPointerType *FromBlockPtr =
2291 FromType->getAs<BlockPointerType>())
2292 FromPointeeType = FromBlockPtr->getPointeeType();
2293 else
2294 return false;
2295 // We have pointer to blocks, check whether the only
2296 // differences in the argument and result types are in Objective-C
2297 // pointer conversions. If so, we permit the conversion.
2298
2299 const FunctionProtoType *FromFunctionType
2300 = FromPointeeType->getAs<FunctionProtoType>();
2301 const FunctionProtoType *ToFunctionType
2302 = ToPointeeType->getAs<FunctionProtoType>();
2303
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002304 if (!FromFunctionType || !ToFunctionType)
2305 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002306
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002307 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002308 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002309
2310 // Perform the quick checks that will tell us whether these
2311 // function types are obviously different.
2312 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2313 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2314 return false;
2315
2316 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2317 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2318 if (FromEInfo != ToEInfo)
2319 return false;
2320
2321 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002322 if (Context.hasSameType(FromFunctionType->getResultType(),
2323 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002324 // Okay, the types match exactly. Nothing to do.
2325 } else {
2326 QualType RHS = FromFunctionType->getResultType();
2327 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002328 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002329 !RHS.hasQualifiers() && LHS.hasQualifiers())
2330 LHS = LHS.getUnqualifiedType();
2331
2332 if (Context.hasSameType(RHS,LHS)) {
2333 // OK exact match.
2334 } else if (isObjCPointerConversion(RHS, LHS,
2335 ConvertedType, IncompatibleObjC)) {
2336 if (IncompatibleObjC)
2337 return false;
2338 // Okay, we have an Objective-C pointer conversion.
2339 }
2340 else
2341 return false;
2342 }
2343
2344 // Check argument types.
2345 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2346 ArgIdx != NumArgs; ++ArgIdx) {
2347 IncompatibleObjC = false;
2348 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2349 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2350 if (Context.hasSameType(FromArgType, ToArgType)) {
2351 // Okay, the types match exactly. Nothing to do.
2352 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2353 ConvertedType, IncompatibleObjC)) {
2354 if (IncompatibleObjC)
2355 return false;
2356 // Okay, we have an Objective-C pointer conversion.
2357 } else
2358 // Argument types are too different. Abort.
2359 return false;
2360 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002361 if (LangOpts.ObjCAutoRefCount &&
2362 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2363 ToFunctionType))
2364 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002365
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002366 ConvertedType = ToType;
2367 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002368}
2369
Richard Trieu6efd4c52011-11-23 22:32:32 +00002370enum {
2371 ft_default,
2372 ft_different_class,
2373 ft_parameter_arity,
2374 ft_parameter_mismatch,
2375 ft_return_type,
2376 ft_qualifer_mismatch
2377};
2378
2379/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2380/// function types. Catches different number of parameter, mismatch in
2381/// parameter types, and different return types.
2382void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2383 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002384 // If either type is not valid, include no extra info.
2385 if (FromType.isNull() || ToType.isNull()) {
2386 PDiag << ft_default;
2387 return;
2388 }
2389
Richard Trieu6efd4c52011-11-23 22:32:32 +00002390 // Get the function type from the pointers.
2391 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2392 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2393 *ToMember = ToType->getAs<MemberPointerType>();
2394 if (FromMember->getClass() != ToMember->getClass()) {
2395 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2396 << QualType(FromMember->getClass(), 0);
2397 return;
2398 }
2399 FromType = FromMember->getPointeeType();
2400 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002401 }
2402
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002403 if (FromType->isPointerType())
2404 FromType = FromType->getPointeeType();
2405 if (ToType->isPointerType())
2406 ToType = ToType->getPointeeType();
2407
2408 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002409 FromType = FromType.getNonReferenceType();
2410 ToType = ToType.getNonReferenceType();
2411
Richard Trieu6efd4c52011-11-23 22:32:32 +00002412 // Don't print extra info for non-specialized template functions.
2413 if (FromType->isInstantiationDependentType() &&
2414 !FromType->getAs<TemplateSpecializationType>()) {
2415 PDiag << ft_default;
2416 return;
2417 }
2418
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002419 // No extra info for same types.
2420 if (Context.hasSameType(FromType, ToType)) {
2421 PDiag << ft_default;
2422 return;
2423 }
2424
Richard Trieu6efd4c52011-11-23 22:32:32 +00002425 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2426 *ToFunction = ToType->getAs<FunctionProtoType>();
2427
2428 // Both types need to be function types.
2429 if (!FromFunction || !ToFunction) {
2430 PDiag << ft_default;
2431 return;
2432 }
2433
2434 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2435 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2436 << FromFunction->getNumArgs();
2437 return;
2438 }
2439
2440 // Handle different parameter types.
2441 unsigned ArgPos;
2442 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2443 PDiag << ft_parameter_mismatch << ArgPos + 1
2444 << ToFunction->getArgType(ArgPos)
2445 << FromFunction->getArgType(ArgPos);
2446 return;
2447 }
2448
2449 // Handle different return type.
2450 if (!Context.hasSameType(FromFunction->getResultType(),
2451 ToFunction->getResultType())) {
2452 PDiag << ft_return_type << ToFunction->getResultType()
2453 << FromFunction->getResultType();
2454 return;
2455 }
2456
2457 unsigned FromQuals = FromFunction->getTypeQuals(),
2458 ToQuals = ToFunction->getTypeQuals();
2459 if (FromQuals != ToQuals) {
2460 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2461 return;
2462 }
2463
2464 // Unable to find a difference, so add no extra info.
2465 PDiag << ft_default;
2466}
2467
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002468/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002469/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002470/// they have same number of arguments. This routine assumes that Objective-C
2471/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002472/// If the parameters are different, ArgPos will have the the parameter index
2473/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002474bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002475 const FunctionProtoType *NewType,
2476 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002477 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002478 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2479 N = NewType->arg_type_begin(),
2480 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2481 if (!Context.hasSameType(*O, *N)) {
2482 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2483 return false;
2484 }
2485 }
2486 return true;
2487 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002488
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002489 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2490 N = NewType->arg_type_begin(),
2491 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2492 QualType ToType = (*O);
2493 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002494 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002495 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2496 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002497 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2498 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2499 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2500 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002501 continue;
2502 }
John McCallc12c5bb2010-05-15 11:32:37 +00002503 else if (const ObjCObjectPointerType *PTTo =
2504 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002505 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002506 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002507 if (Context.hasSameUnqualifiedType(
2508 PTTo->getObjectType()->getBaseType(),
2509 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002510 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002511 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002512 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002513 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002514 }
2515 }
2516 return true;
2517}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002518
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002519/// CheckPointerConversion - Check the pointer conversion from the
2520/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002521/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002522/// conversions for which IsPointerConversion has already returned
2523/// true. It returns true and produces a diagnostic if there was an
2524/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002525bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002526 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002527 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002528 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002529 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002530 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002531
John McCalldaa8e4e2010-11-15 09:13:47 +00002532 Kind = CK_BitCast;
2533
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002534 if (!IsCStyleOrFunctionalCast &&
2535 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2536 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2537 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002538 PDiag(diag::warn_impcast_bool_to_null_pointer)
2539 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002540
John McCall1d9b3b22011-09-09 05:25:32 +00002541 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2542 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002543 QualType FromPointeeType = FromPtrType->getPointeeType(),
2544 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002545
Douglas Gregor5fccd362010-03-03 23:55:11 +00002546 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2547 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002548 // We must have a derived-to-base conversion. Check an
2549 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002550 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2551 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002552 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002553 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002554 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002555
Anders Carlsson61faec12009-09-12 04:46:44 +00002556 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002557 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002558 }
2559 }
John McCall1d9b3b22011-09-09 05:25:32 +00002560 } else if (const ObjCObjectPointerType *ToPtrType =
2561 ToType->getAs<ObjCObjectPointerType>()) {
2562 if (const ObjCObjectPointerType *FromPtrType =
2563 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002564 // Objective-C++ conversions are always okay.
2565 // FIXME: We should have a different class of conversions for the
2566 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002567 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002568 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002569 } else if (FromType->isBlockPointerType()) {
2570 Kind = CK_BlockPointerToObjCPointerCast;
2571 } else {
2572 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002573 }
John McCall1d9b3b22011-09-09 05:25:32 +00002574 } else if (ToType->isBlockPointerType()) {
2575 if (!FromType->isBlockPointerType())
2576 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002577 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002578
2579 // We shouldn't fall into this case unless it's valid for other
2580 // reasons.
2581 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2582 Kind = CK_NullToPointer;
2583
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002584 return false;
2585}
2586
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002587/// IsMemberPointerConversion - Determines whether the conversion of the
2588/// expression From, which has the (possibly adjusted) type FromType, can be
2589/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2590/// If so, returns true and places the converted type (that might differ from
2591/// ToType in its cv-qualifiers at some level) into ConvertedType.
2592bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002593 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002594 bool InOverloadResolution,
2595 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002596 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002597 if (!ToTypePtr)
2598 return false;
2599
2600 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002601 if (From->isNullPointerConstant(Context,
2602 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2603 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002604 ConvertedType = ToType;
2605 return true;
2606 }
2607
2608 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002609 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002610 if (!FromTypePtr)
2611 return false;
2612
2613 // A pointer to member of B can be converted to a pointer to member of D,
2614 // where D is derived from B (C++ 4.11p2).
2615 QualType FromClass(FromTypePtr->getClass(), 0);
2616 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002617
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002618 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002619 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002620 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002621 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2622 ToClass.getTypePtr());
2623 return true;
2624 }
2625
2626 return false;
2627}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002628
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002629/// CheckMemberPointerConversion - Check the member pointer conversion from the
2630/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002631/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002632/// for which IsMemberPointerConversion has already returned true. It returns
2633/// true and produces a diagnostic if there was an error, or returns false
2634/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002635bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002636 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002637 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002638 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002639 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002640 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002641 if (!FromPtrType) {
2642 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002643 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002644 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002645 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002646 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002647 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002648 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002649
Ted Kremenek6217b802009-07-29 21:53:49 +00002650 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002651 assert(ToPtrType && "No member pointer cast has a target type "
2652 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002653
Sebastian Redl21593ac2009-01-28 18:33:18 +00002654 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2655 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002656
Sebastian Redl21593ac2009-01-28 18:33:18 +00002657 // FIXME: What about dependent types?
2658 assert(FromClass->isRecordType() && "Pointer into non-class.");
2659 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002660
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002661 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002662 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002663 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2664 assert(DerivationOkay &&
2665 "Should not have been called if derivation isn't OK.");
2666 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002667
Sebastian Redl21593ac2009-01-28 18:33:18 +00002668 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2669 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002670 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2671 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2672 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2673 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002674 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002675
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002676 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002677 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2678 << FromClass << ToClass << QualType(VBase, 0)
2679 << From->getSourceRange();
2680 return true;
2681 }
2682
John McCall6b2accb2010-02-10 09:31:12 +00002683 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002684 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2685 Paths.front(),
2686 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002687
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002688 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002689 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002690 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002691 return false;
2692}
2693
Douglas Gregor98cd5992008-10-21 23:43:52 +00002694/// IsQualificationConversion - Determines whether the conversion from
2695/// an rvalue of type FromType to ToType is a qualification conversion
2696/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002697///
2698/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2699/// when the qualification conversion involves a change in the Objective-C
2700/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002701bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002702Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002703 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002704 FromType = Context.getCanonicalType(FromType);
2705 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002706 ObjCLifetimeConversion = false;
2707
Douglas Gregor98cd5992008-10-21 23:43:52 +00002708 // If FromType and ToType are the same type, this is not a
2709 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002710 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002711 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002712
Douglas Gregor98cd5992008-10-21 23:43:52 +00002713 // (C++ 4.4p4):
2714 // A conversion can add cv-qualifiers at levels other than the first
2715 // in multi-level pointers, subject to the following rules: [...]
2716 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002717 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002718 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002719 // Within each iteration of the loop, we check the qualifiers to
2720 // determine if this still looks like a qualification
2721 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002722 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002723 // until there are no more pointers or pointers-to-members left to
2724 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002725 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002726
Douglas Gregor621c92a2011-04-25 18:40:17 +00002727 Qualifiers FromQuals = FromType.getQualifiers();
2728 Qualifiers ToQuals = ToType.getQualifiers();
2729
John McCallf85e1932011-06-15 23:02:42 +00002730 // Objective-C ARC:
2731 // Check Objective-C lifetime conversions.
2732 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2733 UnwrappedAnyPointer) {
2734 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2735 ObjCLifetimeConversion = true;
2736 FromQuals.removeObjCLifetime();
2737 ToQuals.removeObjCLifetime();
2738 } else {
2739 // Qualification conversions cannot cast between different
2740 // Objective-C lifetime qualifiers.
2741 return false;
2742 }
2743 }
2744
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002745 // Allow addition/removal of GC attributes but not changing GC attributes.
2746 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2747 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2748 FromQuals.removeObjCGCAttr();
2749 ToQuals.removeObjCGCAttr();
2750 }
2751
Douglas Gregor98cd5992008-10-21 23:43:52 +00002752 // -- for every j > 0, if const is in cv 1,j then const is in cv
2753 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002754 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002755 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002756
Douglas Gregor98cd5992008-10-21 23:43:52 +00002757 // -- if the cv 1,j and cv 2,j are different, then const is in
2758 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002759 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002760 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002761 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002762
Douglas Gregor98cd5992008-10-21 23:43:52 +00002763 // Keep track of whether all prior cv-qualifiers in the "to" type
2764 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002765 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002766 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002767 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002768
2769 // We are left with FromType and ToType being the pointee types
2770 // after unwrapping the original FromType and ToType the same number
2771 // of types. If we unwrapped any pointers, and if FromType and
2772 // ToType have the same unqualified type (since we checked
2773 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002774 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002775}
2776
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002777/// \brief - Determine whether this is a conversion from a scalar type to an
2778/// atomic type.
2779///
2780/// If successful, updates \c SCS's second and third steps in the conversion
2781/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002782static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2783 bool InOverloadResolution,
2784 StandardConversionSequence &SCS,
2785 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002786 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2787 if (!ToAtomic)
2788 return false;
2789
2790 StandardConversionSequence InnerSCS;
2791 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2792 InOverloadResolution, InnerSCS,
2793 CStyle, /*AllowObjCWritebackConversion=*/false))
2794 return false;
2795
2796 SCS.Second = InnerSCS.Second;
2797 SCS.setToType(1, InnerSCS.getToType(1));
2798 SCS.Third = InnerSCS.Third;
2799 SCS.QualificationIncludesObjCLifetime
2800 = InnerSCS.QualificationIncludesObjCLifetime;
2801 SCS.setToType(2, InnerSCS.getToType(2));
2802 return true;
2803}
2804
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002805static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2806 CXXConstructorDecl *Constructor,
2807 QualType Type) {
2808 const FunctionProtoType *CtorType =
2809 Constructor->getType()->getAs<FunctionProtoType>();
2810 if (CtorType->getNumArgs() > 0) {
2811 QualType FirstArg = CtorType->getArgType(0);
2812 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2813 return true;
2814 }
2815 return false;
2816}
2817
Sebastian Redl56a04282012-02-11 23:51:08 +00002818static OverloadingResult
2819IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2820 CXXRecordDecl *To,
2821 UserDefinedConversionSequence &User,
2822 OverloadCandidateSet &CandidateSet,
2823 bool AllowExplicit) {
2824 DeclContext::lookup_iterator Con, ConEnd;
2825 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2826 Con != ConEnd; ++Con) {
2827 NamedDecl *D = *Con;
2828 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2829
2830 // Find the constructor (which may be a template).
2831 CXXConstructorDecl *Constructor = 0;
2832 FunctionTemplateDecl *ConstructorTmpl
2833 = dyn_cast<FunctionTemplateDecl>(D);
2834 if (ConstructorTmpl)
2835 Constructor
2836 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2837 else
2838 Constructor = cast<CXXConstructorDecl>(D);
2839
2840 bool Usable = !Constructor->isInvalidDecl() &&
2841 S.isInitListConstructor(Constructor) &&
2842 (AllowExplicit || !Constructor->isExplicit());
2843 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002844 // If the first argument is (a reference to) the target type,
2845 // suppress conversions.
2846 bool SuppressUserConversions =
2847 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002848 if (ConstructorTmpl)
2849 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2850 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002851 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002852 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002853 else
2854 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002855 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002856 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002857 }
2858 }
2859
2860 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2861
2862 OverloadCandidateSet::iterator Best;
2863 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2864 case OR_Success: {
2865 // Record the standard conversion we used and the conversion function.
2866 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2867 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2868
2869 QualType ThisType = Constructor->getThisType(S.Context);
2870 // Initializer lists don't have conversions as such.
2871 User.Before.setAsIdentityConversion();
2872 User.HadMultipleCandidates = HadMultipleCandidates;
2873 User.ConversionFunction = Constructor;
2874 User.FoundConversionFunction = Best->FoundDecl;
2875 User.After.setAsIdentityConversion();
2876 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2877 User.After.setAllToTypes(ToType);
2878 return OR_Success;
2879 }
2880
2881 case OR_No_Viable_Function:
2882 return OR_No_Viable_Function;
2883 case OR_Deleted:
2884 return OR_Deleted;
2885 case OR_Ambiguous:
2886 return OR_Ambiguous;
2887 }
2888
2889 llvm_unreachable("Invalid OverloadResult!");
2890}
2891
Douglas Gregor734d9862009-01-30 23:27:23 +00002892/// Determines whether there is a user-defined conversion sequence
2893/// (C++ [over.ics.user]) that converts expression From to the type
2894/// ToType. If such a conversion exists, User will contain the
2895/// user-defined conversion sequence that performs such a conversion
2896/// and this routine will return true. Otherwise, this routine returns
2897/// false and User is unspecified.
2898///
Douglas Gregor734d9862009-01-30 23:27:23 +00002899/// \param AllowExplicit true if the conversion should consider C++0x
2900/// "explicit" conversion functions as well as non-explicit conversion
2901/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002902static OverloadingResult
2903IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002904 UserDefinedConversionSequence &User,
2905 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002906 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002907 // Whether we will only visit constructors.
2908 bool ConstructorsOnly = false;
2909
2910 // If the type we are conversion to is a class type, enumerate its
2911 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002912 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002913 // C++ [over.match.ctor]p1:
2914 // When objects of class type are direct-initialized (8.5), or
2915 // copy-initialized from an expression of the same or a
2916 // derived class type (8.5), overload resolution selects the
2917 // constructor. [...] For copy-initialization, the candidate
2918 // functions are all the converting constructors (12.3.1) of
2919 // that class. The argument list is the expression-list within
2920 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002921 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002922 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002923 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002924 ConstructorsOnly = true;
2925
Douglas Gregord10099e2012-05-04 16:32:21 +00002926 S.RequireCompleteType(From->getLocStart(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002927 // RequireCompleteType may have returned true due to some invalid decl
2928 // during template instantiation, but ToType may be complete enough now
2929 // to try to recover.
2930 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002931 // We're not going to find any constructors.
2932 } else if (CXXRecordDecl *ToRecordDecl
2933 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002934
2935 Expr **Args = &From;
2936 unsigned NumArgs = 1;
2937 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002938 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002939 // But first, see if there is an init-list-contructor that will work.
2940 OverloadingResult Result = IsInitializerListConstructorConversion(
2941 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2942 if (Result != OR_No_Viable_Function)
2943 return Result;
2944 // Never mind.
2945 CandidateSet.clear();
2946
2947 // If we're list-initializing, we pass the individual elements as
2948 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002949 Args = InitList->getInits();
2950 NumArgs = InitList->getNumInits();
2951 ListInitializing = true;
2952 }
2953
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002954 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002955 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002956 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002957 NamedDecl *D = *Con;
2958 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2959
Douglas Gregordec06662009-08-21 18:42:58 +00002960 // Find the constructor (which may be a template).
2961 CXXConstructorDecl *Constructor = 0;
2962 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002963 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002964 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002965 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002966 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2967 else
John McCall9aa472c2010-03-19 07:35:19 +00002968 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002969
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002970 bool Usable = !Constructor->isInvalidDecl();
2971 if (ListInitializing)
2972 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2973 else
2974 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2975 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002976 bool SuppressUserConversions = !ConstructorsOnly;
2977 if (SuppressUserConversions && ListInitializing) {
2978 SuppressUserConversions = false;
2979 if (NumArgs == 1) {
2980 // If the first argument is (a reference to) the target type,
2981 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002982 SuppressUserConversions = isFirstArgumentCompatibleWithType(
2983 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002984 }
2985 }
Douglas Gregordec06662009-08-21 18:42:58 +00002986 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002987 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2988 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002989 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002990 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00002991 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002992 // Allow one user-defined conversion when user specifies a
2993 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002994 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002995 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002996 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00002997 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002998 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002999 }
3000 }
3001
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003002 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003003 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003004 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003005 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003006 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003007 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003008 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003009 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3010 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00003011 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003012 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003013 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003014 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003015 DeclAccessPair FoundDecl = I.getPair();
3016 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003017 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3018 if (isa<UsingShadowDecl>(D))
3019 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3020
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003021 CXXConversionDecl *Conv;
3022 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003023 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3024 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003025 else
John McCall32daa422010-03-31 01:36:47 +00003026 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003027
3028 if (AllowExplicit || !Conv->isExplicit()) {
3029 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003030 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3031 ActingContext, From, ToType,
3032 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003033 else
John McCall120d63c2010-08-24 20:38:10 +00003034 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3035 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003036 }
3037 }
3038 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003039 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003040
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003041 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3042
Douglas Gregor60d62c22008-10-31 16:23:19 +00003043 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003044 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003045 case OR_Success:
3046 // Record the standard conversion we used and the conversion function.
3047 if (CXXConstructorDecl *Constructor
3048 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003049 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003050
John McCall120d63c2010-08-24 20:38:10 +00003051 // C++ [over.ics.user]p1:
3052 // If the user-defined conversion is specified by a
3053 // constructor (12.3.1), the initial standard conversion
3054 // sequence converts the source type to the type required by
3055 // the argument of the constructor.
3056 //
3057 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003058 if (isa<InitListExpr>(From)) {
3059 // Initializer lists don't have conversions as such.
3060 User.Before.setAsIdentityConversion();
3061 } else {
3062 if (Best->Conversions[0].isEllipsis())
3063 User.EllipsisConversion = true;
3064 else {
3065 User.Before = Best->Conversions[0].Standard;
3066 User.EllipsisConversion = false;
3067 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003068 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003069 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003070 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003071 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003072 User.After.setAsIdentityConversion();
3073 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3074 User.After.setAllToTypes(ToType);
3075 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003076 }
3077 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003078 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003079 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003080
John McCall120d63c2010-08-24 20:38:10 +00003081 // C++ [over.ics.user]p1:
3082 //
3083 // [...] If the user-defined conversion is specified by a
3084 // conversion function (12.3.2), the initial standard
3085 // conversion sequence converts the source type to the
3086 // implicit object parameter of the conversion function.
3087 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003088 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003089 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003090 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003091 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003092
John McCall120d63c2010-08-24 20:38:10 +00003093 // C++ [over.ics.user]p2:
3094 // The second standard conversion sequence converts the
3095 // result of the user-defined conversion to the target type
3096 // for the sequence. Since an implicit conversion sequence
3097 // is an initialization, the special rules for
3098 // initialization by user-defined conversion apply when
3099 // selecting the best user-defined conversion for a
3100 // user-defined conversion sequence (see 13.3.3 and
3101 // 13.3.3.1).
3102 User.After = Best->FinalConversion;
3103 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003104 }
David Blaikie7530c032012-01-17 06:56:22 +00003105 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003106
John McCall120d63c2010-08-24 20:38:10 +00003107 case OR_No_Viable_Function:
3108 return OR_No_Viable_Function;
3109 case OR_Deleted:
3110 // No conversion here! We're done.
3111 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003112
John McCall120d63c2010-08-24 20:38:10 +00003113 case OR_Ambiguous:
3114 return OR_Ambiguous;
3115 }
3116
David Blaikie7530c032012-01-17 06:56:22 +00003117 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003118}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003119
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003120bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003121Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003122 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003123 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003124 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003125 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003126 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003127 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003128 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003129 diag::err_typecheck_ambiguous_condition)
3130 << From->getType() << ToType << From->getSourceRange();
3131 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003132 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003133 diag::err_typecheck_nonviable_condition)
3134 << From->getType() << ToType << From->getSourceRange();
3135 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003136 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003137 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003138 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003139}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003140
Douglas Gregorb734e242012-02-22 17:32:19 +00003141/// \brief Compare the user-defined conversion functions or constructors
3142/// of two user-defined conversion sequences to determine whether any ordering
3143/// is possible.
3144static ImplicitConversionSequence::CompareKind
3145compareConversionFunctions(Sema &S,
3146 FunctionDecl *Function1,
3147 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003148 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003149 return ImplicitConversionSequence::Indistinguishable;
3150
3151 // Objective-C++:
3152 // If both conversion functions are implicitly-declared conversions from
3153 // a lambda closure type to a function pointer and a block pointer,
3154 // respectively, always prefer the conversion to a function pointer,
3155 // because the function pointer is more lightweight and is more likely
3156 // to keep code working.
3157 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3158 if (!Conv1)
3159 return ImplicitConversionSequence::Indistinguishable;
3160
3161 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3162 if (!Conv2)
3163 return ImplicitConversionSequence::Indistinguishable;
3164
3165 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3166 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3167 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3168 if (Block1 != Block2)
3169 return Block1? ImplicitConversionSequence::Worse
3170 : ImplicitConversionSequence::Better;
3171 }
3172
3173 return ImplicitConversionSequence::Indistinguishable;
3174}
3175
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003176/// CompareImplicitConversionSequences - Compare two implicit
3177/// conversion sequences to determine whether one is better than the
3178/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003179static ImplicitConversionSequence::CompareKind
3180CompareImplicitConversionSequences(Sema &S,
3181 const ImplicitConversionSequence& ICS1,
3182 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003183{
3184 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3185 // conversion sequences (as defined in 13.3.3.1)
3186 // -- a standard conversion sequence (13.3.3.1.1) is a better
3187 // conversion sequence than a user-defined conversion sequence or
3188 // an ellipsis conversion sequence, and
3189 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3190 // conversion sequence than an ellipsis conversion sequence
3191 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003192 //
John McCall1d318332010-01-12 00:44:57 +00003193 // C++0x [over.best.ics]p10:
3194 // For the purpose of ranking implicit conversion sequences as
3195 // described in 13.3.3.2, the ambiguous conversion sequence is
3196 // treated as a user-defined sequence that is indistinguishable
3197 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003198 if (ICS1.getKindRank() < ICS2.getKindRank())
3199 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003200 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003201 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003202
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003203 // The following checks require both conversion sequences to be of
3204 // the same kind.
3205 if (ICS1.getKind() != ICS2.getKind())
3206 return ImplicitConversionSequence::Indistinguishable;
3207
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003208 ImplicitConversionSequence::CompareKind Result =
3209 ImplicitConversionSequence::Indistinguishable;
3210
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003211 // Two implicit conversion sequences of the same form are
3212 // indistinguishable conversion sequences unless one of the
3213 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003214 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003215 Result = CompareStandardConversionSequences(S,
3216 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003217 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003218 // User-defined conversion sequence U1 is a better conversion
3219 // sequence than another user-defined conversion sequence U2 if
3220 // they contain the same user-defined conversion function or
3221 // constructor and if the second standard conversion sequence of
3222 // U1 is better than the second standard conversion sequence of
3223 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003224 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003225 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003226 Result = CompareStandardConversionSequences(S,
3227 ICS1.UserDefined.After,
3228 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003229 else
3230 Result = compareConversionFunctions(S,
3231 ICS1.UserDefined.ConversionFunction,
3232 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003233 }
3234
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003235 // List-initialization sequence L1 is a better conversion sequence than
3236 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3237 // for some X and L2 does not.
3238 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003239 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003240 ICS1.isListInitializationSequence() &&
3241 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003242 if (ICS1.isStdInitializerListElement() &&
3243 !ICS2.isStdInitializerListElement())
3244 return ImplicitConversionSequence::Better;
3245 if (!ICS1.isStdInitializerListElement() &&
3246 ICS2.isStdInitializerListElement())
3247 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003248 }
3249
3250 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003251}
3252
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003253static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3254 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3255 Qualifiers Quals;
3256 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003257 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003258 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003259
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003260 return Context.hasSameUnqualifiedType(T1, T2);
3261}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003262
Douglas Gregorad323a82010-01-27 03:51:04 +00003263// Per 13.3.3.2p3, compare the given standard conversion sequences to
3264// determine if one is a proper subset of the other.
3265static ImplicitConversionSequence::CompareKind
3266compareStandardConversionSubsets(ASTContext &Context,
3267 const StandardConversionSequence& SCS1,
3268 const StandardConversionSequence& SCS2) {
3269 ImplicitConversionSequence::CompareKind Result
3270 = ImplicitConversionSequence::Indistinguishable;
3271
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003272 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003273 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003274 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3275 return ImplicitConversionSequence::Better;
3276 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3277 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003278
Douglas Gregorad323a82010-01-27 03:51:04 +00003279 if (SCS1.Second != SCS2.Second) {
3280 if (SCS1.Second == ICK_Identity)
3281 Result = ImplicitConversionSequence::Better;
3282 else if (SCS2.Second == ICK_Identity)
3283 Result = ImplicitConversionSequence::Worse;
3284 else
3285 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003286 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003287 return ImplicitConversionSequence::Indistinguishable;
3288
3289 if (SCS1.Third == SCS2.Third) {
3290 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3291 : ImplicitConversionSequence::Indistinguishable;
3292 }
3293
3294 if (SCS1.Third == ICK_Identity)
3295 return Result == ImplicitConversionSequence::Worse
3296 ? ImplicitConversionSequence::Indistinguishable
3297 : ImplicitConversionSequence::Better;
3298
3299 if (SCS2.Third == ICK_Identity)
3300 return Result == ImplicitConversionSequence::Better
3301 ? ImplicitConversionSequence::Indistinguishable
3302 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003303
Douglas Gregorad323a82010-01-27 03:51:04 +00003304 return ImplicitConversionSequence::Indistinguishable;
3305}
3306
Douglas Gregor440a4832011-01-26 14:52:12 +00003307/// \brief Determine whether one of the given reference bindings is better
3308/// than the other based on what kind of bindings they are.
3309static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3310 const StandardConversionSequence &SCS2) {
3311 // C++0x [over.ics.rank]p3b4:
3312 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3313 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003314 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003315 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003316 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003317 // reference*.
3318 //
3319 // FIXME: Rvalue references. We're going rogue with the above edits,
3320 // because the semantics in the current C++0x working paper (N3225 at the
3321 // time of this writing) break the standard definition of std::forward
3322 // and std::reference_wrapper when dealing with references to functions.
3323 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003324 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3325 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3326 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327
Douglas Gregor440a4832011-01-26 14:52:12 +00003328 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3329 SCS2.IsLvalueReference) ||
3330 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3331 !SCS2.IsLvalueReference);
3332}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003333
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003334/// CompareStandardConversionSequences - Compare two standard
3335/// conversion sequences to determine whether one is better than the
3336/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003337static ImplicitConversionSequence::CompareKind
3338CompareStandardConversionSequences(Sema &S,
3339 const StandardConversionSequence& SCS1,
3340 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003341{
3342 // Standard conversion sequence S1 is a better conversion sequence
3343 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3344
3345 // -- S1 is a proper subsequence of S2 (comparing the conversion
3346 // sequences in the canonical form defined by 13.3.3.1.1,
3347 // excluding any Lvalue Transformation; the identity conversion
3348 // sequence is considered to be a subsequence of any
3349 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003350 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003351 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003352 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003353
3354 // -- the rank of S1 is better than the rank of S2 (by the rules
3355 // defined below), or, if not that,
3356 ImplicitConversionRank Rank1 = SCS1.getRank();
3357 ImplicitConversionRank Rank2 = SCS2.getRank();
3358 if (Rank1 < Rank2)
3359 return ImplicitConversionSequence::Better;
3360 else if (Rank2 < Rank1)
3361 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003362
Douglas Gregor57373262008-10-22 14:17:15 +00003363 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3364 // are indistinguishable unless one of the following rules
3365 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003366
Douglas Gregor57373262008-10-22 14:17:15 +00003367 // A conversion that is not a conversion of a pointer, or
3368 // pointer to member, to bool is better than another conversion
3369 // that is such a conversion.
3370 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3371 return SCS2.isPointerConversionToBool()
3372 ? ImplicitConversionSequence::Better
3373 : ImplicitConversionSequence::Worse;
3374
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003375 // C++ [over.ics.rank]p4b2:
3376 //
3377 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003378 // conversion of B* to A* is better than conversion of B* to
3379 // void*, and conversion of A* to void* is better than conversion
3380 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003381 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003382 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003383 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003384 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003385 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3386 // Exactly one of the conversion sequences is a conversion to
3387 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003388 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3389 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003390 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3391 // Neither conversion sequence converts to a void pointer; compare
3392 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003393 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003394 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003395 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003396 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3397 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003398 // Both conversion sequences are conversions to void
3399 // pointers. Compare the source types to determine if there's an
3400 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003401 QualType FromType1 = SCS1.getFromType();
3402 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003403
3404 // Adjust the types we're converting from via the array-to-pointer
3405 // conversion, if we need to.
3406 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003407 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003408 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003409 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003410
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003411 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3412 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003413
John McCall120d63c2010-08-24 20:38:10 +00003414 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003415 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003416 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003417 return ImplicitConversionSequence::Worse;
3418
3419 // Objective-C++: If one interface is more specific than the
3420 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003421 const ObjCObjectPointerType* FromObjCPtr1
3422 = FromType1->getAs<ObjCObjectPointerType>();
3423 const ObjCObjectPointerType* FromObjCPtr2
3424 = FromType2->getAs<ObjCObjectPointerType>();
3425 if (FromObjCPtr1 && FromObjCPtr2) {
3426 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3427 FromObjCPtr2);
3428 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3429 FromObjCPtr1);
3430 if (AssignLeft != AssignRight) {
3431 return AssignLeft? ImplicitConversionSequence::Better
3432 : ImplicitConversionSequence::Worse;
3433 }
Douglas Gregor01919692009-12-13 21:37:05 +00003434 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003435 }
Douglas Gregor57373262008-10-22 14:17:15 +00003436
3437 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3438 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003439 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003440 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003441 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003442
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003443 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003444 // Check for a better reference binding based on the kind of bindings.
3445 if (isBetterReferenceBindingKind(SCS1, SCS2))
3446 return ImplicitConversionSequence::Better;
3447 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3448 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003449
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003450 // C++ [over.ics.rank]p3b4:
3451 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3452 // which the references refer are the same type except for
3453 // top-level cv-qualifiers, and the type to which the reference
3454 // initialized by S2 refers is more cv-qualified than the type
3455 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003456 QualType T1 = SCS1.getToType(2);
3457 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003458 T1 = S.Context.getCanonicalType(T1);
3459 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003460 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003461 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3462 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003463 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003464 // Objective-C++ ARC: If the references refer to objects with different
3465 // lifetimes, prefer bindings that don't change lifetime.
3466 if (SCS1.ObjCLifetimeConversionBinding !=
3467 SCS2.ObjCLifetimeConversionBinding) {
3468 return SCS1.ObjCLifetimeConversionBinding
3469 ? ImplicitConversionSequence::Worse
3470 : ImplicitConversionSequence::Better;
3471 }
3472
Chandler Carruth6df868e2010-12-12 08:17:55 +00003473 // If the type is an array type, promote the element qualifiers to the
3474 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003475 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003476 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003477 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003478 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003479 if (T2.isMoreQualifiedThan(T1))
3480 return ImplicitConversionSequence::Better;
3481 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003482 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003483 }
3484 }
Douglas Gregor57373262008-10-22 14:17:15 +00003485
Francois Pichet1c98d622011-09-18 21:37:37 +00003486 // In Microsoft mode, prefer an integral conversion to a
3487 // floating-to-integral conversion if the integral conversion
3488 // is between types of the same size.
3489 // For example:
3490 // void f(float);
3491 // void f(int);
3492 // int main {
3493 // long a;
3494 // f(a);
3495 // }
3496 // Here, MSVC will call f(int) instead of generating a compile error
3497 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003498 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003499 SCS1.Second == ICK_Integral_Conversion &&
3500 SCS2.Second == ICK_Floating_Integral &&
3501 S.Context.getTypeSize(SCS1.getFromType()) ==
3502 S.Context.getTypeSize(SCS1.getToType(2)))
3503 return ImplicitConversionSequence::Better;
3504
Douglas Gregor57373262008-10-22 14:17:15 +00003505 return ImplicitConversionSequence::Indistinguishable;
3506}
3507
3508/// CompareQualificationConversions - Compares two standard conversion
3509/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003510/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3511ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003512CompareQualificationConversions(Sema &S,
3513 const StandardConversionSequence& SCS1,
3514 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003515 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003516 // -- S1 and S2 differ only in their qualification conversion and
3517 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3518 // cv-qualification signature of type T1 is a proper subset of
3519 // the cv-qualification signature of type T2, and S1 is not the
3520 // deprecated string literal array-to-pointer conversion (4.2).
3521 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3522 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3523 return ImplicitConversionSequence::Indistinguishable;
3524
3525 // FIXME: the example in the standard doesn't use a qualification
3526 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003527 QualType T1 = SCS1.getToType(2);
3528 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003529 T1 = S.Context.getCanonicalType(T1);
3530 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003531 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003532 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3533 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003534
3535 // If the types are the same, we won't learn anything by unwrapped
3536 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003537 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003538 return ImplicitConversionSequence::Indistinguishable;
3539
Chandler Carruth28e318c2009-12-29 07:16:59 +00003540 // If the type is an array type, promote the element qualifiers to the type
3541 // for comparison.
3542 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003543 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003544 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003545 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003546
Mike Stump1eb44332009-09-09 15:08:12 +00003547 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003548 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003549
3550 // Objective-C++ ARC:
3551 // Prefer qualification conversions not involving a change in lifetime
3552 // to qualification conversions that do not change lifetime.
3553 if (SCS1.QualificationIncludesObjCLifetime !=
3554 SCS2.QualificationIncludesObjCLifetime) {
3555 Result = SCS1.QualificationIncludesObjCLifetime
3556 ? ImplicitConversionSequence::Worse
3557 : ImplicitConversionSequence::Better;
3558 }
3559
John McCall120d63c2010-08-24 20:38:10 +00003560 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003561 // Within each iteration of the loop, we check the qualifiers to
3562 // determine if this still looks like a qualification
3563 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003564 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003565 // until there are no more pointers or pointers-to-members left
3566 // to unwrap. This essentially mimics what
3567 // IsQualificationConversion does, but here we're checking for a
3568 // strict subset of qualifiers.
3569 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3570 // The qualifiers are the same, so this doesn't tell us anything
3571 // about how the sequences rank.
3572 ;
3573 else if (T2.isMoreQualifiedThan(T1)) {
3574 // T1 has fewer qualifiers, so it could be the better sequence.
3575 if (Result == ImplicitConversionSequence::Worse)
3576 // Neither has qualifiers that are a subset of the other's
3577 // qualifiers.
3578 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003579
Douglas Gregor57373262008-10-22 14:17:15 +00003580 Result = ImplicitConversionSequence::Better;
3581 } else if (T1.isMoreQualifiedThan(T2)) {
3582 // T2 has fewer qualifiers, so it could be the better sequence.
3583 if (Result == ImplicitConversionSequence::Better)
3584 // Neither has qualifiers that are a subset of the other's
3585 // qualifiers.
3586 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003587
Douglas Gregor57373262008-10-22 14:17:15 +00003588 Result = ImplicitConversionSequence::Worse;
3589 } else {
3590 // Qualifiers are disjoint.
3591 return ImplicitConversionSequence::Indistinguishable;
3592 }
3593
3594 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003595 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003596 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003597 }
3598
Douglas Gregor57373262008-10-22 14:17:15 +00003599 // Check that the winning standard conversion sequence isn't using
3600 // the deprecated string literal array to pointer conversion.
3601 switch (Result) {
3602 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003603 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003604 Result = ImplicitConversionSequence::Indistinguishable;
3605 break;
3606
3607 case ImplicitConversionSequence::Indistinguishable:
3608 break;
3609
3610 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003611 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003612 Result = ImplicitConversionSequence::Indistinguishable;
3613 break;
3614 }
3615
3616 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003617}
3618
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003619/// CompareDerivedToBaseConversions - Compares two standard conversion
3620/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003621/// various kinds of derived-to-base conversions (C++
3622/// [over.ics.rank]p4b3). As part of these checks, we also look at
3623/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003624ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003625CompareDerivedToBaseConversions(Sema &S,
3626 const StandardConversionSequence& SCS1,
3627 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003628 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003629 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003630 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003631 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003632
3633 // Adjust the types we're converting from via the array-to-pointer
3634 // conversion, if we need to.
3635 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003636 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003637 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003638 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003639
3640 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003641 FromType1 = S.Context.getCanonicalType(FromType1);
3642 ToType1 = S.Context.getCanonicalType(ToType1);
3643 FromType2 = S.Context.getCanonicalType(FromType2);
3644 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003645
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003646 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003647 //
3648 // If class B is derived directly or indirectly from class A and
3649 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003650 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003651 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003652 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003653 SCS2.Second == ICK_Pointer_Conversion &&
3654 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3655 FromType1->isPointerType() && FromType2->isPointerType() &&
3656 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003657 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003658 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003659 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003660 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003661 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003662 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003663 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003664 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003665
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003666 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003667 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003668 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003669 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003670 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003671 return ImplicitConversionSequence::Worse;
3672 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003673
3674 // -- conversion of B* to A* is better than conversion of C* to A*,
3675 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003676 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003677 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003678 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003679 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003680 }
3681 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3682 SCS2.Second == ICK_Pointer_Conversion) {
3683 const ObjCObjectPointerType *FromPtr1
3684 = FromType1->getAs<ObjCObjectPointerType>();
3685 const ObjCObjectPointerType *FromPtr2
3686 = FromType2->getAs<ObjCObjectPointerType>();
3687 const ObjCObjectPointerType *ToPtr1
3688 = ToType1->getAs<ObjCObjectPointerType>();
3689 const ObjCObjectPointerType *ToPtr2
3690 = ToType2->getAs<ObjCObjectPointerType>();
3691
3692 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3693 // Apply the same conversion ranking rules for Objective-C pointer types
3694 // that we do for C++ pointers to class types. However, we employ the
3695 // Objective-C pseudo-subtyping relationship used for assignment of
3696 // Objective-C pointer types.
3697 bool FromAssignLeft
3698 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3699 bool FromAssignRight
3700 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3701 bool ToAssignLeft
3702 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3703 bool ToAssignRight
3704 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3705
3706 // A conversion to an a non-id object pointer type or qualified 'id'
3707 // type is better than a conversion to 'id'.
3708 if (ToPtr1->isObjCIdType() &&
3709 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3710 return ImplicitConversionSequence::Worse;
3711 if (ToPtr2->isObjCIdType() &&
3712 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3713 return ImplicitConversionSequence::Better;
3714
3715 // A conversion to a non-id object pointer type is better than a
3716 // conversion to a qualified 'id' type
3717 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3718 return ImplicitConversionSequence::Worse;
3719 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3720 return ImplicitConversionSequence::Better;
3721
3722 // A conversion to an a non-Class object pointer type or qualified 'Class'
3723 // type is better than a conversion to 'Class'.
3724 if (ToPtr1->isObjCClassType() &&
3725 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3726 return ImplicitConversionSequence::Worse;
3727 if (ToPtr2->isObjCClassType() &&
3728 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3729 return ImplicitConversionSequence::Better;
3730
3731 // A conversion to a non-Class object pointer type is better than a
3732 // conversion to a qualified 'Class' type.
3733 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3734 return ImplicitConversionSequence::Worse;
3735 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3736 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003737
Douglas Gregor395cc372011-01-31 18:51:41 +00003738 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3739 if (S.Context.hasSameType(FromType1, FromType2) &&
3740 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3741 (ToAssignLeft != ToAssignRight))
3742 return ToAssignLeft? ImplicitConversionSequence::Worse
3743 : ImplicitConversionSequence::Better;
3744
3745 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3746 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3747 (FromAssignLeft != FromAssignRight))
3748 return FromAssignLeft? ImplicitConversionSequence::Better
3749 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003750 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003751 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003752
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003753 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003754 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3755 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3756 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003757 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003758 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003759 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003760 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003761 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003762 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003763 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003764 ToType2->getAs<MemberPointerType>();
3765 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3766 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3767 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3768 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3769 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3770 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3771 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3772 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003773 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003774 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003775 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003776 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003777 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003778 return ImplicitConversionSequence::Better;
3779 }
3780 // conversion of B::* to C::* is better than conversion of A::* to C::*
3781 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003782 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003783 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003784 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003785 return ImplicitConversionSequence::Worse;
3786 }
3787 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003789 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003790 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003791 // -- binding of an expression of type C to a reference of type
3792 // B& is better than binding an expression of type C to a
3793 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003794 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3795 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3796 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003797 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003798 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003799 return ImplicitConversionSequence::Worse;
3800 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003801
Douglas Gregor225c41e2008-11-03 19:09:14 +00003802 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003803 // -- binding of an expression of type B to a reference of type
3804 // A& is better than binding an expression of type C to a
3805 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003806 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3807 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3808 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003809 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003810 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003811 return ImplicitConversionSequence::Worse;
3812 }
3813 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003814
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003815 return ImplicitConversionSequence::Indistinguishable;
3816}
3817
Douglas Gregorabe183d2010-04-13 16:31:36 +00003818/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3819/// determine whether they are reference-related,
3820/// reference-compatible, reference-compatible with added
3821/// qualification, or incompatible, for use in C++ initialization by
3822/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3823/// type, and the first type (T1) is the pointee type of the reference
3824/// type being initialized.
3825Sema::ReferenceCompareResult
3826Sema::CompareReferenceRelationship(SourceLocation Loc,
3827 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003828 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003829 bool &ObjCConversion,
3830 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003831 assert(!OrigT1->isReferenceType() &&
3832 "T1 must be the pointee type of the reference type");
3833 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3834
3835 QualType T1 = Context.getCanonicalType(OrigT1);
3836 QualType T2 = Context.getCanonicalType(OrigT2);
3837 Qualifiers T1Quals, T2Quals;
3838 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3839 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3840
3841 // C++ [dcl.init.ref]p4:
3842 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3843 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3844 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003845 DerivedToBase = false;
3846 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003847 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003848 if (UnqualT1 == UnqualT2) {
3849 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003850 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003851 IsDerivedFrom(UnqualT2, UnqualT1))
3852 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003853 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3854 UnqualT2->isObjCObjectOrInterfaceType() &&
3855 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3856 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003857 else
3858 return Ref_Incompatible;
3859
3860 // At this point, we know that T1 and T2 are reference-related (at
3861 // least).
3862
3863 // If the type is an array type, promote the element qualifiers to the type
3864 // for comparison.
3865 if (isa<ArrayType>(T1) && T1Quals)
3866 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3867 if (isa<ArrayType>(T2) && T2Quals)
3868 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3869
3870 // C++ [dcl.init.ref]p4:
3871 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3872 // reference-related to T2 and cv1 is the same cv-qualification
3873 // as, or greater cv-qualification than, cv2. For purposes of
3874 // overload resolution, cases for which cv1 is greater
3875 // cv-qualification than cv2 are identified as
3876 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003877 //
3878 // Note that we also require equivalence of Objective-C GC and address-space
3879 // qualifiers when performing these computations, so that e.g., an int in
3880 // address space 1 is not reference-compatible with an int in address
3881 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003882 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3883 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3884 T1Quals.removeObjCLifetime();
3885 T2Quals.removeObjCLifetime();
3886 ObjCLifetimeConversion = true;
3887 }
3888
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003889 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003890 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003891 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003892 return Ref_Compatible_With_Added_Qualification;
3893 else
3894 return Ref_Related;
3895}
3896
Douglas Gregor604eb652010-08-11 02:15:33 +00003897/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003898/// with DeclType. Return true if something definite is found.
3899static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003900FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3901 QualType DeclType, SourceLocation DeclLoc,
3902 Expr *Init, QualType T2, bool AllowRvalues,
3903 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003904 assert(T2->isRecordType() && "Can only find conversions of record types.");
3905 CXXRecordDecl *T2RecordDecl
3906 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3907
3908 OverloadCandidateSet CandidateSet(DeclLoc);
3909 const UnresolvedSetImpl *Conversions
3910 = T2RecordDecl->getVisibleConversionFunctions();
3911 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3912 E = Conversions->end(); I != E; ++I) {
3913 NamedDecl *D = *I;
3914 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3915 if (isa<UsingShadowDecl>(D))
3916 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3917
3918 FunctionTemplateDecl *ConvTemplate
3919 = dyn_cast<FunctionTemplateDecl>(D);
3920 CXXConversionDecl *Conv;
3921 if (ConvTemplate)
3922 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3923 else
3924 Conv = cast<CXXConversionDecl>(D);
3925
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003926 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003927 // explicit conversions, skip it.
3928 if (!AllowExplicit && Conv->isExplicit())
3929 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003930
Douglas Gregor604eb652010-08-11 02:15:33 +00003931 if (AllowRvalues) {
3932 bool DerivedToBase = false;
3933 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003934 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003935
3936 // If we are initializing an rvalue reference, don't permit conversion
3937 // functions that return lvalues.
3938 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3939 const ReferenceType *RefType
3940 = Conv->getConversionType()->getAs<LValueReferenceType>();
3941 if (RefType && !RefType->getPointeeType()->isFunctionType())
3942 continue;
3943 }
3944
Douglas Gregor604eb652010-08-11 02:15:33 +00003945 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003946 S.CompareReferenceRelationship(
3947 DeclLoc,
3948 Conv->getConversionType().getNonReferenceType()
3949 .getUnqualifiedType(),
3950 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003951 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003952 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003953 continue;
3954 } else {
3955 // If the conversion function doesn't return a reference type,
3956 // it can't be considered for this conversion. An rvalue reference
3957 // is only acceptable if its referencee is a function type.
3958
3959 const ReferenceType *RefType =
3960 Conv->getConversionType()->getAs<ReferenceType>();
3961 if (!RefType ||
3962 (!RefType->isLValueReferenceType() &&
3963 !RefType->getPointeeType()->isFunctionType()))
3964 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003965 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003966
Douglas Gregor604eb652010-08-11 02:15:33 +00003967 if (ConvTemplate)
3968 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003969 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003970 else
3971 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003972 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003973 }
3974
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003975 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3976
Sebastian Redl4680bf22010-06-30 18:13:39 +00003977 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003978 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003979 case OR_Success:
3980 // C++ [over.ics.ref]p1:
3981 //
3982 // [...] If the parameter binds directly to the result of
3983 // applying a conversion function to the argument
3984 // expression, the implicit conversion sequence is a
3985 // user-defined conversion sequence (13.3.3.1.2), with the
3986 // second standard conversion sequence either an identity
3987 // conversion or, if the conversion function returns an
3988 // entity of a type that is a derived class of the parameter
3989 // type, a derived-to-base Conversion.
3990 if (!Best->FinalConversion.DirectBinding)
3991 return false;
3992
Chandler Carruth25ca4212011-02-25 19:41:05 +00003993 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003994 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003995 ICS.setUserDefined();
3996 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3997 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003998 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003999 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004000 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004001 ICS.UserDefined.EllipsisConversion = false;
4002 assert(ICS.UserDefined.After.ReferenceBinding &&
4003 ICS.UserDefined.After.DirectBinding &&
4004 "Expected a direct reference binding!");
4005 return true;
4006
4007 case OR_Ambiguous:
4008 ICS.setAmbiguous();
4009 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4010 Cand != CandidateSet.end(); ++Cand)
4011 if (Cand->Viable)
4012 ICS.Ambiguous.addConversion(Cand->Function);
4013 return true;
4014
4015 case OR_No_Viable_Function:
4016 case OR_Deleted:
4017 // There was no suitable conversion, or we found a deleted
4018 // conversion; continue with other checks.
4019 return false;
4020 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004021
David Blaikie7530c032012-01-17 06:56:22 +00004022 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004023}
4024
Douglas Gregorabe183d2010-04-13 16:31:36 +00004025/// \brief Compute an implicit conversion sequence for reference
4026/// initialization.
4027static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004028TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004029 SourceLocation DeclLoc,
4030 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004031 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004032 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4033
4034 // Most paths end in a failed conversion.
4035 ImplicitConversionSequence ICS;
4036 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4037
4038 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4039 QualType T2 = Init->getType();
4040
4041 // If the initializer is the address of an overloaded function, try
4042 // to resolve the overloaded function. If all goes well, T2 is the
4043 // type of the resulting function.
4044 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4045 DeclAccessPair Found;
4046 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4047 false, Found))
4048 T2 = Fn->getType();
4049 }
4050
4051 // Compute some basic properties of the types and the initializer.
4052 bool isRValRef = DeclType->isRValueReferenceType();
4053 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004054 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004055 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004056 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004057 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004058 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004059 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004060
Douglas Gregorabe183d2010-04-13 16:31:36 +00004061
Sebastian Redl4680bf22010-06-30 18:13:39 +00004062 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004063 // A reference to type "cv1 T1" is initialized by an expression
4064 // of type "cv2 T2" as follows:
4065
Sebastian Redl4680bf22010-06-30 18:13:39 +00004066 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004067 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004068 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4069 // reference-compatible with "cv2 T2," or
4070 //
4071 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4072 if (InitCategory.isLValue() &&
4073 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004074 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004075 // When a parameter of reference type binds directly (8.5.3)
4076 // to an argument expression, the implicit conversion sequence
4077 // is the identity conversion, unless the argument expression
4078 // has a type that is a derived class of the parameter type,
4079 // in which case the implicit conversion sequence is a
4080 // derived-to-base Conversion (13.3.3.1).
4081 ICS.setStandard();
4082 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004083 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4084 : ObjCConversion? ICK_Compatible_Conversion
4085 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004086 ICS.Standard.Third = ICK_Identity;
4087 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4088 ICS.Standard.setToType(0, T2);
4089 ICS.Standard.setToType(1, T1);
4090 ICS.Standard.setToType(2, T1);
4091 ICS.Standard.ReferenceBinding = true;
4092 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004093 ICS.Standard.IsLvalueReference = !isRValRef;
4094 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4095 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004096 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004097 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004098 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004099
Sebastian Redl4680bf22010-06-30 18:13:39 +00004100 // Nothing more to do: the inaccessibility/ambiguity check for
4101 // derived-to-base conversions is suppressed when we're
4102 // computing the implicit conversion sequence (C++
4103 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004104 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004105 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004106
Sebastian Redl4680bf22010-06-30 18:13:39 +00004107 // -- has a class type (i.e., T2 is a class type), where T1 is
4108 // not reference-related to T2, and can be implicitly
4109 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4110 // is reference-compatible with "cv3 T3" 92) (this
4111 // conversion is selected by enumerating the applicable
4112 // conversion functions (13.3.1.6) and choosing the best
4113 // one through overload resolution (13.3)),
4114 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004115 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004116 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004117 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4118 Init, T2, /*AllowRvalues=*/false,
4119 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004120 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004121 }
4122 }
4123
Sebastian Redl4680bf22010-06-30 18:13:39 +00004124 // -- Otherwise, the reference shall be an lvalue reference to a
4125 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004126 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004127 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004128 // We actually handle one oddity of C++ [over.ics.ref] at this
4129 // point, which is that, due to p2 (which short-circuits reference
4130 // binding by only attempting a simple conversion for non-direct
4131 // bindings) and p3's strange wording, we allow a const volatile
4132 // reference to bind to an rvalue. Hence the check for the presence
4133 // of "const" rather than checking for "const" being the only
4134 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004135 // This is also the point where rvalue references and lvalue inits no longer
4136 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004137 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00004138 return ICS;
4139
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004140 // -- If the initializer expression
4141 //
4142 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004143 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004144 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4145 (InitCategory.isXValue() ||
4146 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4147 (InitCategory.isLValue() && T2->isFunctionType()))) {
4148 ICS.setStandard();
4149 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004150 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004151 : ObjCConversion? ICK_Compatible_Conversion
4152 : ICK_Identity;
4153 ICS.Standard.Third = ICK_Identity;
4154 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4155 ICS.Standard.setToType(0, T2);
4156 ICS.Standard.setToType(1, T1);
4157 ICS.Standard.setToType(2, T1);
4158 ICS.Standard.ReferenceBinding = true;
4159 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4160 // binding unless we're binding to a class prvalue.
4161 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4162 // allow the use of rvalue references in C++98/03 for the benefit of
4163 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004164 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004165 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004166 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004167 ICS.Standard.IsLvalueReference = !isRValRef;
4168 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004169 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004170 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004171 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004172 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004173 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004174 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004175
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004176 // -- has a class type (i.e., T2 is a class type), where T1 is not
4177 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004178 // an xvalue, class prvalue, or function lvalue of type
4179 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004180 // "cv3 T3",
4181 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004182 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004183 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004184 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004185 // class subobject).
4186 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004188 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4189 Init, T2, /*AllowRvalues=*/true,
4190 AllowExplicit)) {
4191 // In the second case, if the reference is an rvalue reference
4192 // and the second standard conversion sequence of the
4193 // user-defined conversion sequence includes an lvalue-to-rvalue
4194 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004195 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004196 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4197 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4198
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004199 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004201
Douglas Gregorabe183d2010-04-13 16:31:36 +00004202 // -- Otherwise, a temporary of type "cv1 T1" is created and
4203 // initialized from the initializer expression using the
4204 // rules for a non-reference copy initialization (8.5). The
4205 // reference is then bound to the temporary. If T1 is
4206 // reference-related to T2, cv1 must be the same
4207 // cv-qualification as, or greater cv-qualification than,
4208 // cv2; otherwise, the program is ill-formed.
4209 if (RefRelationship == Sema::Ref_Related) {
4210 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4211 // we would be reference-compatible or reference-compatible with
4212 // added qualification. But that wasn't the case, so the reference
4213 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004214 //
4215 // Note that we only want to check address spaces and cvr-qualifiers here.
4216 // ObjC GC and lifetime qualifiers aren't important.
4217 Qualifiers T1Quals = T1.getQualifiers();
4218 Qualifiers T2Quals = T2.getQualifiers();
4219 T1Quals.removeObjCGCAttr();
4220 T1Quals.removeObjCLifetime();
4221 T2Quals.removeObjCGCAttr();
4222 T2Quals.removeObjCLifetime();
4223 if (!T1Quals.compatiblyIncludes(T2Quals))
4224 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004225 }
4226
4227 // If at least one of the types is a class type, the types are not
4228 // related, and we aren't allowed any user conversions, the
4229 // reference binding fails. This case is important for breaking
4230 // recursion, since TryImplicitConversion below will attempt to
4231 // create a temporary through the use of a copy constructor.
4232 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4233 (T1->isRecordType() || T2->isRecordType()))
4234 return ICS;
4235
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004236 // If T1 is reference-related to T2 and the reference is an rvalue
4237 // reference, the initializer expression shall not be an lvalue.
4238 if (RefRelationship >= Sema::Ref_Related &&
4239 isRValRef && Init->Classify(S.Context).isLValue())
4240 return ICS;
4241
Douglas Gregorabe183d2010-04-13 16:31:36 +00004242 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004243 // When a parameter of reference type is not bound directly to
4244 // an argument expression, the conversion sequence is the one
4245 // required to convert the argument expression to the
4246 // underlying type of the reference according to
4247 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4248 // to copy-initializing a temporary of the underlying type with
4249 // the argument expression. Any difference in top-level
4250 // cv-qualification is subsumed by the initialization itself
4251 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004252 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4253 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004254 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004255 /*CStyle=*/false,
4256 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004257
4258 // Of course, that's still a reference binding.
4259 if (ICS.isStandard()) {
4260 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004261 ICS.Standard.IsLvalueReference = !isRValRef;
4262 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4263 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004264 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004265 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004266 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004267 // Don't allow rvalue references to bind to lvalues.
4268 if (DeclType->isRValueReferenceType()) {
4269 if (const ReferenceType *RefType
4270 = ICS.UserDefined.ConversionFunction->getResultType()
4271 ->getAs<LValueReferenceType>()) {
4272 if (!RefType->getPointeeType()->isFunctionType()) {
4273 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4274 DeclType);
4275 return ICS;
4276 }
4277 }
4278 }
4279
Douglas Gregorabe183d2010-04-13 16:31:36 +00004280 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004281 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4282 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4283 ICS.UserDefined.After.BindsToRvalue = true;
4284 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4285 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004286 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004287
Douglas Gregorabe183d2010-04-13 16:31:36 +00004288 return ICS;
4289}
4290
Sebastian Redl5405b812011-10-16 18:19:34 +00004291static ImplicitConversionSequence
4292TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4293 bool SuppressUserConversions,
4294 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004295 bool AllowObjCWritebackConversion,
4296 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004297
4298/// TryListConversion - Try to copy-initialize a value of type ToType from the
4299/// initializer list From.
4300static ImplicitConversionSequence
4301TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4302 bool SuppressUserConversions,
4303 bool InOverloadResolution,
4304 bool AllowObjCWritebackConversion) {
4305 // C++11 [over.ics.list]p1:
4306 // When an argument is an initializer list, it is not an expression and
4307 // special rules apply for converting it to a parameter type.
4308
4309 ImplicitConversionSequence Result;
4310 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004311 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004312
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004313 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004314 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004315 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004316 return Result;
4317
Sebastian Redl5405b812011-10-16 18:19:34 +00004318 // C++11 [over.ics.list]p2:
4319 // If the parameter type is std::initializer_list<X> or "array of X" and
4320 // all the elements can be implicitly converted to X, the implicit
4321 // conversion sequence is the worst conversion necessary to convert an
4322 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004323 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004324 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004325 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004326 X = S.Context.getBaseElementType(ToType);
4327 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004328 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004329 if (!X.isNull()) {
4330 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4331 Expr *Init = From->getInit(i);
4332 ImplicitConversionSequence ICS =
4333 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4334 InOverloadResolution,
4335 AllowObjCWritebackConversion);
4336 // If a single element isn't convertible, fail.
4337 if (ICS.isBad()) {
4338 Result = ICS;
4339 break;
4340 }
4341 // Otherwise, look for the worst conversion.
4342 if (Result.isBad() ||
4343 CompareImplicitConversionSequences(S, ICS, Result) ==
4344 ImplicitConversionSequence::Worse)
4345 Result = ICS;
4346 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004347
4348 // For an empty list, we won't have computed any conversion sequence.
4349 // Introduce the identity conversion sequence.
4350 if (From->getNumInits() == 0) {
4351 Result.setStandard();
4352 Result.Standard.setAsIdentityConversion();
4353 Result.Standard.setFromType(ToType);
4354 Result.Standard.setAllToTypes(ToType);
4355 }
4356
Sebastian Redlfe592282012-01-17 22:49:48 +00004357 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004358 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004359 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004360 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004361
4362 // C++11 [over.ics.list]p3:
4363 // Otherwise, if the parameter is a non-aggregate class X and overload
4364 // resolution chooses a single best constructor [...] the implicit
4365 // conversion sequence is a user-defined conversion sequence. If multiple
4366 // constructors are viable but none is better than the others, the
4367 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004368 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4369 // This function can deal with initializer lists.
4370 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4371 /*AllowExplicit=*/false,
4372 InOverloadResolution, /*CStyle=*/false,
4373 AllowObjCWritebackConversion);
4374 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004375 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004376 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004377
4378 // C++11 [over.ics.list]p4:
4379 // Otherwise, if the parameter has an aggregate type which can be
4380 // initialized from the initializer list [...] the implicit conversion
4381 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004382 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004383 // Type is an aggregate, argument is an init list. At this point it comes
4384 // down to checking whether the initialization works.
4385 // FIXME: Find out whether this parameter is consumed or not.
4386 InitializedEntity Entity =
4387 InitializedEntity::InitializeParameter(S.Context, ToType,
4388 /*Consumed=*/false);
4389 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4390 Result.setUserDefined();
4391 Result.UserDefined.Before.setAsIdentityConversion();
4392 // Initializer lists don't have a type.
4393 Result.UserDefined.Before.setFromType(QualType());
4394 Result.UserDefined.Before.setAllToTypes(QualType());
4395
4396 Result.UserDefined.After.setAsIdentityConversion();
4397 Result.UserDefined.After.setFromType(ToType);
4398 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004399 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004400 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004401 return Result;
4402 }
4403
4404 // C++11 [over.ics.list]p5:
4405 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004406 if (ToType->isReferenceType()) {
4407 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4408 // mention initializer lists in any way. So we go by what list-
4409 // initialization would do and try to extrapolate from that.
4410
4411 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4412
4413 // If the initializer list has a single element that is reference-related
4414 // to the parameter type, we initialize the reference from that.
4415 if (From->getNumInits() == 1) {
4416 Expr *Init = From->getInit(0);
4417
4418 QualType T2 = Init->getType();
4419
4420 // If the initializer is the address of an overloaded function, try
4421 // to resolve the overloaded function. If all goes well, T2 is the
4422 // type of the resulting function.
4423 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4424 DeclAccessPair Found;
4425 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4426 Init, ToType, false, Found))
4427 T2 = Fn->getType();
4428 }
4429
4430 // Compute some basic properties of the types and the initializer.
4431 bool dummy1 = false;
4432 bool dummy2 = false;
4433 bool dummy3 = false;
4434 Sema::ReferenceCompareResult RefRelationship
4435 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4436 dummy2, dummy3);
4437
4438 if (RefRelationship >= Sema::Ref_Related)
4439 return TryReferenceInit(S, Init, ToType,
4440 /*FIXME:*/From->getLocStart(),
4441 SuppressUserConversions,
4442 /*AllowExplicit=*/false);
4443 }
4444
4445 // Otherwise, we bind the reference to a temporary created from the
4446 // initializer list.
4447 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4448 InOverloadResolution,
4449 AllowObjCWritebackConversion);
4450 if (Result.isFailure())
4451 return Result;
4452 assert(!Result.isEllipsis() &&
4453 "Sub-initialization cannot result in ellipsis conversion.");
4454
4455 // Can we even bind to a temporary?
4456 if (ToType->isRValueReferenceType() ||
4457 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4458 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4459 Result.UserDefined.After;
4460 SCS.ReferenceBinding = true;
4461 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4462 SCS.BindsToRvalue = true;
4463 SCS.BindsToFunctionLvalue = false;
4464 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4465 SCS.ObjCLifetimeConversionBinding = false;
4466 } else
4467 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4468 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004469 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004470 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004471
4472 // C++11 [over.ics.list]p6:
4473 // Otherwise, if the parameter type is not a class:
4474 if (!ToType->isRecordType()) {
4475 // - if the initializer list has one element, the implicit conversion
4476 // sequence is the one required to convert the element to the
4477 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004478 unsigned NumInits = From->getNumInits();
4479 if (NumInits == 1)
4480 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4481 SuppressUserConversions,
4482 InOverloadResolution,
4483 AllowObjCWritebackConversion);
4484 // - if the initializer list has no elements, the implicit conversion
4485 // sequence is the identity conversion.
4486 else if (NumInits == 0) {
4487 Result.setStandard();
4488 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004489 Result.Standard.setFromType(ToType);
4490 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004491 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004492 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004493 return Result;
4494 }
4495
4496 // C++11 [over.ics.list]p7:
4497 // In all cases other than those enumerated above, no conversion is possible
4498 return Result;
4499}
4500
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004501/// TryCopyInitialization - Try to copy-initialize a value of type
4502/// ToType from the expression From. Return the implicit conversion
4503/// sequence required to pass this argument, which may be a bad
4504/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004505/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004506/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004507static ImplicitConversionSequence
4508TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004509 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004510 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004511 bool AllowObjCWritebackConversion,
4512 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004513 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4514 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4515 InOverloadResolution,AllowObjCWritebackConversion);
4516
Douglas Gregorabe183d2010-04-13 16:31:36 +00004517 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004518 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004519 /*FIXME:*/From->getLocStart(),
4520 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004521 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004522
John McCall120d63c2010-08-24 20:38:10 +00004523 return TryImplicitConversion(S, From, ToType,
4524 SuppressUserConversions,
4525 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004526 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004527 /*CStyle=*/false,
4528 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004529}
4530
Anna Zaksf3546ee2011-07-28 19:46:48 +00004531static bool TryCopyInitialization(const CanQualType FromQTy,
4532 const CanQualType ToQTy,
4533 Sema &S,
4534 SourceLocation Loc,
4535 ExprValueKind FromVK) {
4536 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4537 ImplicitConversionSequence ICS =
4538 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4539
4540 return !ICS.isBad();
4541}
4542
Douglas Gregor96176b32008-11-18 23:14:02 +00004543/// TryObjectArgumentInitialization - Try to initialize the object
4544/// parameter of the given member function (@c Method) from the
4545/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004546static ImplicitConversionSequence
4547TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004548 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004549 CXXMethodDecl *Method,
4550 CXXRecordDecl *ActingContext) {
4551 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004552 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4553 // const volatile object.
4554 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4555 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004556 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004557
4558 // Set up the conversion sequence as a "bad" conversion, to allow us
4559 // to exit early.
4560 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004561
4562 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004563 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004564 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004565 FromType = PT->getPointeeType();
4566
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004567 // When we had a pointer, it's implicitly dereferenced, so we
4568 // better have an lvalue.
4569 assert(FromClassification.isLValue());
4570 }
4571
Anders Carlssona552f7c2009-05-01 18:34:30 +00004572 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004573
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004574 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004575 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004576 // parameter is
4577 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004578 // - "lvalue reference to cv X" for functions declared without a
4579 // ref-qualifier or with the & ref-qualifier
4580 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004581 // ref-qualifier
4582 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004583 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004584 // cv-qualification on the member function declaration.
4585 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004586 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004587 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004588 // (C++ [over.match.funcs]p5). We perform a simplified version of
4589 // reference binding here, that allows class rvalues to bind to
4590 // non-constant references.
4591
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004592 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004593 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004594 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004595 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004596 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004597 ICS.setBad(BadConversionSequence::bad_qualifiers,
4598 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004599 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004600 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004601
4602 // Check that we have either the same type or a derived type. It
4603 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004604 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004605 ImplicitConversionKind SecondKind;
4606 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4607 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004608 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004609 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004610 else {
John McCallb1bdc622010-02-25 01:37:24 +00004611 ICS.setBad(BadConversionSequence::unrelated_class,
4612 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004613 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004614 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004615
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004616 // Check the ref-qualifier.
4617 switch (Method->getRefQualifier()) {
4618 case RQ_None:
4619 // Do nothing; we don't care about lvalueness or rvalueness.
4620 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004621
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004622 case RQ_LValue:
4623 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4624 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004625 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004626 ImplicitParamType);
4627 return ICS;
4628 }
4629 break;
4630
4631 case RQ_RValue:
4632 if (!FromClassification.isRValue()) {
4633 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004634 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004635 ImplicitParamType);
4636 return ICS;
4637 }
4638 break;
4639 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640
Douglas Gregor96176b32008-11-18 23:14:02 +00004641 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004642 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004643 ICS.Standard.setAsIdentityConversion();
4644 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004645 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004646 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004647 ICS.Standard.ReferenceBinding = true;
4648 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004649 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004650 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004651 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4652 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4653 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004654 return ICS;
4655}
4656
4657/// PerformObjectArgumentInitialization - Perform initialization of
4658/// the implicit object parameter for the given Method with the given
4659/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004660ExprResult
4661Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004662 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004663 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004664 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004665 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004666 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004667 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004668
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004669 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004670 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004671 FromRecordType = PT->getPointeeType();
4672 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004673 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004674 } else {
4675 FromRecordType = From->getType();
4676 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004677 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004678 }
4679
John McCall701c89e2009-12-03 04:06:58 +00004680 // Note that we always use the true parent context when performing
4681 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004682 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004683 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4684 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004685 if (ICS.isBad()) {
4686 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4687 Qualifiers FromQs = FromRecordType.getQualifiers();
4688 Qualifiers ToQs = DestType.getQualifiers();
4689 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4690 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004691 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004692 diag::err_member_function_call_bad_cvr)
4693 << Method->getDeclName() << FromRecordType << (CVR - 1)
4694 << From->getSourceRange();
4695 Diag(Method->getLocation(), diag::note_previous_decl)
4696 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004697 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004698 }
4699 }
4700
Daniel Dunbar96a00142012-03-09 18:35:03 +00004701 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004702 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004703 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004704 }
Mike Stump1eb44332009-09-09 15:08:12 +00004705
John Wiegley429bb272011-04-08 18:41:53 +00004706 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4707 ExprResult FromRes =
4708 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4709 if (FromRes.isInvalid())
4710 return ExprError();
4711 From = FromRes.take();
4712 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004713
Douglas Gregor5fccd362010-03-03 23:55:11 +00004714 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004715 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004716 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004717 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004718}
4719
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004720/// TryContextuallyConvertToBool - Attempt to contextually convert the
4721/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004722static ImplicitConversionSequence
4723TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004724 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004725 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004726 // FIXME: Are these flags correct?
4727 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004728 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004729 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004730 /*CStyle=*/false,
4731 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004732}
4733
4734/// PerformContextuallyConvertToBool - Perform a contextual conversion
4735/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004736ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004737 if (checkPlaceholderForOverload(*this, From))
4738 return ExprError();
4739
John McCall120d63c2010-08-24 20:38:10 +00004740 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004741 if (!ICS.isBad())
4742 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004743
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004744 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004745 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004746 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004747 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004748 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004749}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004750
Richard Smith8ef7b202012-01-18 23:55:52 +00004751/// Check that the specified conversion is permitted in a converted constant
4752/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4753/// is acceptable.
4754static bool CheckConvertedConstantConversions(Sema &S,
4755 StandardConversionSequence &SCS) {
4756 // Since we know that the target type is an integral or unscoped enumeration
4757 // type, most conversion kinds are impossible. All possible First and Third
4758 // conversions are fine.
4759 switch (SCS.Second) {
4760 case ICK_Identity:
4761 case ICK_Integral_Promotion:
4762 case ICK_Integral_Conversion:
4763 return true;
4764
4765 case ICK_Boolean_Conversion:
4766 // Conversion from an integral or unscoped enumeration type to bool is
4767 // classified as ICK_Boolean_Conversion, but it's also an integral
4768 // conversion, so it's permitted in a converted constant expression.
4769 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4770 SCS.getToType(2)->isBooleanType();
4771
4772 case ICK_Floating_Integral:
4773 case ICK_Complex_Real:
4774 return false;
4775
4776 case ICK_Lvalue_To_Rvalue:
4777 case ICK_Array_To_Pointer:
4778 case ICK_Function_To_Pointer:
4779 case ICK_NoReturn_Adjustment:
4780 case ICK_Qualification:
4781 case ICK_Compatible_Conversion:
4782 case ICK_Vector_Conversion:
4783 case ICK_Vector_Splat:
4784 case ICK_Derived_To_Base:
4785 case ICK_Pointer_Conversion:
4786 case ICK_Pointer_Member:
4787 case ICK_Block_Pointer_Conversion:
4788 case ICK_Writeback_Conversion:
4789 case ICK_Floating_Promotion:
4790 case ICK_Complex_Promotion:
4791 case ICK_Complex_Conversion:
4792 case ICK_Floating_Conversion:
4793 case ICK_TransparentUnionConversion:
4794 llvm_unreachable("unexpected second conversion kind");
4795
4796 case ICK_Num_Conversion_Kinds:
4797 break;
4798 }
4799
4800 llvm_unreachable("unknown conversion kind");
4801}
4802
4803/// CheckConvertedConstantExpression - Check that the expression From is a
4804/// converted constant expression of type T, perform the conversion and produce
4805/// the converted expression, per C++11 [expr.const]p3.
4806ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4807 llvm::APSInt &Value,
4808 CCEKind CCE) {
4809 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4810 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4811
4812 if (checkPlaceholderForOverload(*this, From))
4813 return ExprError();
4814
4815 // C++11 [expr.const]p3 with proposed wording fixes:
4816 // A converted constant expression of type T is a core constant expression,
4817 // implicitly converted to a prvalue of type T, where the converted
4818 // expression is a literal constant expression and the implicit conversion
4819 // sequence contains only user-defined conversions, lvalue-to-rvalue
4820 // conversions, integral promotions, and integral conversions other than
4821 // narrowing conversions.
4822 ImplicitConversionSequence ICS =
4823 TryImplicitConversion(From, T,
4824 /*SuppressUserConversions=*/false,
4825 /*AllowExplicit=*/false,
4826 /*InOverloadResolution=*/false,
4827 /*CStyle=*/false,
4828 /*AllowObjcWritebackConversion=*/false);
4829 StandardConversionSequence *SCS = 0;
4830 switch (ICS.getKind()) {
4831 case ImplicitConversionSequence::StandardConversion:
4832 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004833 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004834 diag::err_typecheck_converted_constant_expression_disallowed)
4835 << From->getType() << From->getSourceRange() << T;
4836 SCS = &ICS.Standard;
4837 break;
4838 case ImplicitConversionSequence::UserDefinedConversion:
4839 // We are converting from class type to an integral or enumeration type, so
4840 // the Before sequence must be trivial.
4841 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004842 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004843 diag::err_typecheck_converted_constant_expression_disallowed)
4844 << From->getType() << From->getSourceRange() << T;
4845 SCS = &ICS.UserDefined.After;
4846 break;
4847 case ImplicitConversionSequence::AmbiguousConversion:
4848 case ImplicitConversionSequence::BadConversion:
4849 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004850 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004851 diag::err_typecheck_converted_constant_expression)
4852 << From->getType() << From->getSourceRange() << T;
4853 return ExprError();
4854
4855 case ImplicitConversionSequence::EllipsisConversion:
4856 llvm_unreachable("ellipsis conversion in converted constant expression");
4857 }
4858
4859 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4860 if (Result.isInvalid())
4861 return Result;
4862
4863 // Check for a narrowing implicit conversion.
4864 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004865 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004866 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4867 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004868 case NK_Variable_Narrowing:
4869 // Implicit conversion to a narrower type, and the value is not a constant
4870 // expression. We'll diagnose this in a moment.
4871 case NK_Not_Narrowing:
4872 break;
4873
4874 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004875 Diag(From->getLocStart(),
4876 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4877 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004878 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004879 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004880 break;
4881
4882 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004883 Diag(From->getLocStart(),
4884 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4885 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004886 << CCE << /*Constant*/0 << From->getType() << T;
4887 break;
4888 }
4889
4890 // Check the expression is a constant expression.
4891 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4892 Expr::EvalResult Eval;
4893 Eval.Diag = &Notes;
4894
4895 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4896 // The expression can't be folded, so we can't keep it at this position in
4897 // the AST.
4898 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004899 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004900 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004901
4902 if (Notes.empty()) {
4903 // It's a constant expression.
4904 return Result;
4905 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004906 }
4907
4908 // It's not a constant expression. Produce an appropriate diagnostic.
4909 if (Notes.size() == 1 &&
4910 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4911 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4912 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004913 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004914 << CCE << From->getSourceRange();
4915 for (unsigned I = 0; I < Notes.size(); ++I)
4916 Diag(Notes[I].first, Notes[I].second);
4917 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004918 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004919}
4920
John McCall0bcc9bc2011-09-09 06:11:02 +00004921/// dropPointerConversions - If the given standard conversion sequence
4922/// involves any pointer conversions, remove them. This may change
4923/// the result type of the conversion sequence.
4924static void dropPointerConversion(StandardConversionSequence &SCS) {
4925 if (SCS.Second == ICK_Pointer_Conversion) {
4926 SCS.Second = ICK_Identity;
4927 SCS.Third = ICK_Identity;
4928 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4929 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004930}
John McCall120d63c2010-08-24 20:38:10 +00004931
John McCall0bcc9bc2011-09-09 06:11:02 +00004932/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4933/// convert the expression From to an Objective-C pointer type.
4934static ImplicitConversionSequence
4935TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4936 // Do an implicit conversion to 'id'.
4937 QualType Ty = S.Context.getObjCIdType();
4938 ImplicitConversionSequence ICS
4939 = TryImplicitConversion(S, From, Ty,
4940 // FIXME: Are these flags correct?
4941 /*SuppressUserConversions=*/false,
4942 /*AllowExplicit=*/true,
4943 /*InOverloadResolution=*/false,
4944 /*CStyle=*/false,
4945 /*AllowObjCWritebackConversion=*/false);
4946
4947 // Strip off any final conversions to 'id'.
4948 switch (ICS.getKind()) {
4949 case ImplicitConversionSequence::BadConversion:
4950 case ImplicitConversionSequence::AmbiguousConversion:
4951 case ImplicitConversionSequence::EllipsisConversion:
4952 break;
4953
4954 case ImplicitConversionSequence::UserDefinedConversion:
4955 dropPointerConversion(ICS.UserDefined.After);
4956 break;
4957
4958 case ImplicitConversionSequence::StandardConversion:
4959 dropPointerConversion(ICS.Standard);
4960 break;
4961 }
4962
4963 return ICS;
4964}
4965
4966/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4967/// conversion of the expression From to an Objective-C pointer type.
4968ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004969 if (checkPlaceholderForOverload(*this, From))
4970 return ExprError();
4971
John McCallc12c5bb2010-05-15 11:32:37 +00004972 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004973 ImplicitConversionSequence ICS =
4974 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004975 if (!ICS.isBad())
4976 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004977 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004978}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004979
Richard Smithf39aec12012-02-04 07:07:42 +00004980/// Determine whether the provided type is an integral type, or an enumeration
4981/// type of a permitted flavor.
4982static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4983 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4984 : T->isIntegralOrUnscopedEnumerationType();
4985}
4986
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004987/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004988/// enumeration type.
4989///
4990/// This routine will attempt to convert an expression of class type to an
4991/// integral or enumeration type, if that class type only has a single
4992/// conversion to an integral or enumeration type.
4993///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004994/// \param Loc The source location of the construct that requires the
4995/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004996///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004997/// \param FromE The expression we're converting from.
4998///
4999/// \param NotIntDiag The diagnostic to be emitted if the expression does not
5000/// have integral or enumeration type.
5001///
5002/// \param IncompleteDiag The diagnostic to be emitted if the expression has
5003/// incomplete class type.
5004///
5005/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
5006/// explicit conversion function (because no implicit conversion functions
5007/// were available). This is a recovery mode.
5008///
5009/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
5010/// showing which conversion was picked.
5011///
5012/// \param AmbigDiag The diagnostic to be emitted if there is more than one
5013/// conversion function that could convert to integral or enumeration type.
5014///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005015/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005016/// usable conversion function.
5017///
5018/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
5019/// function, which may be an extension in this case.
5020///
Richard Smithf39aec12012-02-04 07:07:42 +00005021/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5022/// enumerations should be considered.
5023///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005024/// \returns The expression, converted to an integral or enumeration type if
5025/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005026ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005027Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005028 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005029 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005030 // We can't perform any more checking for type-dependent expressions.
5031 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005032 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005033
Eli Friedmanceccab92012-01-26 00:26:18 +00005034 // Process placeholders immediately.
5035 if (From->hasPlaceholderType()) {
5036 ExprResult result = CheckPlaceholderExpr(From);
5037 if (result.isInvalid()) return result;
5038 From = result.take();
5039 }
5040
Douglas Gregorc30614b2010-06-29 23:17:37 +00005041 // If the expression already has integral or enumeration type, we're golden.
5042 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005043 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005044 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005045
5046 // FIXME: Check for missing '()' if T is a function type?
5047
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005048 // 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 +00005049 // expression of integral or enumeration type.
5050 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005051 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005052 if (!Diagnoser.Suppress)
5053 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005054 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005055 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005056
Douglas Gregorc30614b2010-06-29 23:17:37 +00005057 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005058 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005059 ICEConvertDiagnoser &Diagnoser;
5060 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005061
Douglas Gregorab41fe92012-05-04 22:38:52 +00005062 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5063 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005064
5065 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005066 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005067 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005068 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005069
5070 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005071 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005072
Douglas Gregorc30614b2010-06-29 23:17:37 +00005073 // Look for a conversion to an integral or enumeration type.
5074 UnresolvedSet<4> ViableConversions;
5075 UnresolvedSet<4> ExplicitConversions;
5076 const UnresolvedSetImpl *Conversions
5077 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005078
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005079 bool HadMultipleCandidates = (Conversions->size() > 1);
5080
Douglas Gregorc30614b2010-06-29 23:17:37 +00005081 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082 E = Conversions->end();
5083 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005084 ++I) {
5085 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005086 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5087 if (isIntegralOrEnumerationType(
5088 Conversion->getConversionType().getNonReferenceType(),
5089 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005090 if (Conversion->isExplicit())
5091 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5092 else
5093 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5094 }
Richard Smithf39aec12012-02-04 07:07:42 +00005095 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005096 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005097
Douglas Gregorc30614b2010-06-29 23:17:37 +00005098 switch (ViableConversions.size()) {
5099 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005100 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005101 DeclAccessPair Found = ExplicitConversions[0];
5102 CXXConversionDecl *Conversion
5103 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005104
Douglas Gregorc30614b2010-06-29 23:17:37 +00005105 // The user probably meant to invoke the given explicit
5106 // conversion; use it.
5107 QualType ConvTy
5108 = Conversion->getConversionType().getNonReferenceType();
5109 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005110 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005111
Douglas Gregorab41fe92012-05-04 22:38:52 +00005112 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005113 << FixItHint::CreateInsertion(From->getLocStart(),
5114 "static_cast<" + TypeStr + ">(")
5115 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5116 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005117 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005118
5119 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005120 // explicit conversion function.
5121 if (isSFINAEContext())
5122 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005123
Douglas Gregorc30614b2010-06-29 23:17:37 +00005124 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005125 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5126 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005127 if (Result.isInvalid())
5128 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005129 // Record usage of conversion in an implicit cast.
5130 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5131 CK_UserDefinedConversion,
5132 Result.get(), 0,
5133 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005134 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005135
Douglas Gregorc30614b2010-06-29 23:17:37 +00005136 // We'll complain below about a non-integral condition type.
5137 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005138
Douglas Gregorc30614b2010-06-29 23:17:37 +00005139 case 1: {
5140 // Apply this conversion.
5141 DeclAccessPair Found = ViableConversions[0];
5142 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005143
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005144 CXXConversionDecl *Conversion
5145 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5146 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005147 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005148 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005149 if (isSFINAEContext())
5150 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005151
Douglas Gregorab41fe92012-05-04 22:38:52 +00005152 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5153 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005154 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005155
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005156 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5157 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005158 if (Result.isInvalid())
5159 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005160 // Record usage of conversion in an implicit cast.
5161 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5162 CK_UserDefinedConversion,
5163 Result.get(), 0,
5164 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005165 break;
5166 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005167
Douglas Gregorc30614b2010-06-29 23:17:37 +00005168 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005169 if (Diagnoser.Suppress)
5170 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005171
Douglas Gregorab41fe92012-05-04 22:38:52 +00005172 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005173 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5174 CXXConversionDecl *Conv
5175 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5176 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005177 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005178 }
John McCall9ae2f072010-08-23 23:25:46 +00005179 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005180 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005181
Richard Smith282e7e62012-02-04 09:53:13 +00005182 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005183 !Diagnoser.Suppress) {
5184 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5185 << From->getSourceRange();
5186 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005187
Eli Friedmanceccab92012-01-26 00:26:18 +00005188 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005189}
5190
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005191/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005192/// candidate functions, using the given function call arguments. If
5193/// @p SuppressUserConversions, then don't allow user-defined
5194/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005195///
5196/// \para PartialOverloading true if we are performing "partial" overloading
5197/// based on an incomplete set of function arguments. This feature is used by
5198/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005199void
5200Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005201 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005202 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005203 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005204 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005205 bool PartialOverloading,
5206 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005207 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005208 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005209 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005210 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005211 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005212
Douglas Gregor88a35142008-12-22 05:46:06 +00005213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005214 if (!isa<CXXConstructorDecl>(Method)) {
5215 // If we get here, it's because we're calling a member function
5216 // that is named without a member access expression (e.g.,
5217 // "this->f") that was either written explicitly or created
5218 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005219 // function, e.g., X::f(). We use an empty type for the implied
5220 // object argument (C++ [over.call.func]p3), and the acting context
5221 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005222 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005223 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005224 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005225 return;
5226 }
5227 // We treat a constructor like a non-member function, since its object
5228 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005229 }
5230
Douglas Gregorfd476482009-11-13 23:59:09 +00005231 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005232 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005233
Douglas Gregor7edfb692009-11-23 12:27:39 +00005234 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005235 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005236
Douglas Gregor66724ea2009-11-14 01:20:54 +00005237 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5238 // C++ [class.copy]p3:
5239 // A member function template is never instantiated to perform the copy
5240 // of a class object to an object of its class type.
5241 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005242 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005243 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005244 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5245 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005246 return;
5247 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005248
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005249 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005250 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005251 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005252 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005253 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005254 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005255 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005256 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005257
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005258 unsigned NumArgsInProto = Proto->getNumArgs();
5259
5260 // (C++ 13.3.2p2): A candidate function having fewer than m
5261 // parameters is viable only if it has an ellipsis in its parameter
5262 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005263 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005264 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005265 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005266 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005267 return;
5268 }
5269
5270 // (C++ 13.3.2p2): A candidate function having more than m parameters
5271 // is viable only if the (m+1)st parameter has a default argument
5272 // (8.3.6). For the purposes of overload resolution, the
5273 // parameter list is truncated on the right, so that there are
5274 // exactly m parameters.
5275 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005276 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005277 // Not enough arguments.
5278 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005279 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005280 return;
5281 }
5282
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005283 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005284 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005285 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5286 if (CheckCUDATarget(Caller, Function)) {
5287 Candidate.Viable = false;
5288 Candidate.FailureKind = ovl_fail_bad_target;
5289 return;
5290 }
5291
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005292 // Determine the implicit conversion sequences for each of the
5293 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005294 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005295 if (ArgIdx < NumArgsInProto) {
5296 // (C++ 13.3.2p3): for F to be a viable function, there shall
5297 // exist for each argument an implicit conversion sequence
5298 // (13.3.3.1) that converts that argument to the corresponding
5299 // parameter of F.
5300 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005301 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005302 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005303 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005304 /*InOverloadResolution=*/true,
5305 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005306 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005307 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005308 if (Candidate.Conversions[ArgIdx].isBad()) {
5309 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005310 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005311 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005312 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005313 } else {
5314 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5315 // argument for which there is no corresponding parameter is
5316 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005317 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005318 }
5319 }
5320}
5321
Douglas Gregor063daf62009-03-13 18:40:31 +00005322/// \brief Add all of the function declarations in the given function set to
5323/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005324void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005325 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005326 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005327 bool SuppressUserConversions,
5328 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005329 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005330 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5331 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005332 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005333 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005334 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005335 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005336 Args.slice(1), CandidateSet,
5337 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005338 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005339 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005340 SuppressUserConversions);
5341 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005342 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005343 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5344 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005345 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005346 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005347 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005348 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005349 Args[0]->Classify(Context), Args.slice(1),
5350 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005351 else
John McCall9aa472c2010-03-19 07:35:19 +00005352 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005353 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005354 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005355 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005356 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005357}
5358
John McCall314be4e2009-11-17 07:50:12 +00005359/// AddMethodCandidate - Adds a named decl (which is some kind of
5360/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005361void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005362 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005363 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005364 Expr **Args, unsigned NumArgs,
5365 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005366 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005367 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005368 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005369
5370 if (isa<UsingShadowDecl>(Decl))
5371 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005372
John McCall314be4e2009-11-17 07:50:12 +00005373 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5374 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5375 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005376 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5377 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005378 ObjectType, ObjectClassification,
5379 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005380 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005381 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005382 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005383 ObjectType, ObjectClassification,
5384 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005385 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005386 }
5387}
5388
Douglas Gregor96176b32008-11-18 23:14:02 +00005389/// AddMethodCandidate - Adds the given C++ member function to the set
5390/// of candidate functions, using the given function call arguments
5391/// and the object argument (@c Object). For example, in a call
5392/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5393/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5394/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005395/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005396void
John McCall9aa472c2010-03-19 07:35:19 +00005397Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005398 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005399 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005400 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005401 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005402 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005403 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005404 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005405 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005406 assert(!isa<CXXConstructorDecl>(Method) &&
5407 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005408
Douglas Gregor3f396022009-09-28 04:47:19 +00005409 if (!CandidateSet.isNewCandidate(Method))
5410 return;
5411
Douglas Gregor7edfb692009-11-23 12:27:39 +00005412 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005413 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005414
Douglas Gregor96176b32008-11-18 23:14:02 +00005415 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005416 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005417 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005418 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005419 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005420 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005421 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005422
5423 unsigned NumArgsInProto = Proto->getNumArgs();
5424
5425 // (C++ 13.3.2p2): A candidate function having fewer than m
5426 // parameters is viable only if it has an ellipsis in its parameter
5427 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005428 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005429 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005430 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005431 return;
5432 }
5433
5434 // (C++ 13.3.2p2): A candidate function having more than m parameters
5435 // is viable only if the (m+1)st parameter has a default argument
5436 // (8.3.6). For the purposes of overload resolution, the
5437 // parameter list is truncated on the right, so that there are
5438 // exactly m parameters.
5439 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005440 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005441 // Not enough arguments.
5442 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005443 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005444 return;
5445 }
5446
5447 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005448
John McCall701c89e2009-12-03 04:06:58 +00005449 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005450 // The implicit object argument is ignored.
5451 Candidate.IgnoreObjectArgument = true;
5452 else {
5453 // Determine the implicit conversion sequence for the object
5454 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005455 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005456 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5457 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005458 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005459 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005460 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005461 return;
5462 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005463 }
5464
5465 // Determine the implicit conversion sequences for each of the
5466 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005467 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005468 if (ArgIdx < NumArgsInProto) {
5469 // (C++ 13.3.2p3): for F to be a viable function, there shall
5470 // exist for each argument an implicit conversion sequence
5471 // (13.3.3.1) that converts that argument to the corresponding
5472 // parameter of F.
5473 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005474 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005475 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005476 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005477 /*InOverloadResolution=*/true,
5478 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005479 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005480 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005481 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005482 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005483 break;
5484 }
5485 } else {
5486 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5487 // argument for which there is no corresponding parameter is
5488 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005489 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005490 }
5491 }
5492}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005493
Douglas Gregor6b906862009-08-21 00:16:32 +00005494/// \brief Add a C++ member function template as a candidate to the candidate
5495/// set, using template argument deduction to produce an appropriate member
5496/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005497void
Douglas Gregor6b906862009-08-21 00:16:32 +00005498Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005499 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005500 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005501 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005502 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005503 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005504 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005505 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005506 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005507 if (!CandidateSet.isNewCandidate(MethodTmpl))
5508 return;
5509
Douglas Gregor6b906862009-08-21 00:16:32 +00005510 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005511 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005512 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005513 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005514 // candidate functions in the usual way.113) A given name can refer to one
5515 // or more function templates and also to a set of overloaded non-template
5516 // functions. In such a case, the candidate functions generated from each
5517 // function template are combined with the set of non-template candidate
5518 // functions.
John McCall5769d612010-02-08 23:07:23 +00005519 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005520 FunctionDecl *Specialization = 0;
5521 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005522 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5523 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005524 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005525 Candidate.FoundDecl = FoundDecl;
5526 Candidate.Function = MethodTmpl->getTemplatedDecl();
5527 Candidate.Viable = false;
5528 Candidate.FailureKind = ovl_fail_bad_deduction;
5529 Candidate.IsSurrogate = false;
5530 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005531 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005532 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005533 Info);
5534 return;
5535 }
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Douglas Gregor6b906862009-08-21 00:16:32 +00005537 // Add the function template specialization produced by template argument
5538 // deduction as a candidate.
5539 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005540 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005541 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005542 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005543 ActingContext, ObjectType, ObjectClassification, Args,
5544 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005545}
5546
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005547/// \brief Add a C++ function template specialization as a candidate
5548/// in the candidate set, using template argument deduction to produce
5549/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005550void
Douglas Gregore53060f2009-06-25 22:08:12 +00005551Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005552 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005553 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005554 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005555 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005556 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005557 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5558 return;
5559
Douglas Gregore53060f2009-06-25 22:08:12 +00005560 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005561 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005562 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005563 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005564 // candidate functions in the usual way.113) A given name can refer to one
5565 // or more function templates and also to a set of overloaded non-template
5566 // functions. In such a case, the candidate functions generated from each
5567 // function template are combined with the set of non-template candidate
5568 // functions.
John McCall5769d612010-02-08 23:07:23 +00005569 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005570 FunctionDecl *Specialization = 0;
5571 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005572 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5573 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005574 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005575 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005576 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5577 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005578 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005579 Candidate.IsSurrogate = false;
5580 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005581 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005582 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005583 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005584 return;
5585 }
Mike Stump1eb44332009-09-09 15:08:12 +00005586
Douglas Gregore53060f2009-06-25 22:08:12 +00005587 // Add the function template specialization produced by template argument
5588 // deduction as a candidate.
5589 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005590 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005591 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005592}
Mike Stump1eb44332009-09-09 15:08:12 +00005593
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005594/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005595/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005596/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005597/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005598/// (which may or may not be the same type as the type that the
5599/// conversion function produces).
5600void
5601Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005602 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005603 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005604 Expr *From, QualType ToType,
5605 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005606 assert(!Conversion->getDescribedFunctionTemplate() &&
5607 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005608 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005609 if (!CandidateSet.isNewCandidate(Conversion))
5610 return;
5611
Douglas Gregor7edfb692009-11-23 12:27:39 +00005612 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005613 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005614
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005615 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005616 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005617 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005618 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005619 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005620 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005621 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005622 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005623 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005624 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005625 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005626
Douglas Gregorbca39322010-08-19 15:37:02 +00005627 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005628 // For conversion functions, the function is considered to be a member of
5629 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005630 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005631 //
5632 // Determine the implicit conversion sequence for the implicit
5633 // object parameter.
5634 QualType ImplicitParamType = From->getType();
5635 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5636 ImplicitParamType = FromPtrType->getPointeeType();
5637 CXXRecordDecl *ConversionContext
5638 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005639
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005640 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005641 = TryObjectArgumentInitialization(*this, From->getType(),
5642 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005643 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005644
John McCall1d318332010-01-12 00:44:57 +00005645 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005646 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005647 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005648 return;
5649 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005650
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005651 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005652 // derived to base as such conversions are given Conversion Rank. They only
5653 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5654 QualType FromCanon
5655 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5656 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5657 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5658 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005659 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005660 return;
5661 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005662
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005663 // To determine what the conversion from the result of calling the
5664 // conversion function to the type we're eventually trying to
5665 // convert to (ToType), we need to synthesize a call to the
5666 // conversion function and attempt copy initialization from it. This
5667 // makes sure that we get the right semantics with respect to
5668 // lvalues/rvalues and the type. Fortunately, we can allocate this
5669 // call on the stack and we don't need its arguments to be
5670 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005671 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005672 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005673 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5674 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005675 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005676 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005677
Richard Smith87c1f1f2011-07-13 22:53:21 +00005678 QualType ConversionType = Conversion->getConversionType();
5679 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005680 Candidate.Viable = false;
5681 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5682 return;
5683 }
5684
Richard Smith87c1f1f2011-07-13 22:53:21 +00005685 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005686
Mike Stump1eb44332009-09-09 15:08:12 +00005687 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005688 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5689 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005690 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005691 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005692 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005693 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005694 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005695 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005696 /*InOverloadResolution=*/false,
5697 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005698
John McCall1d318332010-01-12 00:44:57 +00005699 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005700 case ImplicitConversionSequence::StandardConversion:
5701 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005702
Douglas Gregorc520c842010-04-12 23:42:09 +00005703 // C++ [over.ics.user]p3:
5704 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005705 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005706 // shall have exact match rank.
5707 if (Conversion->getPrimaryTemplate() &&
5708 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5709 Candidate.Viable = false;
5710 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5711 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005712
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005713 // C++0x [dcl.init.ref]p5:
5714 // In the second case, if the reference is an rvalue reference and
5715 // the second standard conversion sequence of the user-defined
5716 // conversion sequence includes an lvalue-to-rvalue conversion, the
5717 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005718 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005719 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5720 Candidate.Viable = false;
5721 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5722 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005723 break;
5724
5725 case ImplicitConversionSequence::BadConversion:
5726 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005727 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005728 break;
5729
5730 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005731 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005732 "Can only end up with a standard conversion sequence or failure");
5733 }
5734}
5735
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005736/// \brief Adds a conversion function template specialization
5737/// candidate to the overload set, using template argument deduction
5738/// to deduce the template arguments of the conversion function
5739/// template from the type that we are converting to (C++
5740/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005741void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005742Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005743 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005744 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005745 Expr *From, QualType ToType,
5746 OverloadCandidateSet &CandidateSet) {
5747 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5748 "Only conversion function templates permitted here");
5749
Douglas Gregor3f396022009-09-28 04:47:19 +00005750 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5751 return;
5752
John McCall5769d612010-02-08 23:07:23 +00005753 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005754 CXXConversionDecl *Specialization = 0;
5755 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005756 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005757 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005758 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005759 Candidate.FoundDecl = FoundDecl;
5760 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5761 Candidate.Viable = false;
5762 Candidate.FailureKind = ovl_fail_bad_deduction;
5763 Candidate.IsSurrogate = false;
5764 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005765 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005766 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005767 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005768 return;
5769 }
Mike Stump1eb44332009-09-09 15:08:12 +00005770
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005771 // Add the conversion function template specialization produced by
5772 // template argument deduction as a candidate.
5773 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005774 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005775 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005776}
5777
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005778/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5779/// converts the given @c Object to a function pointer via the
5780/// conversion function @c Conversion, and then attempts to call it
5781/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5782/// the type of function that we'll eventually be calling.
5783void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005784 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005785 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005786 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005787 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005788 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005789 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005790 if (!CandidateSet.isNewCandidate(Conversion))
5791 return;
5792
Douglas Gregor7edfb692009-11-23 12:27:39 +00005793 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005794 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005795
Ahmed Charles13a140c2012-02-25 11:00:22 +00005796 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005797 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005798 Candidate.Function = 0;
5799 Candidate.Surrogate = Conversion;
5800 Candidate.Viable = true;
5801 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005802 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005803 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005804
5805 // Determine the implicit conversion sequence for the implicit
5806 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005807 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005808 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005809 Object->Classify(Context),
5810 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005811 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005812 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005813 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005814 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005815 return;
5816 }
5817
5818 // The first conversion is actually a user-defined conversion whose
5819 // first conversion is ObjectInit's standard conversion (which is
5820 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005821 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005822 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005823 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005824 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005825 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005826 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005827 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005828 = Candidate.Conversions[0].UserDefined.Before;
5829 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5830
Mike Stump1eb44332009-09-09 15:08:12 +00005831 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005832 unsigned NumArgsInProto = Proto->getNumArgs();
5833
5834 // (C++ 13.3.2p2): A candidate function having fewer than m
5835 // parameters is viable only if it has an ellipsis in its parameter
5836 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005837 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005838 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005839 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005840 return;
5841 }
5842
5843 // Function types don't have any default arguments, so just check if
5844 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005845 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005846 // Not enough arguments.
5847 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005848 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005849 return;
5850 }
5851
5852 // Determine the implicit conversion sequences for each of the
5853 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005854 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005855 if (ArgIdx < NumArgsInProto) {
5856 // (C++ 13.3.2p3): for F to be a viable function, there shall
5857 // exist for each argument an implicit conversion sequence
5858 // (13.3.3.1) that converts that argument to the corresponding
5859 // parameter of F.
5860 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005861 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005862 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005863 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005864 /*InOverloadResolution=*/false,
5865 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005866 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005867 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005868 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005869 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005870 break;
5871 }
5872 } else {
5873 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5874 // argument for which there is no corresponding parameter is
5875 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005876 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005877 }
5878 }
5879}
5880
Douglas Gregor063daf62009-03-13 18:40:31 +00005881/// \brief Add overload candidates for overloaded operators that are
5882/// member functions.
5883///
5884/// Add the overloaded operator candidates that are member functions
5885/// for the operator Op that was used in an operator expression such
5886/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5887/// CandidateSet will store the added overload candidates. (C++
5888/// [over.match.oper]).
5889void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5890 SourceLocation OpLoc,
5891 Expr **Args, unsigned NumArgs,
5892 OverloadCandidateSet& CandidateSet,
5893 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005894 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5895
5896 // C++ [over.match.oper]p3:
5897 // For a unary operator @ with an operand of a type whose
5898 // cv-unqualified version is T1, and for a binary operator @ with
5899 // a left operand of a type whose cv-unqualified version is T1 and
5900 // a right operand of a type whose cv-unqualified version is T2,
5901 // three sets of candidate functions, designated member
5902 // candidates, non-member candidates and built-in candidates, are
5903 // constructed as follows:
5904 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005905
5906 // -- If T1 is a class type, the set of member candidates is the
5907 // result of the qualified lookup of T1::operator@
5908 // (13.3.1.1.1); otherwise, the set of member candidates is
5909 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005910 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005911 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005912 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005913 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005914
John McCalla24dc2e2009-11-17 02:14:36 +00005915 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5916 LookupQualifiedName(Operators, T1Rec->getDecl());
5917 Operators.suppressDiagnostics();
5918
Mike Stump1eb44332009-09-09 15:08:12 +00005919 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005920 OperEnd = Operators.end();
5921 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005922 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005923 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005924 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005925 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005926 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005927 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005928}
5929
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005930/// AddBuiltinCandidate - Add a candidate for a built-in
5931/// operator. ResultTy and ParamTys are the result and parameter types
5932/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005933/// arguments being passed to the candidate. IsAssignmentOperator
5934/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005935/// operator. NumContextualBoolArguments is the number of arguments
5936/// (at the beginning of the argument list) that will be contextually
5937/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005938void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005939 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005940 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005941 bool IsAssignmentOperator,
5942 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005943 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005944 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005945
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005946 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005947 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005948 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005949 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005950 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005951 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005952 Candidate.BuiltinTypes.ResultTy = ResultTy;
5953 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5954 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5955
5956 // Determine the implicit conversion sequences for each of the
5957 // arguments.
5958 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005959 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005960 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005961 // C++ [over.match.oper]p4:
5962 // For the built-in assignment operators, conversions of the
5963 // left operand are restricted as follows:
5964 // -- no temporaries are introduced to hold the left operand, and
5965 // -- no user-defined conversions are applied to the left
5966 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005967 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005968 //
5969 // We block these conversions by turning off user-defined
5970 // conversions, since that is the only way that initialization of
5971 // a reference to a non-class type can occur from something that
5972 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005973 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005974 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005975 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005976 Candidate.Conversions[ArgIdx]
5977 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005978 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005979 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005980 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005981 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005982 /*InOverloadResolution=*/false,
5983 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005984 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005985 }
John McCall1d318332010-01-12 00:44:57 +00005986 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005987 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005988 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005989 break;
5990 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005991 }
5992}
5993
5994/// BuiltinCandidateTypeSet - A set of types that will be used for the
5995/// candidate operator functions for built-in operators (C++
5996/// [over.built]). The types are separated into pointer types and
5997/// enumeration types.
5998class BuiltinCandidateTypeSet {
5999 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006000 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006001
6002 /// PointerTypes - The set of pointer types that will be used in the
6003 /// built-in candidates.
6004 TypeSet PointerTypes;
6005
Sebastian Redl78eb8742009-04-19 21:53:20 +00006006 /// MemberPointerTypes - The set of member pointer types that will be
6007 /// used in the built-in candidates.
6008 TypeSet MemberPointerTypes;
6009
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006010 /// EnumerationTypes - The set of enumeration types that will be
6011 /// used in the built-in candidates.
6012 TypeSet EnumerationTypes;
6013
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006014 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006015 /// candidates.
6016 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006017
6018 /// \brief A flag indicating non-record types are viable candidates
6019 bool HasNonRecordTypes;
6020
6021 /// \brief A flag indicating whether either arithmetic or enumeration types
6022 /// were present in the candidate set.
6023 bool HasArithmeticOrEnumeralTypes;
6024
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006025 /// \brief A flag indicating whether the nullptr type was present in the
6026 /// candidate set.
6027 bool HasNullPtrType;
6028
Douglas Gregor5842ba92009-08-24 15:23:48 +00006029 /// Sema - The semantic analysis instance where we are building the
6030 /// candidate type set.
6031 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006032
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006033 /// Context - The AST context in which we will build the type sets.
6034 ASTContext &Context;
6035
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006036 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6037 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006038 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006039
6040public:
6041 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006042 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006043
Mike Stump1eb44332009-09-09 15:08:12 +00006044 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006045 : HasNonRecordTypes(false),
6046 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006047 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006048 SemaRef(SemaRef),
6049 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006050
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006051 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006052 SourceLocation Loc,
6053 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006054 bool AllowExplicitConversions,
6055 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006056
6057 /// pointer_begin - First pointer type found;
6058 iterator pointer_begin() { return PointerTypes.begin(); }
6059
Sebastian Redl78eb8742009-04-19 21:53:20 +00006060 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006061 iterator pointer_end() { return PointerTypes.end(); }
6062
Sebastian Redl78eb8742009-04-19 21:53:20 +00006063 /// member_pointer_begin - First member pointer type found;
6064 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6065
6066 /// member_pointer_end - Past the last member pointer type found;
6067 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6068
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006069 /// enumeration_begin - First enumeration type found;
6070 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6071
Sebastian Redl78eb8742009-04-19 21:53:20 +00006072 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006073 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006074
Douglas Gregor26bcf672010-05-19 03:21:00 +00006075 iterator vector_begin() { return VectorTypes.begin(); }
6076 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006077
6078 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6079 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006080 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006081};
6082
Sebastian Redl78eb8742009-04-19 21:53:20 +00006083/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006084/// the set of pointer types along with any more-qualified variants of
6085/// that type. For example, if @p Ty is "int const *", this routine
6086/// will add "int const *", "int const volatile *", "int const
6087/// restrict *", and "int const volatile restrict *" to the set of
6088/// pointer types. Returns true if the add of @p Ty itself succeeded,
6089/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006090///
6091/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006092bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006093BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6094 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006095
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006096 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006097 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006098 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006099
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006100 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006101 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006102 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006103 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006104 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006105 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006106 buildObjCPtr = true;
6107 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006108 else
David Blaikieb219cfc2011-09-23 05:06:16 +00006109 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006110 }
6111 else
6112 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006113
Sebastian Redla9efada2009-11-18 20:39:26 +00006114 // Don't add qualified variants of arrays. For one, they're not allowed
6115 // (the qualifier would sink to the element type), and for another, the
6116 // only overload situation where it matters is subscript or pointer +- int,
6117 // and those shouldn't have qualifier variants anyway.
6118 if (PointeeTy->isArrayType())
6119 return true;
John McCall0953e762009-09-24 19:53:00 +00006120 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00006121 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00006122 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006123 bool hasVolatile = VisibleQuals.hasVolatile();
6124 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006125
John McCall0953e762009-09-24 19:53:00 +00006126 // Iterate through all strict supersets of BaseCVR.
6127 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6128 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006129 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6130 // in the types.
6131 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6132 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00006133 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006134 if (!buildObjCPtr)
6135 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6136 else
6137 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006138 }
6139
6140 return true;
6141}
6142
Sebastian Redl78eb8742009-04-19 21:53:20 +00006143/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6144/// to the set of pointer types along with any more-qualified variants of
6145/// that type. For example, if @p Ty is "int const *", this routine
6146/// will add "int const *", "int const volatile *", "int const
6147/// restrict *", and "int const volatile restrict *" to the set of
6148/// pointer types. Returns true if the add of @p Ty itself succeeded,
6149/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006150///
6151/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006152bool
6153BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6154 QualType Ty) {
6155 // Insert this type.
6156 if (!MemberPointerTypes.insert(Ty))
6157 return false;
6158
John McCall0953e762009-09-24 19:53:00 +00006159 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6160 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006161
John McCall0953e762009-09-24 19:53:00 +00006162 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006163 // Don't add qualified variants of arrays. For one, they're not allowed
6164 // (the qualifier would sink to the element type), and for another, the
6165 // only overload situation where it matters is subscript or pointer +- int,
6166 // and those shouldn't have qualifier variants anyway.
6167 if (PointeeTy->isArrayType())
6168 return true;
John McCall0953e762009-09-24 19:53:00 +00006169 const Type *ClassTy = PointerTy->getClass();
6170
6171 // Iterate through all strict supersets of the pointee type's CVR
6172 // qualifiers.
6173 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6174 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6175 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006176
John McCall0953e762009-09-24 19:53:00 +00006177 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006178 MemberPointerTypes.insert(
6179 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006180 }
6181
6182 return true;
6183}
6184
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006185/// AddTypesConvertedFrom - Add each of the types to which the type @p
6186/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006187/// primarily interested in pointer types and enumeration types. We also
6188/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006189/// AllowUserConversions is true if we should look at the conversion
6190/// functions of a class type, and AllowExplicitConversions if we
6191/// should also include the explicit conversion functions of a class
6192/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006193void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006194BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006195 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006196 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006197 bool AllowExplicitConversions,
6198 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006199 // Only deal with canonical types.
6200 Ty = Context.getCanonicalType(Ty);
6201
6202 // Look through reference types; they aren't part of the type of an
6203 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006204 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006205 Ty = RefTy->getPointeeType();
6206
John McCall3b657512011-01-19 10:06:00 +00006207 // If we're dealing with an array type, decay to the pointer.
6208 if (Ty->isArrayType())
6209 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6210
6211 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006212 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006213
Chandler Carruth6a577462010-12-13 01:44:01 +00006214 // Flag if we ever add a non-record type.
6215 const RecordType *TyRec = Ty->getAs<RecordType>();
6216 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6217
Chandler Carruth6a577462010-12-13 01:44:01 +00006218 // Flag if we encounter an arithmetic type.
6219 HasArithmeticOrEnumeralTypes =
6220 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6221
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006222 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6223 PointerTypes.insert(Ty);
6224 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006225 // Insert our type, and its more-qualified variants, into the set
6226 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006227 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006228 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006229 } else if (Ty->isMemberPointerType()) {
6230 // Member pointers are far easier, since the pointee can't be converted.
6231 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6232 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006233 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006234 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006235 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006236 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006237 // We treat vector types as arithmetic types in many contexts as an
6238 // extension.
6239 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006240 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006241 } else if (Ty->isNullPtrType()) {
6242 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006243 } else if (AllowUserConversions && TyRec) {
6244 // No conversion functions in incomplete types.
6245 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6246 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006247
Chandler Carruth6a577462010-12-13 01:44:01 +00006248 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6249 const UnresolvedSetImpl *Conversions
6250 = ClassDecl->getVisibleConversionFunctions();
6251 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6252 E = Conversions->end(); I != E; ++I) {
6253 NamedDecl *D = I.getDecl();
6254 if (isa<UsingShadowDecl>(D))
6255 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006256
Chandler Carruth6a577462010-12-13 01:44:01 +00006257 // Skip conversion function templates; they don't tell us anything
6258 // about which builtin types we can convert to.
6259 if (isa<FunctionTemplateDecl>(D))
6260 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006261
Chandler Carruth6a577462010-12-13 01:44:01 +00006262 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6263 if (AllowExplicitConversions || !Conv->isExplicit()) {
6264 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6265 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006266 }
6267 }
6268 }
6269}
6270
Douglas Gregor19b7b152009-08-24 13:43:27 +00006271/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6272/// the volatile- and non-volatile-qualified assignment operators for the
6273/// given type to the candidate set.
6274static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6275 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006276 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006277 unsigned NumArgs,
6278 OverloadCandidateSet &CandidateSet) {
6279 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006280
Douglas Gregor19b7b152009-08-24 13:43:27 +00006281 // T& operator=(T&, T)
6282 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6283 ParamTypes[1] = T;
6284 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6285 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006286
Douglas Gregor19b7b152009-08-24 13:43:27 +00006287 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6288 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006289 ParamTypes[0]
6290 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006291 ParamTypes[1] = T;
6292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006293 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006294 }
6295}
Mike Stump1eb44332009-09-09 15:08:12 +00006296
Sebastian Redl9994a342009-10-25 17:03:50 +00006297/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6298/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006299static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6300 Qualifiers VRQuals;
6301 const RecordType *TyRec;
6302 if (const MemberPointerType *RHSMPType =
6303 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006304 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006305 else
6306 TyRec = ArgExpr->getType()->getAs<RecordType>();
6307 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006308 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006309 VRQuals.addVolatile();
6310 VRQuals.addRestrict();
6311 return VRQuals;
6312 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006313
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006314 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006315 if (!ClassDecl->hasDefinition())
6316 return VRQuals;
6317
John McCalleec51cf2010-01-20 00:46:10 +00006318 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006319 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006320
John McCalleec51cf2010-01-20 00:46:10 +00006321 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006322 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006323 NamedDecl *D = I.getDecl();
6324 if (isa<UsingShadowDecl>(D))
6325 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6326 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006327 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6328 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6329 CanTy = ResTypeRef->getPointeeType();
6330 // Need to go down the pointer/mempointer chain and add qualifiers
6331 // as see them.
6332 bool done = false;
6333 while (!done) {
6334 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6335 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006336 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006337 CanTy->getAs<MemberPointerType>())
6338 CanTy = ResTypeMPtr->getPointeeType();
6339 else
6340 done = true;
6341 if (CanTy.isVolatileQualified())
6342 VRQuals.addVolatile();
6343 if (CanTy.isRestrictQualified())
6344 VRQuals.addRestrict();
6345 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6346 return VRQuals;
6347 }
6348 }
6349 }
6350 return VRQuals;
6351}
John McCall00071ec2010-11-13 05:51:15 +00006352
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006353namespace {
John McCall00071ec2010-11-13 05:51:15 +00006354
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006355/// \brief Helper class to manage the addition of builtin operator overload
6356/// candidates. It provides shared state and utility methods used throughout
6357/// the process, as well as a helper method to add each group of builtin
6358/// operator overloads from the standard to a candidate set.
6359class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006360 // Common instance state available to all overload candidate addition methods.
6361 Sema &S;
6362 Expr **Args;
6363 unsigned NumArgs;
6364 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006365 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006366 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006367 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006368
Chandler Carruth6d695582010-12-12 10:35:00 +00006369 // Define some constants used to index and iterate over the arithemetic types
6370 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006371 // The "promoted arithmetic types" are the arithmetic
6372 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006373 static const unsigned FirstIntegralType = 3;
6374 static const unsigned LastIntegralType = 18;
6375 static const unsigned FirstPromotedIntegralType = 3,
6376 LastPromotedIntegralType = 9;
6377 static const unsigned FirstPromotedArithmeticType = 0,
6378 LastPromotedArithmeticType = 9;
6379 static const unsigned NumArithmeticTypes = 18;
6380
Chandler Carruth6d695582010-12-12 10:35:00 +00006381 /// \brief Get the canonical type for a given arithmetic type index.
6382 CanQualType getArithmeticType(unsigned index) {
6383 assert(index < NumArithmeticTypes);
6384 static CanQualType ASTContext::* const
6385 ArithmeticTypes[NumArithmeticTypes] = {
6386 // Start of promoted types.
6387 &ASTContext::FloatTy,
6388 &ASTContext::DoubleTy,
6389 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006390
Chandler Carruth6d695582010-12-12 10:35:00 +00006391 // Start of integral types.
6392 &ASTContext::IntTy,
6393 &ASTContext::LongTy,
6394 &ASTContext::LongLongTy,
6395 &ASTContext::UnsignedIntTy,
6396 &ASTContext::UnsignedLongTy,
6397 &ASTContext::UnsignedLongLongTy,
6398 // End of promoted types.
6399
6400 &ASTContext::BoolTy,
6401 &ASTContext::CharTy,
6402 &ASTContext::WCharTy,
6403 &ASTContext::Char16Ty,
6404 &ASTContext::Char32Ty,
6405 &ASTContext::SignedCharTy,
6406 &ASTContext::ShortTy,
6407 &ASTContext::UnsignedCharTy,
6408 &ASTContext::UnsignedShortTy,
6409 // End of integral types.
6410 // FIXME: What about complex?
6411 };
6412 return S.Context.*ArithmeticTypes[index];
6413 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006414
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006415 /// \brief Gets the canonical type resulting from the usual arithemetic
6416 /// converions for the given arithmetic types.
6417 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6418 // Accelerator table for performing the usual arithmetic conversions.
6419 // The rules are basically:
6420 // - if either is floating-point, use the wider floating-point
6421 // - if same signedness, use the higher rank
6422 // - if same size, use unsigned of the higher rank
6423 // - use the larger type
6424 // These rules, together with the axiom that higher ranks are
6425 // never smaller, are sufficient to precompute all of these results
6426 // *except* when dealing with signed types of higher rank.
6427 // (we could precompute SLL x UI for all known platforms, but it's
6428 // better not to make any assumptions).
6429 enum PromotedType {
6430 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6431 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006432 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006433 [LastPromotedArithmeticType] = {
6434 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6435 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6436 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6437 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6438 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6439 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6440 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6441 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6442 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6443 };
6444
6445 assert(L < LastPromotedArithmeticType);
6446 assert(R < LastPromotedArithmeticType);
6447 int Idx = ConversionsTable[L][R];
6448
6449 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006450 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006451
6452 // Slow path: we need to compare widths.
6453 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006454 CanQualType LT = getArithmeticType(L),
6455 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006456 unsigned LW = S.Context.getIntWidth(LT),
6457 RW = S.Context.getIntWidth(RT);
6458
6459 // If they're different widths, use the signed type.
6460 if (LW > RW) return LT;
6461 else if (LW < RW) return RT;
6462
6463 // Otherwise, use the unsigned type of the signed type's rank.
6464 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6465 assert(L == SLL || R == SLL);
6466 return S.Context.UnsignedLongLongTy;
6467 }
6468
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006469 /// \brief Helper method to factor out the common pattern of adding overloads
6470 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006471 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6472 bool HasVolatile) {
6473 QualType ParamTypes[2] = {
6474 S.Context.getLValueReferenceType(CandidateTy),
6475 S.Context.IntTy
6476 };
6477
6478 // Non-volatile version.
6479 if (NumArgs == 1)
6480 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6481 else
6482 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6483
6484 // Use a heuristic to reduce number of builtin candidates in the set:
6485 // add volatile version only if there are conversions to a volatile type.
6486 if (HasVolatile) {
6487 ParamTypes[0] =
6488 S.Context.getLValueReferenceType(
6489 S.Context.getVolatileType(CandidateTy));
6490 if (NumArgs == 1)
6491 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6492 else
6493 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6494 }
6495 }
6496
6497public:
6498 BuiltinOperatorOverloadBuilder(
6499 Sema &S, Expr **Args, unsigned NumArgs,
6500 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006501 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006502 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006503 OverloadCandidateSet &CandidateSet)
6504 : S(S), Args(Args), NumArgs(NumArgs),
6505 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006506 HasArithmeticOrEnumeralCandidateType(
6507 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006508 CandidateTypes(CandidateTypes),
6509 CandidateSet(CandidateSet) {
6510 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006511 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006512 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006513 assert(getArithmeticType(LastPromotedIntegralType - 1)
6514 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006515 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006516 assert(getArithmeticType(FirstPromotedArithmeticType)
6517 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006518 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006519 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6520 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006521 "Invalid last promoted arithmetic type");
6522 }
6523
6524 // C++ [over.built]p3:
6525 //
6526 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6527 // is either volatile or empty, there exist candidate operator
6528 // functions of the form
6529 //
6530 // VQ T& operator++(VQ T&);
6531 // T operator++(VQ T&, int);
6532 //
6533 // C++ [over.built]p4:
6534 //
6535 // For every pair (T, VQ), where T is an arithmetic type other
6536 // than bool, and VQ is either volatile or empty, there exist
6537 // candidate operator functions of the form
6538 //
6539 // VQ T& operator--(VQ T&);
6540 // T operator--(VQ T&, int);
6541 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006542 if (!HasArithmeticOrEnumeralCandidateType)
6543 return;
6544
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006545 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6546 Arith < NumArithmeticTypes; ++Arith) {
6547 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006548 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006549 VisibleTypeConversionsQuals.hasVolatile());
6550 }
6551 }
6552
6553 // C++ [over.built]p5:
6554 //
6555 // For every pair (T, VQ), where T is a cv-qualified or
6556 // cv-unqualified object type, and VQ is either volatile or
6557 // empty, there exist candidate operator functions of the form
6558 //
6559 // T*VQ& operator++(T*VQ&);
6560 // T*VQ& operator--(T*VQ&);
6561 // T* operator++(T*VQ&, int);
6562 // T* operator--(T*VQ&, int);
6563 void addPlusPlusMinusMinusPointerOverloads() {
6564 for (BuiltinCandidateTypeSet::iterator
6565 Ptr = CandidateTypes[0].pointer_begin(),
6566 PtrEnd = CandidateTypes[0].pointer_end();
6567 Ptr != PtrEnd; ++Ptr) {
6568 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006569 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006570 continue;
6571
6572 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6573 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6574 VisibleTypeConversionsQuals.hasVolatile()));
6575 }
6576 }
6577
6578 // C++ [over.built]p6:
6579 // For every cv-qualified or cv-unqualified object type T, there
6580 // exist candidate operator functions of the form
6581 //
6582 // T& operator*(T*);
6583 //
6584 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006585 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006586 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006587 // T& operator*(T*);
6588 void addUnaryStarPointerOverloads() {
6589 for (BuiltinCandidateTypeSet::iterator
6590 Ptr = CandidateTypes[0].pointer_begin(),
6591 PtrEnd = CandidateTypes[0].pointer_end();
6592 Ptr != PtrEnd; ++Ptr) {
6593 QualType ParamTy = *Ptr;
6594 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006595 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6596 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006597
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006598 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6599 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6600 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006601
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006602 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6603 &ParamTy, Args, 1, CandidateSet);
6604 }
6605 }
6606
6607 // C++ [over.built]p9:
6608 // For every promoted arithmetic type T, there exist candidate
6609 // operator functions of the form
6610 //
6611 // T operator+(T);
6612 // T operator-(T);
6613 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006614 if (!HasArithmeticOrEnumeralCandidateType)
6615 return;
6616
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006617 for (unsigned Arith = FirstPromotedArithmeticType;
6618 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006619 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006620 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6621 }
6622
6623 // Extension: We also add these operators for vector types.
6624 for (BuiltinCandidateTypeSet::iterator
6625 Vec = CandidateTypes[0].vector_begin(),
6626 VecEnd = CandidateTypes[0].vector_end();
6627 Vec != VecEnd; ++Vec) {
6628 QualType VecTy = *Vec;
6629 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6630 }
6631 }
6632
6633 // C++ [over.built]p8:
6634 // For every type T, there exist candidate operator functions of
6635 // the form
6636 //
6637 // T* operator+(T*);
6638 void addUnaryPlusPointerOverloads() {
6639 for (BuiltinCandidateTypeSet::iterator
6640 Ptr = CandidateTypes[0].pointer_begin(),
6641 PtrEnd = CandidateTypes[0].pointer_end();
6642 Ptr != PtrEnd; ++Ptr) {
6643 QualType ParamTy = *Ptr;
6644 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6645 }
6646 }
6647
6648 // C++ [over.built]p10:
6649 // For every promoted integral type T, there exist candidate
6650 // operator functions of the form
6651 //
6652 // T operator~(T);
6653 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006654 if (!HasArithmeticOrEnumeralCandidateType)
6655 return;
6656
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006657 for (unsigned Int = FirstPromotedIntegralType;
6658 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006659 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006660 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6661 }
6662
6663 // Extension: We also add this operator for vector types.
6664 for (BuiltinCandidateTypeSet::iterator
6665 Vec = CandidateTypes[0].vector_begin(),
6666 VecEnd = CandidateTypes[0].vector_end();
6667 Vec != VecEnd; ++Vec) {
6668 QualType VecTy = *Vec;
6669 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6670 }
6671 }
6672
6673 // C++ [over.match.oper]p16:
6674 // For every pointer to member type T, there exist candidate operator
6675 // functions of the form
6676 //
6677 // bool operator==(T,T);
6678 // bool operator!=(T,T);
6679 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6680 /// Set of (canonical) types that we've already handled.
6681 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6682
6683 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6684 for (BuiltinCandidateTypeSet::iterator
6685 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6686 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6687 MemPtr != MemPtrEnd;
6688 ++MemPtr) {
6689 // Don't add the same builtin candidate twice.
6690 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6691 continue;
6692
6693 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6694 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6695 CandidateSet);
6696 }
6697 }
6698 }
6699
6700 // C++ [over.built]p15:
6701 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006702 // For every T, where T is an enumeration type, a pointer type, or
6703 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006704 //
6705 // bool operator<(T, T);
6706 // bool operator>(T, T);
6707 // bool operator<=(T, T);
6708 // bool operator>=(T, T);
6709 // bool operator==(T, T);
6710 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006711 void addRelationalPointerOrEnumeralOverloads() {
6712 // C++ [over.built]p1:
6713 // If there is a user-written candidate with the same name and parameter
6714 // types as a built-in candidate operator function, the built-in operator
6715 // function is hidden and is not included in the set of candidate
6716 // functions.
6717 //
6718 // The text is actually in a note, but if we don't implement it then we end
6719 // up with ambiguities when the user provides an overloaded operator for
6720 // an enumeration type. Note that only enumeration types have this problem,
6721 // so we track which enumeration types we've seen operators for. Also, the
6722 // only other overloaded operator with enumeration argumenst, operator=,
6723 // cannot be overloaded for enumeration types, so this is the only place
6724 // where we must suppress candidates like this.
6725 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6726 UserDefinedBinaryOperators;
6727
6728 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6729 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6730 CandidateTypes[ArgIdx].enumeration_end()) {
6731 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6732 CEnd = CandidateSet.end();
6733 C != CEnd; ++C) {
6734 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6735 continue;
6736
6737 QualType FirstParamType =
6738 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6739 QualType SecondParamType =
6740 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6741
6742 // Skip if either parameter isn't of enumeral type.
6743 if (!FirstParamType->isEnumeralType() ||
6744 !SecondParamType->isEnumeralType())
6745 continue;
6746
6747 // Add this operator to the set of known user-defined operators.
6748 UserDefinedBinaryOperators.insert(
6749 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6750 S.Context.getCanonicalType(SecondParamType)));
6751 }
6752 }
6753 }
6754
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006755 /// Set of (canonical) types that we've already handled.
6756 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6757
6758 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6759 for (BuiltinCandidateTypeSet::iterator
6760 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6761 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6762 Ptr != PtrEnd; ++Ptr) {
6763 // Don't add the same builtin candidate twice.
6764 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6765 continue;
6766
6767 QualType ParamTypes[2] = { *Ptr, *Ptr };
6768 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6769 CandidateSet);
6770 }
6771 for (BuiltinCandidateTypeSet::iterator
6772 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6773 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6774 Enum != EnumEnd; ++Enum) {
6775 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6776
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006777 // Don't add the same builtin candidate twice, or if a user defined
6778 // candidate exists.
6779 if (!AddedTypes.insert(CanonType) ||
6780 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6781 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006782 continue;
6783
6784 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006785 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6786 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006787 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006788
6789 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6790 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6791 if (AddedTypes.insert(NullPtrTy) &&
6792 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6793 NullPtrTy))) {
6794 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6795 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6796 CandidateSet);
6797 }
6798 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006799 }
6800 }
6801
6802 // C++ [over.built]p13:
6803 //
6804 // For every cv-qualified or cv-unqualified object type T
6805 // there exist candidate operator functions of the form
6806 //
6807 // T* operator+(T*, ptrdiff_t);
6808 // T& operator[](T*, ptrdiff_t); [BELOW]
6809 // T* operator-(T*, ptrdiff_t);
6810 // T* operator+(ptrdiff_t, T*);
6811 // T& operator[](ptrdiff_t, T*); [BELOW]
6812 //
6813 // C++ [over.built]p14:
6814 //
6815 // For every T, where T is a pointer to object type, there
6816 // exist candidate operator functions of the form
6817 //
6818 // ptrdiff_t operator-(T, T);
6819 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6820 /// Set of (canonical) types that we've already handled.
6821 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6822
6823 for (int Arg = 0; Arg < 2; ++Arg) {
6824 QualType AsymetricParamTypes[2] = {
6825 S.Context.getPointerDiffType(),
6826 S.Context.getPointerDiffType(),
6827 };
6828 for (BuiltinCandidateTypeSet::iterator
6829 Ptr = CandidateTypes[Arg].pointer_begin(),
6830 PtrEnd = CandidateTypes[Arg].pointer_end();
6831 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006832 QualType PointeeTy = (*Ptr)->getPointeeType();
6833 if (!PointeeTy->isObjectType())
6834 continue;
6835
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006836 AsymetricParamTypes[Arg] = *Ptr;
6837 if (Arg == 0 || Op == OO_Plus) {
6838 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6839 // T* operator+(ptrdiff_t, T*);
6840 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6841 CandidateSet);
6842 }
6843 if (Op == OO_Minus) {
6844 // ptrdiff_t operator-(T, T);
6845 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6846 continue;
6847
6848 QualType ParamTypes[2] = { *Ptr, *Ptr };
6849 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6850 Args, 2, CandidateSet);
6851 }
6852 }
6853 }
6854 }
6855
6856 // C++ [over.built]p12:
6857 //
6858 // For every pair of promoted arithmetic types L and R, there
6859 // exist candidate operator functions of the form
6860 //
6861 // LR operator*(L, R);
6862 // LR operator/(L, R);
6863 // LR operator+(L, R);
6864 // LR operator-(L, R);
6865 // bool operator<(L, R);
6866 // bool operator>(L, R);
6867 // bool operator<=(L, R);
6868 // bool operator>=(L, R);
6869 // bool operator==(L, R);
6870 // bool operator!=(L, R);
6871 //
6872 // where LR is the result of the usual arithmetic conversions
6873 // between types L and R.
6874 //
6875 // C++ [over.built]p24:
6876 //
6877 // For every pair of promoted arithmetic types L and R, there exist
6878 // candidate operator functions of the form
6879 //
6880 // LR operator?(bool, L, R);
6881 //
6882 // where LR is the result of the usual arithmetic conversions
6883 // between types L and R.
6884 // Our candidates ignore the first parameter.
6885 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006886 if (!HasArithmeticOrEnumeralCandidateType)
6887 return;
6888
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006889 for (unsigned Left = FirstPromotedArithmeticType;
6890 Left < LastPromotedArithmeticType; ++Left) {
6891 for (unsigned Right = FirstPromotedArithmeticType;
6892 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006893 QualType LandR[2] = { getArithmeticType(Left),
6894 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006895 QualType Result =
6896 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006897 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006898 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6899 }
6900 }
6901
6902 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6903 // conditional operator for vector types.
6904 for (BuiltinCandidateTypeSet::iterator
6905 Vec1 = CandidateTypes[0].vector_begin(),
6906 Vec1End = CandidateTypes[0].vector_end();
6907 Vec1 != Vec1End; ++Vec1) {
6908 for (BuiltinCandidateTypeSet::iterator
6909 Vec2 = CandidateTypes[1].vector_begin(),
6910 Vec2End = CandidateTypes[1].vector_end();
6911 Vec2 != Vec2End; ++Vec2) {
6912 QualType LandR[2] = { *Vec1, *Vec2 };
6913 QualType Result = S.Context.BoolTy;
6914 if (!isComparison) {
6915 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6916 Result = *Vec1;
6917 else
6918 Result = *Vec2;
6919 }
6920
6921 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6922 }
6923 }
6924 }
6925
6926 // C++ [over.built]p17:
6927 //
6928 // For every pair of promoted integral types L and R, there
6929 // exist candidate operator functions of the form
6930 //
6931 // LR operator%(L, R);
6932 // LR operator&(L, R);
6933 // LR operator^(L, R);
6934 // LR operator|(L, R);
6935 // L operator<<(L, R);
6936 // L operator>>(L, R);
6937 //
6938 // where LR is the result of the usual arithmetic conversions
6939 // between types L and R.
6940 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006941 if (!HasArithmeticOrEnumeralCandidateType)
6942 return;
6943
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006944 for (unsigned Left = FirstPromotedIntegralType;
6945 Left < LastPromotedIntegralType; ++Left) {
6946 for (unsigned Right = FirstPromotedIntegralType;
6947 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006948 QualType LandR[2] = { getArithmeticType(Left),
6949 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006950 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6951 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006952 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006953 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6954 }
6955 }
6956 }
6957
6958 // C++ [over.built]p20:
6959 //
6960 // For every pair (T, VQ), where T is an enumeration or
6961 // pointer to member type and VQ is either volatile or
6962 // empty, there exist candidate operator functions of the form
6963 //
6964 // VQ T& operator=(VQ T&, T);
6965 void addAssignmentMemberPointerOrEnumeralOverloads() {
6966 /// Set of (canonical) types that we've already handled.
6967 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6968
6969 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6970 for (BuiltinCandidateTypeSet::iterator
6971 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6972 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6973 Enum != EnumEnd; ++Enum) {
6974 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6975 continue;
6976
6977 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6978 CandidateSet);
6979 }
6980
6981 for (BuiltinCandidateTypeSet::iterator
6982 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6983 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6984 MemPtr != MemPtrEnd; ++MemPtr) {
6985 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6986 continue;
6987
6988 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6989 CandidateSet);
6990 }
6991 }
6992 }
6993
6994 // C++ [over.built]p19:
6995 //
6996 // For every pair (T, VQ), where T is any type and VQ is either
6997 // volatile or empty, there exist candidate operator functions
6998 // of the form
6999 //
7000 // T*VQ& operator=(T*VQ&, T*);
7001 //
7002 // C++ [over.built]p21:
7003 //
7004 // For every pair (T, VQ), where T is a cv-qualified or
7005 // cv-unqualified object type and VQ is either volatile or
7006 // empty, there exist candidate operator functions of the form
7007 //
7008 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7009 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7010 void addAssignmentPointerOverloads(bool isEqualOp) {
7011 /// Set of (canonical) types that we've already handled.
7012 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7013
7014 for (BuiltinCandidateTypeSet::iterator
7015 Ptr = CandidateTypes[0].pointer_begin(),
7016 PtrEnd = CandidateTypes[0].pointer_end();
7017 Ptr != PtrEnd; ++Ptr) {
7018 // If this is operator=, keep track of the builtin candidates we added.
7019 if (isEqualOp)
7020 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007021 else if (!(*Ptr)->getPointeeType()->isObjectType())
7022 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007023
7024 // non-volatile version
7025 QualType ParamTypes[2] = {
7026 S.Context.getLValueReferenceType(*Ptr),
7027 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7028 };
7029 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7030 /*IsAssigmentOperator=*/ isEqualOp);
7031
7032 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7033 VisibleTypeConversionsQuals.hasVolatile()) {
7034 // volatile version
7035 ParamTypes[0] =
7036 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7037 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7038 /*IsAssigmentOperator=*/isEqualOp);
7039 }
7040 }
7041
7042 if (isEqualOp) {
7043 for (BuiltinCandidateTypeSet::iterator
7044 Ptr = CandidateTypes[1].pointer_begin(),
7045 PtrEnd = CandidateTypes[1].pointer_end();
7046 Ptr != PtrEnd; ++Ptr) {
7047 // Make sure we don't add the same candidate twice.
7048 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7049 continue;
7050
Chandler Carruth6df868e2010-12-12 08:17:55 +00007051 QualType ParamTypes[2] = {
7052 S.Context.getLValueReferenceType(*Ptr),
7053 *Ptr,
7054 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007055
7056 // non-volatile version
7057 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7058 /*IsAssigmentOperator=*/true);
7059
7060 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7061 VisibleTypeConversionsQuals.hasVolatile()) {
7062 // volatile version
7063 ParamTypes[0] =
7064 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007065 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7066 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007067 }
7068 }
7069 }
7070 }
7071
7072 // C++ [over.built]p18:
7073 //
7074 // For every triple (L, VQ, R), where L is an arithmetic type,
7075 // VQ is either volatile or empty, and R is a promoted
7076 // arithmetic type, there exist candidate operator functions of
7077 // the form
7078 //
7079 // VQ L& operator=(VQ L&, R);
7080 // VQ L& operator*=(VQ L&, R);
7081 // VQ L& operator/=(VQ L&, R);
7082 // VQ L& operator+=(VQ L&, R);
7083 // VQ L& operator-=(VQ L&, R);
7084 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007085 if (!HasArithmeticOrEnumeralCandidateType)
7086 return;
7087
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007088 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7089 for (unsigned Right = FirstPromotedArithmeticType;
7090 Right < LastPromotedArithmeticType; ++Right) {
7091 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007092 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007093
7094 // Add this built-in operator as a candidate (VQ is empty).
7095 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007096 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007097 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7098 /*IsAssigmentOperator=*/isEqualOp);
7099
7100 // Add this built-in operator as a candidate (VQ is 'volatile').
7101 if (VisibleTypeConversionsQuals.hasVolatile()) {
7102 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007103 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007104 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007105 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7106 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007107 /*IsAssigmentOperator=*/isEqualOp);
7108 }
7109 }
7110 }
7111
7112 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7113 for (BuiltinCandidateTypeSet::iterator
7114 Vec1 = CandidateTypes[0].vector_begin(),
7115 Vec1End = CandidateTypes[0].vector_end();
7116 Vec1 != Vec1End; ++Vec1) {
7117 for (BuiltinCandidateTypeSet::iterator
7118 Vec2 = CandidateTypes[1].vector_begin(),
7119 Vec2End = CandidateTypes[1].vector_end();
7120 Vec2 != Vec2End; ++Vec2) {
7121 QualType ParamTypes[2];
7122 ParamTypes[1] = *Vec2;
7123 // Add this built-in operator as a candidate (VQ is empty).
7124 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7125 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7126 /*IsAssigmentOperator=*/isEqualOp);
7127
7128 // Add this built-in operator as a candidate (VQ is 'volatile').
7129 if (VisibleTypeConversionsQuals.hasVolatile()) {
7130 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7131 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007132 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7133 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007134 /*IsAssigmentOperator=*/isEqualOp);
7135 }
7136 }
7137 }
7138 }
7139
7140 // C++ [over.built]p22:
7141 //
7142 // For every triple (L, VQ, R), where L is an integral type, VQ
7143 // is either volatile or empty, and R is a promoted integral
7144 // type, there exist candidate operator functions of the form
7145 //
7146 // VQ L& operator%=(VQ L&, R);
7147 // VQ L& operator<<=(VQ L&, R);
7148 // VQ L& operator>>=(VQ L&, R);
7149 // VQ L& operator&=(VQ L&, R);
7150 // VQ L& operator^=(VQ L&, R);
7151 // VQ L& operator|=(VQ L&, R);
7152 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007153 if (!HasArithmeticOrEnumeralCandidateType)
7154 return;
7155
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007156 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7157 for (unsigned Right = FirstPromotedIntegralType;
7158 Right < LastPromotedIntegralType; ++Right) {
7159 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007160 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007161
7162 // Add this built-in operator as a candidate (VQ is empty).
7163 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007164 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007165 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7166 if (VisibleTypeConversionsQuals.hasVolatile()) {
7167 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007168 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007169 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7170 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7172 CandidateSet);
7173 }
7174 }
7175 }
7176 }
7177
7178 // C++ [over.operator]p23:
7179 //
7180 // There also exist candidate operator functions of the form
7181 //
7182 // bool operator!(bool);
7183 // bool operator&&(bool, bool);
7184 // bool operator||(bool, bool);
7185 void addExclaimOverload() {
7186 QualType ParamTy = S.Context.BoolTy;
7187 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7188 /*IsAssignmentOperator=*/false,
7189 /*NumContextualBoolArguments=*/1);
7190 }
7191 void addAmpAmpOrPipePipeOverload() {
7192 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7193 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7194 /*IsAssignmentOperator=*/false,
7195 /*NumContextualBoolArguments=*/2);
7196 }
7197
7198 // C++ [over.built]p13:
7199 //
7200 // For every cv-qualified or cv-unqualified object type T there
7201 // exist candidate operator functions of the form
7202 //
7203 // T* operator+(T*, ptrdiff_t); [ABOVE]
7204 // T& operator[](T*, ptrdiff_t);
7205 // T* operator-(T*, ptrdiff_t); [ABOVE]
7206 // T* operator+(ptrdiff_t, T*); [ABOVE]
7207 // T& operator[](ptrdiff_t, T*);
7208 void addSubscriptOverloads() {
7209 for (BuiltinCandidateTypeSet::iterator
7210 Ptr = CandidateTypes[0].pointer_begin(),
7211 PtrEnd = CandidateTypes[0].pointer_end();
7212 Ptr != PtrEnd; ++Ptr) {
7213 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7214 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007215 if (!PointeeType->isObjectType())
7216 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007217
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007218 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7219
7220 // T& operator[](T*, ptrdiff_t)
7221 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7222 }
7223
7224 for (BuiltinCandidateTypeSet::iterator
7225 Ptr = CandidateTypes[1].pointer_begin(),
7226 PtrEnd = CandidateTypes[1].pointer_end();
7227 Ptr != PtrEnd; ++Ptr) {
7228 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7229 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007230 if (!PointeeType->isObjectType())
7231 continue;
7232
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007233 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7234
7235 // T& operator[](ptrdiff_t, T*)
7236 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7237 }
7238 }
7239
7240 // C++ [over.built]p11:
7241 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7242 // C1 is the same type as C2 or is a derived class of C2, T is an object
7243 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7244 // there exist candidate operator functions of the form
7245 //
7246 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7247 //
7248 // where CV12 is the union of CV1 and CV2.
7249 void addArrowStarOverloads() {
7250 for (BuiltinCandidateTypeSet::iterator
7251 Ptr = CandidateTypes[0].pointer_begin(),
7252 PtrEnd = CandidateTypes[0].pointer_end();
7253 Ptr != PtrEnd; ++Ptr) {
7254 QualType C1Ty = (*Ptr);
7255 QualType C1;
7256 QualifierCollector Q1;
7257 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7258 if (!isa<RecordType>(C1))
7259 continue;
7260 // heuristic to reduce number of builtin candidates in the set.
7261 // Add volatile/restrict version only if there are conversions to a
7262 // volatile/restrict type.
7263 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7264 continue;
7265 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7266 continue;
7267 for (BuiltinCandidateTypeSet::iterator
7268 MemPtr = CandidateTypes[1].member_pointer_begin(),
7269 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7270 MemPtr != MemPtrEnd; ++MemPtr) {
7271 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7272 QualType C2 = QualType(mptr->getClass(), 0);
7273 C2 = C2.getUnqualifiedType();
7274 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7275 break;
7276 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7277 // build CV12 T&
7278 QualType T = mptr->getPointeeType();
7279 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7280 T.isVolatileQualified())
7281 continue;
7282 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7283 T.isRestrictQualified())
7284 continue;
7285 T = Q1.apply(S.Context, T);
7286 QualType ResultTy = S.Context.getLValueReferenceType(T);
7287 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7288 }
7289 }
7290 }
7291
7292 // Note that we don't consider the first argument, since it has been
7293 // contextually converted to bool long ago. The candidates below are
7294 // therefore added as binary.
7295 //
7296 // C++ [over.built]p25:
7297 // For every type T, where T is a pointer, pointer-to-member, or scoped
7298 // enumeration type, there exist candidate operator functions of the form
7299 //
7300 // T operator?(bool, T, T);
7301 //
7302 void addConditionalOperatorOverloads() {
7303 /// Set of (canonical) types that we've already handled.
7304 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7305
7306 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7307 for (BuiltinCandidateTypeSet::iterator
7308 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7309 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7310 Ptr != PtrEnd; ++Ptr) {
7311 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7312 continue;
7313
7314 QualType ParamTypes[2] = { *Ptr, *Ptr };
7315 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7316 }
7317
7318 for (BuiltinCandidateTypeSet::iterator
7319 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7320 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7321 MemPtr != MemPtrEnd; ++MemPtr) {
7322 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7323 continue;
7324
7325 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7326 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7327 }
7328
David Blaikie4e4d0842012-03-11 07:00:24 +00007329 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007330 for (BuiltinCandidateTypeSet::iterator
7331 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7332 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7333 Enum != EnumEnd; ++Enum) {
7334 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7335 continue;
7336
7337 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7338 continue;
7339
7340 QualType ParamTypes[2] = { *Enum, *Enum };
7341 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7342 }
7343 }
7344 }
7345 }
7346};
7347
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007348} // end anonymous namespace
7349
7350/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7351/// operator overloads to the candidate set (C++ [over.built]), based
7352/// on the operator @p Op and the arguments given. For example, if the
7353/// operator is a binary '+', this routine might add "int
7354/// operator+(int, int)" to cover integer addition.
7355void
7356Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7357 SourceLocation OpLoc,
7358 Expr **Args, unsigned NumArgs,
7359 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007360 // Find all of the types that the arguments can convert to, but only
7361 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007362 // that make use of these types. Also record whether we encounter non-record
7363 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007364 Qualifiers VisibleTypeConversionsQuals;
7365 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007366 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7367 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007368
7369 bool HasNonRecordCandidateType = false;
7370 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007371 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007372 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7373 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7374 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7375 OpLoc,
7376 true,
7377 (Op == OO_Exclaim ||
7378 Op == OO_AmpAmp ||
7379 Op == OO_PipePipe),
7380 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007381 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7382 CandidateTypes[ArgIdx].hasNonRecordTypes();
7383 HasArithmeticOrEnumeralCandidateType =
7384 HasArithmeticOrEnumeralCandidateType ||
7385 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007386 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007387
Chandler Carruth6a577462010-12-13 01:44:01 +00007388 // Exit early when no non-record types have been added to the candidate set
7389 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007390 //
7391 // We can't exit early for !, ||, or &&, since there we have always have
7392 // 'bool' overloads.
7393 if (!HasNonRecordCandidateType &&
7394 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007395 return;
7396
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007397 // Setup an object to manage the common state for building overloads.
7398 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7399 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007400 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007401 CandidateTypes, CandidateSet);
7402
7403 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007404 switch (Op) {
7405 case OO_None:
7406 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007407 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007408
Chandler Carruthabb71842010-12-12 08:51:33 +00007409 case OO_New:
7410 case OO_Delete:
7411 case OO_Array_New:
7412 case OO_Array_Delete:
7413 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007414 llvm_unreachable(
7415 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007416
7417 case OO_Comma:
7418 case OO_Arrow:
7419 // C++ [over.match.oper]p3:
7420 // -- For the operator ',', the unary operator '&', or the
7421 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007422 break;
7423
7424 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007425 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007426 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007427 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007428
7429 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007430 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007431 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007432 } else {
7433 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7434 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7435 }
Douglas Gregor74253732008-11-19 15:42:04 +00007436 break;
7437
Chandler Carruthabb71842010-12-12 08:51:33 +00007438 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007439 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007440 OpBuilder.addUnaryStarPointerOverloads();
7441 else
7442 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7443 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007444
Chandler Carruthabb71842010-12-12 08:51:33 +00007445 case OO_Slash:
7446 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007447 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007448
7449 case OO_PlusPlus:
7450 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007451 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7452 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007453 break;
7454
Douglas Gregor19b7b152009-08-24 13:43:27 +00007455 case OO_EqualEqual:
7456 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007457 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007458 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007459
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007460 case OO_Less:
7461 case OO_Greater:
7462 case OO_LessEqual:
7463 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007464 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007465 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7466 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007467
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007468 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007469 case OO_Caret:
7470 case OO_Pipe:
7471 case OO_LessLess:
7472 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007473 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007474 break;
7475
Chandler Carruthabb71842010-12-12 08:51:33 +00007476 case OO_Amp: // '&' is either unary or binary
7477 if (NumArgs == 1)
7478 // C++ [over.match.oper]p3:
7479 // -- For the operator ',', the unary operator '&', or the
7480 // operator '->', the built-in candidates set is empty.
7481 break;
7482
7483 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7484 break;
7485
7486 case OO_Tilde:
7487 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7488 break;
7489
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007490 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007491 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007492 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007493
7494 case OO_PlusEqual:
7495 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007496 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007497 // Fall through.
7498
7499 case OO_StarEqual:
7500 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007501 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007502 break;
7503
7504 case OO_PercentEqual:
7505 case OO_LessLessEqual:
7506 case OO_GreaterGreaterEqual:
7507 case OO_AmpEqual:
7508 case OO_CaretEqual:
7509 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007510 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007511 break;
7512
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007513 case OO_Exclaim:
7514 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007515 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007516
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007517 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007518 case OO_PipePipe:
7519 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007520 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007521
7522 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007523 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007524 break;
7525
7526 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007527 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007528 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007529
7530 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007531 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007532 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7533 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007534 }
7535}
7536
Douglas Gregorfa047642009-02-04 00:32:51 +00007537/// \brief Add function candidates found via argument-dependent lookup
7538/// to the set of overloading candidates.
7539///
7540/// This routine performs argument-dependent name lookup based on the
7541/// given function name (which may also be an operator name) and adds
7542/// all of the overload candidates found by ADL to the overload
7543/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007544void
Douglas Gregorfa047642009-02-04 00:32:51 +00007545Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007546 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007547 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007548 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007549 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007550 bool PartialOverloading,
7551 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007552 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007553
John McCalla113e722010-01-26 06:04:06 +00007554 // FIXME: This approach for uniquing ADL results (and removing
7555 // redundant candidates from the set) relies on pointer-equality,
7556 // which means we need to key off the canonical decl. However,
7557 // always going back to the canonical decl might not get us the
7558 // right set of default arguments. What default arguments are
7559 // we supposed to consider on ADL candidates, anyway?
7560
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007561 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007562 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007563 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007564
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007565 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007566 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7567 CandEnd = CandidateSet.end();
7568 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007569 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007570 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007571 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007572 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007573 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007574
7575 // For each of the ADL candidates we found, add it to the overload
7576 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007577 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007578 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007579 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007580 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007581 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007582
Ahmed Charles13a140c2012-02-25 11:00:22 +00007583 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7584 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007585 } else
John McCall6e266892010-01-26 03:27:55 +00007586 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007587 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007588 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007589 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007590}
7591
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007592/// isBetterOverloadCandidate - Determines whether the first overload
7593/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007594bool
John McCall120d63c2010-08-24 20:38:10 +00007595isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007596 const OverloadCandidate &Cand1,
7597 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007598 SourceLocation Loc,
7599 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007600 // Define viable functions to be better candidates than non-viable
7601 // functions.
7602 if (!Cand2.Viable)
7603 return Cand1.Viable;
7604 else if (!Cand1.Viable)
7605 return false;
7606
Douglas Gregor88a35142008-12-22 05:46:06 +00007607 // C++ [over.match.best]p1:
7608 //
7609 // -- if F is a static member function, ICS1(F) is defined such
7610 // that ICS1(F) is neither better nor worse than ICS1(G) for
7611 // any function G, and, symmetrically, ICS1(G) is neither
7612 // better nor worse than ICS1(F).
7613 unsigned StartArg = 0;
7614 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7615 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007616
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007617 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007618 // A viable function F1 is defined to be a better function than another
7619 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007620 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007621 unsigned NumArgs = Cand1.NumConversions;
7622 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007623 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007624 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007625 switch (CompareImplicitConversionSequences(S,
7626 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007627 Cand2.Conversions[ArgIdx])) {
7628 case ImplicitConversionSequence::Better:
7629 // Cand1 has a better conversion sequence.
7630 HasBetterConversion = true;
7631 break;
7632
7633 case ImplicitConversionSequence::Worse:
7634 // Cand1 can't be better than Cand2.
7635 return false;
7636
7637 case ImplicitConversionSequence::Indistinguishable:
7638 // Do nothing.
7639 break;
7640 }
7641 }
7642
Mike Stump1eb44332009-09-09 15:08:12 +00007643 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007644 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007645 if (HasBetterConversion)
7646 return true;
7647
Mike Stump1eb44332009-09-09 15:08:12 +00007648 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007649 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007650 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007651 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7652 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007653
7654 // -- F1 and F2 are function template specializations, and the function
7655 // template for F1 is more specialized than the template for F2
7656 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007657 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007658 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007659 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007660 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007661 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7662 Cand2.Function->getPrimaryTemplate(),
7663 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007664 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007665 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007666 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007667 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007668 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007669
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007670 // -- the context is an initialization by user-defined conversion
7671 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7672 // from the return type of F1 to the destination type (i.e.,
7673 // the type of the entity being initialized) is a better
7674 // conversion sequence than the standard conversion sequence
7675 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007676 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007677 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007678 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007679 // First check whether we prefer one of the conversion functions over the
7680 // other. This only distinguishes the results in non-standard, extension
7681 // cases such as the conversion from a lambda closure type to a function
7682 // pointer or block.
7683 ImplicitConversionSequence::CompareKind FuncResult
7684 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7685 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7686 return FuncResult;
7687
John McCall120d63c2010-08-24 20:38:10 +00007688 switch (CompareStandardConversionSequences(S,
7689 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007690 Cand2.FinalConversion)) {
7691 case ImplicitConversionSequence::Better:
7692 // Cand1 has a better conversion sequence.
7693 return true;
7694
7695 case ImplicitConversionSequence::Worse:
7696 // Cand1 can't be better than Cand2.
7697 return false;
7698
7699 case ImplicitConversionSequence::Indistinguishable:
7700 // Do nothing
7701 break;
7702 }
7703 }
7704
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007705 return false;
7706}
7707
Mike Stump1eb44332009-09-09 15:08:12 +00007708/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007709/// within an overload candidate set.
7710///
7711/// \param CandidateSet the set of candidate functions.
7712///
7713/// \param Loc the location of the function name (or operator symbol) for
7714/// which overload resolution occurs.
7715///
Mike Stump1eb44332009-09-09 15:08:12 +00007716/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007717/// function, Best points to the candidate function found.
7718///
7719/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007720OverloadingResult
7721OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007722 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007723 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007724 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007725 Best = end();
7726 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7727 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007728 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007729 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007730 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007731 }
7732
7733 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007734 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007735 return OR_No_Viable_Function;
7736
7737 // Make sure that this function is better than every other viable
7738 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007739 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007740 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007741 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007742 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007743 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007744 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007745 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007746 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007747 }
Mike Stump1eb44332009-09-09 15:08:12 +00007748
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007749 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007750 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007751 (Best->Function->isDeleted() ||
7752 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007753 return OR_Deleted;
7754
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007755 return OR_Success;
7756}
7757
John McCall3c80f572010-01-12 02:15:36 +00007758namespace {
7759
7760enum OverloadCandidateKind {
7761 oc_function,
7762 oc_method,
7763 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007764 oc_function_template,
7765 oc_method_template,
7766 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007767 oc_implicit_default_constructor,
7768 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007769 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007770 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007771 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007772 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007773};
7774
John McCall220ccbf2010-01-13 00:25:19 +00007775OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7776 FunctionDecl *Fn,
7777 std::string &Description) {
7778 bool isTemplate = false;
7779
7780 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7781 isTemplate = true;
7782 Description = S.getTemplateArgumentBindingsText(
7783 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7784 }
John McCallb1622a12010-01-06 09:43:14 +00007785
7786 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007787 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007788 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007789
Sebastian Redlf677ea32011-02-05 19:23:19 +00007790 if (Ctor->getInheritedConstructor())
7791 return oc_implicit_inherited_constructor;
7792
Sean Hunt82713172011-05-25 23:16:36 +00007793 if (Ctor->isDefaultConstructor())
7794 return oc_implicit_default_constructor;
7795
7796 if (Ctor->isMoveConstructor())
7797 return oc_implicit_move_constructor;
7798
7799 assert(Ctor->isCopyConstructor() &&
7800 "unexpected sort of implicit constructor");
7801 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007802 }
7803
7804 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7805 // This actually gets spelled 'candidate function' for now, but
7806 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007807 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007808 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007809
Sean Hunt82713172011-05-25 23:16:36 +00007810 if (Meth->isMoveAssignmentOperator())
7811 return oc_implicit_move_assignment;
7812
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007813 if (Meth->isCopyAssignmentOperator())
7814 return oc_implicit_copy_assignment;
7815
7816 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7817 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007818 }
7819
John McCall220ccbf2010-01-13 00:25:19 +00007820 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007821}
7822
Sebastian Redlf677ea32011-02-05 19:23:19 +00007823void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7824 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7825 if (!Ctor) return;
7826
7827 Ctor = Ctor->getInheritedConstructor();
7828 if (!Ctor) return;
7829
7830 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7831}
7832
John McCall3c80f572010-01-12 02:15:36 +00007833} // end anonymous namespace
7834
7835// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007836void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007837 std::string FnDesc;
7838 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007839 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7840 << (unsigned) K << FnDesc;
7841 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7842 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007843 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007844}
7845
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007846//Notes the location of all overload candidates designated through
7847// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007848void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007849 assert(OverloadedExpr->getType() == Context.OverloadTy);
7850
7851 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7852 OverloadExpr *OvlExpr = Ovl.Expression;
7853
7854 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7855 IEnd = OvlExpr->decls_end();
7856 I != IEnd; ++I) {
7857 if (FunctionTemplateDecl *FunTmpl =
7858 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007859 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007860 } else if (FunctionDecl *Fun
7861 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007862 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007863 }
7864 }
7865}
7866
John McCall1d318332010-01-12 00:44:57 +00007867/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7868/// "lead" diagnostic; it will be given two arguments, the source and
7869/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007870void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7871 Sema &S,
7872 SourceLocation CaretLoc,
7873 const PartialDiagnostic &PDiag) const {
7874 S.Diag(CaretLoc, PDiag)
7875 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007876 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007877 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7878 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007879 }
John McCall81201622010-01-08 04:41:39 +00007880}
7881
John McCall1d318332010-01-12 00:44:57 +00007882namespace {
7883
John McCalladbb8f82010-01-13 09:16:55 +00007884void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7885 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7886 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007887 assert(Cand->Function && "for now, candidate must be a function");
7888 FunctionDecl *Fn = Cand->Function;
7889
7890 // There's a conversion slot for the object argument if this is a
7891 // non-constructor method. Note that 'I' corresponds the
7892 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007893 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007894 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007895 if (I == 0)
7896 isObjectArgument = true;
7897 else
7898 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007899 }
7900
John McCall220ccbf2010-01-13 00:25:19 +00007901 std::string FnDesc;
7902 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7903
John McCalladbb8f82010-01-13 09:16:55 +00007904 Expr *FromExpr = Conv.Bad.FromExpr;
7905 QualType FromTy = Conv.Bad.getFromType();
7906 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007907
John McCall5920dbb2010-02-02 02:42:52 +00007908 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007909 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007910 Expr *E = FromExpr->IgnoreParens();
7911 if (isa<UnaryOperator>(E))
7912 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007913 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007914
7915 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7916 << (unsigned) FnKind << FnDesc
7917 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7918 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007919 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007920 return;
7921 }
7922
John McCall258b2032010-01-23 08:10:49 +00007923 // Do some hand-waving analysis to see if the non-viability is due
7924 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007925 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7926 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7927 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7928 CToTy = RT->getPointeeType();
7929 else {
7930 // TODO: detect and diagnose the full richness of const mismatches.
7931 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7932 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7933 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7934 }
7935
7936 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7937 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00007938 Qualifiers FromQs = CFromTy.getQualifiers();
7939 Qualifiers ToQs = CToTy.getQualifiers();
7940
7941 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7942 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7943 << (unsigned) FnKind << FnDesc
7944 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7945 << FromTy
7946 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7947 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007948 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007949 return;
7950 }
7951
John McCallf85e1932011-06-15 23:02:42 +00007952 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007953 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007954 << (unsigned) FnKind << FnDesc
7955 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7956 << FromTy
7957 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7958 << (unsigned) isObjectArgument << I+1;
7959 MaybeEmitInheritedConstructorNote(S, Fn);
7960 return;
7961 }
7962
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007963 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7964 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7965 << (unsigned) FnKind << FnDesc
7966 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7967 << FromTy
7968 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7969 << (unsigned) isObjectArgument << I+1;
7970 MaybeEmitInheritedConstructorNote(S, Fn);
7971 return;
7972 }
7973
John McCall651f3ee2010-01-14 03:28:57 +00007974 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7975 assert(CVR && "unexpected qualifiers mismatch");
7976
7977 if (isObjectArgument) {
7978 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7979 << (unsigned) FnKind << FnDesc
7980 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7981 << FromTy << (CVR - 1);
7982 } else {
7983 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7984 << (unsigned) FnKind << FnDesc
7985 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7986 << FromTy << (CVR - 1) << I+1;
7987 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007988 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007989 return;
7990 }
7991
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007992 // Special diagnostic for failure to convert an initializer list, since
7993 // telling the user that it has type void is not useful.
7994 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7995 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7996 << (unsigned) FnKind << FnDesc
7997 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7998 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7999 MaybeEmitInheritedConstructorNote(S, Fn);
8000 return;
8001 }
8002
John McCall258b2032010-01-23 08:10:49 +00008003 // Diagnose references or pointers to incomplete types differently,
8004 // since it's far from impossible that the incompleteness triggered
8005 // the failure.
8006 QualType TempFromTy = FromTy.getNonReferenceType();
8007 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8008 TempFromTy = PTy->getPointeeType();
8009 if (TempFromTy->isIncompleteType()) {
8010 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8011 << (unsigned) FnKind << FnDesc
8012 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8013 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008014 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008015 return;
8016 }
8017
Douglas Gregor85789812010-06-30 23:01:39 +00008018 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008019 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008020 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8021 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8022 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8023 FromPtrTy->getPointeeType()) &&
8024 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8025 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008026 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008027 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008028 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008029 }
8030 } else if (const ObjCObjectPointerType *FromPtrTy
8031 = FromTy->getAs<ObjCObjectPointerType>()) {
8032 if (const ObjCObjectPointerType *ToPtrTy
8033 = ToTy->getAs<ObjCObjectPointerType>())
8034 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8035 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8036 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8037 FromPtrTy->getPointeeType()) &&
8038 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008039 BaseToDerivedConversion = 2;
8040 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
8041 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8042 !FromTy->isIncompleteType() &&
8043 !ToRefTy->getPointeeType()->isIncompleteType() &&
8044 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
8045 BaseToDerivedConversion = 3;
8046 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008047
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008048 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008049 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008050 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008051 << (unsigned) FnKind << FnDesc
8052 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008053 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008054 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008055 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008056 return;
8057 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008058
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008059 if (isa<ObjCObjectPointerType>(CFromTy) &&
8060 isa<PointerType>(CToTy)) {
8061 Qualifiers FromQs = CFromTy.getQualifiers();
8062 Qualifiers ToQs = CToTy.getQualifiers();
8063 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8064 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8065 << (unsigned) FnKind << FnDesc
8066 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8067 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8068 MaybeEmitInheritedConstructorNote(S, Fn);
8069 return;
8070 }
8071 }
8072
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008073 // Emit the generic diagnostic and, optionally, add the hints to it.
8074 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8075 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008076 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008077 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8078 << (unsigned) (Cand->Fix.Kind);
8079
8080 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008081 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8082 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008083 FDiag << *HI;
8084 S.Diag(Fn->getLocation(), FDiag);
8085
Sebastian Redlf677ea32011-02-05 19:23:19 +00008086 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008087}
8088
8089void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8090 unsigned NumFormalArgs) {
8091 // TODO: treat calls to a missing default constructor as a special case
8092
8093 FunctionDecl *Fn = Cand->Function;
8094 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8095
8096 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008097
Douglas Gregor439d3c32011-05-05 00:13:13 +00008098 // With invalid overloaded operators, it's possible that we think we
8099 // have an arity mismatch when it fact it looks like we have the
8100 // right number of arguments, because only overloaded operators have
8101 // the weird behavior of overloading member and non-member functions.
8102 // Just don't report anything.
8103 if (Fn->isInvalidDecl() &&
8104 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8105 return;
8106
John McCalladbb8f82010-01-13 09:16:55 +00008107 // at least / at most / exactly
8108 unsigned mode, modeCount;
8109 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008110 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8111 (Cand->FailureKind == ovl_fail_bad_deduction &&
8112 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008113 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008114 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008115 mode = 0; // "at least"
8116 else
8117 mode = 2; // "exactly"
8118 modeCount = MinParams;
8119 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008120 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8121 (Cand->FailureKind == ovl_fail_bad_deduction &&
8122 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008123 if (MinParams != FnTy->getNumArgs())
8124 mode = 1; // "at most"
8125 else
8126 mode = 2; // "exactly"
8127 modeCount = FnTy->getNumArgs();
8128 }
8129
8130 std::string Description;
8131 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8132
8133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008134 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00008135 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008136 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008137}
8138
John McCall342fec42010-02-01 18:53:26 +00008139/// Diagnose a failed template-argument deduction.
8140void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008141 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008142 FunctionDecl *Fn = Cand->Function; // pattern
8143
Douglas Gregora9333192010-05-08 17:41:32 +00008144 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008145 NamedDecl *ParamD;
8146 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8147 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8148 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008149 switch (Cand->DeductionFailure.Result) {
8150 case Sema::TDK_Success:
8151 llvm_unreachable("TDK_success while diagnosing bad deduction");
8152
8153 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008154 assert(ParamD && "no parameter found for incomplete deduction result");
8155 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8156 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008157 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008158 return;
8159 }
8160
John McCall57e97782010-08-05 09:05:08 +00008161 case Sema::TDK_Underqualified: {
8162 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8163 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8164
8165 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8166
8167 // Param will have been canonicalized, but it should just be a
8168 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008169 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008170 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008171 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008172 assert(S.Context.hasSameType(Param, NonCanonParam));
8173
8174 // Arg has also been canonicalized, but there's nothing we can do
8175 // about that. It also doesn't matter as much, because it won't
8176 // have any template parameters in it (because deduction isn't
8177 // done on dependent types).
8178 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8179
8180 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8181 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008182 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008183 return;
8184 }
8185
8186 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008187 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008188 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008189 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008190 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008191 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008192 which = 1;
8193 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008194 which = 2;
8195 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008196
Douglas Gregora9333192010-05-08 17:41:32 +00008197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008198 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008199 << *Cand->DeductionFailure.getFirstArg()
8200 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008201 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008202 return;
8203 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008204
Douglas Gregorf1a84452010-05-08 19:15:54 +00008205 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008206 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008207 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008208 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008209 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8210 << ParamD->getDeclName();
8211 else {
8212 int index = 0;
8213 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8214 index = TTP->getIndex();
8215 else if (NonTypeTemplateParmDecl *NTTP
8216 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8217 index = NTTP->getIndex();
8218 else
8219 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008220 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008221 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8222 << (index + 1);
8223 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008224 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008225 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008226
Douglas Gregora18592e2010-05-08 18:13:28 +00008227 case Sema::TDK_TooManyArguments:
8228 case Sema::TDK_TooFewArguments:
8229 DiagnoseArityMismatch(S, Cand, NumArgs);
8230 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008231
8232 case Sema::TDK_InstantiationDepth:
8233 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008234 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008235 return;
8236
8237 case Sema::TDK_SubstitutionFailure: {
8238 std::string ArgString;
8239 if (TemplateArgumentList *Args
8240 = Cand->DeductionFailure.getTemplateArgumentList())
8241 ArgString = S.getTemplateArgumentBindingsText(
8242 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8243 *Args);
8244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8245 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008246 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008247 return;
8248 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008249
John McCall342fec42010-02-01 18:53:26 +00008250 // TODO: diagnose these individually, then kill off
8251 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008252 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008253 case Sema::TDK_FailedOverloadResolution:
8254 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008255 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008256 return;
8257 }
8258}
8259
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008260/// CUDA: diagnose an invalid call across targets.
8261void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8262 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8263 FunctionDecl *Callee = Cand->Function;
8264
8265 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8266 CalleeTarget = S.IdentifyCUDATarget(Callee);
8267
8268 std::string FnDesc;
8269 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8270
8271 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8272 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8273}
8274
John McCall342fec42010-02-01 18:53:26 +00008275/// Generates a 'note' diagnostic for an overload candidate. We've
8276/// already generated a primary error at the call site.
8277///
8278/// It really does need to be a single diagnostic with its caret
8279/// pointed at the candidate declaration. Yes, this creates some
8280/// major challenges of technical writing. Yes, this makes pointing
8281/// out problems with specific arguments quite awkward. It's still
8282/// better than generating twenty screens of text for every failed
8283/// overload.
8284///
8285/// It would be great to be able to express per-candidate problems
8286/// more richly for those diagnostic clients that cared, but we'd
8287/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008288void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008289 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008290 FunctionDecl *Fn = Cand->Function;
8291
John McCall81201622010-01-08 04:41:39 +00008292 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008293 if (Cand->Viable && (Fn->isDeleted() ||
8294 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008295 std::string FnDesc;
8296 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008297
8298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008299 << FnKind << FnDesc
8300 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008301 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008302 return;
John McCall81201622010-01-08 04:41:39 +00008303 }
8304
John McCall220ccbf2010-01-13 00:25:19 +00008305 // We don't really have anything else to say about viable candidates.
8306 if (Cand->Viable) {
8307 S.NoteOverloadCandidate(Fn);
8308 return;
8309 }
John McCall1d318332010-01-12 00:44:57 +00008310
John McCalladbb8f82010-01-13 09:16:55 +00008311 switch (Cand->FailureKind) {
8312 case ovl_fail_too_many_arguments:
8313 case ovl_fail_too_few_arguments:
8314 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008315
John McCalladbb8f82010-01-13 09:16:55 +00008316 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008317 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008318
John McCall717e8912010-01-23 05:17:32 +00008319 case ovl_fail_trivial_conversion:
8320 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008321 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008322 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008323
John McCallb1bdc622010-02-25 01:37:24 +00008324 case ovl_fail_bad_conversion: {
8325 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008326 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008327 if (Cand->Conversions[I].isBad())
8328 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008329
John McCalladbb8f82010-01-13 09:16:55 +00008330 // FIXME: this currently happens when we're called from SemaInit
8331 // when user-conversion overload fails. Figure out how to handle
8332 // those conditions and diagnose them well.
8333 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008334 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008335
8336 case ovl_fail_bad_target:
8337 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008338 }
John McCalla1d7d622010-01-08 00:58:21 +00008339}
8340
8341void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8342 // Desugar the type of the surrogate down to a function type,
8343 // retaining as many typedefs as possible while still showing
8344 // the function type (and, therefore, its parameter types).
8345 QualType FnType = Cand->Surrogate->getConversionType();
8346 bool isLValueReference = false;
8347 bool isRValueReference = false;
8348 bool isPointer = false;
8349 if (const LValueReferenceType *FnTypeRef =
8350 FnType->getAs<LValueReferenceType>()) {
8351 FnType = FnTypeRef->getPointeeType();
8352 isLValueReference = true;
8353 } else if (const RValueReferenceType *FnTypeRef =
8354 FnType->getAs<RValueReferenceType>()) {
8355 FnType = FnTypeRef->getPointeeType();
8356 isRValueReference = true;
8357 }
8358 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8359 FnType = FnTypePtr->getPointeeType();
8360 isPointer = true;
8361 }
8362 // Desugar down to a function type.
8363 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8364 // Reconstruct the pointer/reference as appropriate.
8365 if (isPointer) FnType = S.Context.getPointerType(FnType);
8366 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8367 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8368
8369 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8370 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008371 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008372}
8373
8374void NoteBuiltinOperatorCandidate(Sema &S,
8375 const char *Opc,
8376 SourceLocation OpLoc,
8377 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008378 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008379 std::string TypeStr("operator");
8380 TypeStr += Opc;
8381 TypeStr += "(";
8382 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008383 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008384 TypeStr += ")";
8385 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8386 } else {
8387 TypeStr += ", ";
8388 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8389 TypeStr += ")";
8390 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8391 }
8392}
8393
8394void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8395 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008396 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008397 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8398 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008399 if (ICS.isBad()) break; // all meaningless after first invalid
8400 if (!ICS.isAmbiguous()) continue;
8401
John McCall120d63c2010-08-24 20:38:10 +00008402 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008403 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008404 }
8405}
8406
John McCall1b77e732010-01-15 23:32:50 +00008407SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8408 if (Cand->Function)
8409 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008410 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008411 return Cand->Surrogate->getLocation();
8412 return SourceLocation();
8413}
8414
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008415static unsigned
8416RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008417 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008418 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008419 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008420
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008421 case Sema::TDK_Incomplete:
8422 return 1;
8423
8424 case Sema::TDK_Underqualified:
8425 case Sema::TDK_Inconsistent:
8426 return 2;
8427
8428 case Sema::TDK_SubstitutionFailure:
8429 case Sema::TDK_NonDeducedMismatch:
8430 return 3;
8431
8432 case Sema::TDK_InstantiationDepth:
8433 case Sema::TDK_FailedOverloadResolution:
8434 return 4;
8435
8436 case Sema::TDK_InvalidExplicitArguments:
8437 return 5;
8438
8439 case Sema::TDK_TooManyArguments:
8440 case Sema::TDK_TooFewArguments:
8441 return 6;
8442 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008443 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008444}
8445
John McCallbf65c0b2010-01-12 00:48:53 +00008446struct CompareOverloadCandidatesForDisplay {
8447 Sema &S;
8448 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008449
8450 bool operator()(const OverloadCandidate *L,
8451 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008452 // Fast-path this check.
8453 if (L == R) return false;
8454
John McCall81201622010-01-08 04:41:39 +00008455 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008456 if (L->Viable) {
8457 if (!R->Viable) return true;
8458
8459 // TODO: introduce a tri-valued comparison for overload
8460 // candidates. Would be more worthwhile if we had a sort
8461 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008462 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8463 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008464 } else if (R->Viable)
8465 return false;
John McCall81201622010-01-08 04:41:39 +00008466
John McCall1b77e732010-01-15 23:32:50 +00008467 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008468
John McCall1b77e732010-01-15 23:32:50 +00008469 // Criteria by which we can sort non-viable candidates:
8470 if (!L->Viable) {
8471 // 1. Arity mismatches come after other candidates.
8472 if (L->FailureKind == ovl_fail_too_many_arguments ||
8473 L->FailureKind == ovl_fail_too_few_arguments)
8474 return false;
8475 if (R->FailureKind == ovl_fail_too_many_arguments ||
8476 R->FailureKind == ovl_fail_too_few_arguments)
8477 return true;
John McCall81201622010-01-08 04:41:39 +00008478
John McCall717e8912010-01-23 05:17:32 +00008479 // 2. Bad conversions come first and are ordered by the number
8480 // of bad conversions and quality of good conversions.
8481 if (L->FailureKind == ovl_fail_bad_conversion) {
8482 if (R->FailureKind != ovl_fail_bad_conversion)
8483 return true;
8484
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008485 // The conversion that can be fixed with a smaller number of changes,
8486 // comes first.
8487 unsigned numLFixes = L->Fix.NumConversionsFixed;
8488 unsigned numRFixes = R->Fix.NumConversionsFixed;
8489 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8490 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008491 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008492 if (numLFixes < numRFixes)
8493 return true;
8494 else
8495 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008496 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008497
John McCall717e8912010-01-23 05:17:32 +00008498 // If there's any ordering between the defined conversions...
8499 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008500 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008501
8502 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008503 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008504 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008505 switch (CompareImplicitConversionSequences(S,
8506 L->Conversions[I],
8507 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008508 case ImplicitConversionSequence::Better:
8509 leftBetter++;
8510 break;
8511
8512 case ImplicitConversionSequence::Worse:
8513 leftBetter--;
8514 break;
8515
8516 case ImplicitConversionSequence::Indistinguishable:
8517 break;
8518 }
8519 }
8520 if (leftBetter > 0) return true;
8521 if (leftBetter < 0) return false;
8522
8523 } else if (R->FailureKind == ovl_fail_bad_conversion)
8524 return false;
8525
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008526 if (L->FailureKind == ovl_fail_bad_deduction) {
8527 if (R->FailureKind != ovl_fail_bad_deduction)
8528 return true;
8529
8530 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8531 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008532 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008533 } else if (R->FailureKind == ovl_fail_bad_deduction)
8534 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008535
John McCall1b77e732010-01-15 23:32:50 +00008536 // TODO: others?
8537 }
8538
8539 // Sort everything else by location.
8540 SourceLocation LLoc = GetLocationForCandidate(L);
8541 SourceLocation RLoc = GetLocationForCandidate(R);
8542
8543 // Put candidates without locations (e.g. builtins) at the end.
8544 if (LLoc.isInvalid()) return false;
8545 if (RLoc.isInvalid()) return true;
8546
8547 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008548 }
8549};
8550
John McCall717e8912010-01-23 05:17:32 +00008551/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008552/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008553void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008554 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008555 assert(!Cand->Viable);
8556
8557 // Don't do anything on failures other than bad conversion.
8558 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8559
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008560 // We only want the FixIts if all the arguments can be corrected.
8561 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008562 // Use a implicit copy initialization to check conversion fixes.
8563 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008564
John McCall717e8912010-01-23 05:17:32 +00008565 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008566 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008567 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008568 while (true) {
8569 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8570 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008571 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008572 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008573 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008574 }
John McCall717e8912010-01-23 05:17:32 +00008575 }
8576
8577 if (ConvIdx == ConvCount)
8578 return;
8579
John McCallb1bdc622010-02-25 01:37:24 +00008580 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8581 "remaining conversion is initialized?");
8582
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008583 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008584 // operation somehow.
8585 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008586
8587 const FunctionProtoType* Proto;
8588 unsigned ArgIdx = ConvIdx;
8589
8590 if (Cand->IsSurrogate) {
8591 QualType ConvType
8592 = Cand->Surrogate->getConversionType().getNonReferenceType();
8593 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8594 ConvType = ConvPtrType->getPointeeType();
8595 Proto = ConvType->getAs<FunctionProtoType>();
8596 ArgIdx--;
8597 } else if (Cand->Function) {
8598 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8599 if (isa<CXXMethodDecl>(Cand->Function) &&
8600 !isa<CXXConstructorDecl>(Cand->Function))
8601 ArgIdx--;
8602 } else {
8603 // Builtin binary operator with a bad first conversion.
8604 assert(ConvCount <= 3);
8605 for (; ConvIdx != ConvCount; ++ConvIdx)
8606 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008607 = TryCopyInitialization(S, Args[ConvIdx],
8608 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008609 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008610 /*InOverloadResolution*/ true,
8611 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008612 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008613 return;
8614 }
8615
8616 // Fill in the rest of the conversions.
8617 unsigned NumArgsInProto = Proto->getNumArgs();
8618 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008619 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008620 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008621 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008622 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008623 /*InOverloadResolution=*/true,
8624 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008625 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008626 // Store the FixIt in the candidate if it exists.
8627 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008628 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008629 }
John McCall717e8912010-01-23 05:17:32 +00008630 else
8631 Cand->Conversions[ConvIdx].setEllipsis();
8632 }
8633}
8634
John McCalla1d7d622010-01-08 00:58:21 +00008635} // end anonymous namespace
8636
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008637/// PrintOverloadCandidates - When overload resolution fails, prints
8638/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008639/// set.
John McCall120d63c2010-08-24 20:38:10 +00008640void OverloadCandidateSet::NoteCandidates(Sema &S,
8641 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008642 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008643 const char *Opc,
8644 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008645 // Sort the candidates by viability and position. Sorting directly would
8646 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008647 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008648 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8649 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008650 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008651 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008652 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008653 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008654 if (Cand->Function || Cand->IsSurrogate)
8655 Cands.push_back(Cand);
8656 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8657 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008658 }
8659 }
8660
John McCallbf65c0b2010-01-12 00:48:53 +00008661 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008662 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008663
John McCall1d318332010-01-12 00:44:57 +00008664 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008665
Chris Lattner5f9e2722011-07-23 10:55:15 +00008666 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008667 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8668 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008669 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008670 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8671 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008672
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008673 // Set an arbitrary limit on the number of candidate functions we'll spam
8674 // the user with. FIXME: This limit should depend on details of the
8675 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008676 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008677 break;
8678 }
8679 ++CandsShown;
8680
John McCalla1d7d622010-01-08 00:58:21 +00008681 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008682 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008683 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008684 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008685 else {
8686 assert(Cand->Viable &&
8687 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008688 // Generally we only see ambiguities including viable builtin
8689 // operators if overload resolution got screwed up by an
8690 // ambiguous user-defined conversion.
8691 //
8692 // FIXME: It's quite possible for different conversions to see
8693 // different ambiguities, though.
8694 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008695 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008696 ReportedAmbiguousConversions = true;
8697 }
John McCalla1d7d622010-01-08 00:58:21 +00008698
John McCall1d318332010-01-12 00:44:57 +00008699 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008700 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008701 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008702 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008703
8704 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008705 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008706}
8707
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008708// [PossiblyAFunctionType] --> [Return]
8709// NonFunctionType --> NonFunctionType
8710// R (A) --> R(A)
8711// R (*)(A) --> R (A)
8712// R (&)(A) --> R (A)
8713// R (S::*)(A) --> R (A)
8714QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8715 QualType Ret = PossiblyAFunctionType;
8716 if (const PointerType *ToTypePtr =
8717 PossiblyAFunctionType->getAs<PointerType>())
8718 Ret = ToTypePtr->getPointeeType();
8719 else if (const ReferenceType *ToTypeRef =
8720 PossiblyAFunctionType->getAs<ReferenceType>())
8721 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008722 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008723 PossiblyAFunctionType->getAs<MemberPointerType>())
8724 Ret = MemTypePtr->getPointeeType();
8725 Ret =
8726 Context.getCanonicalType(Ret).getUnqualifiedType();
8727 return Ret;
8728}
Douglas Gregor904eed32008-11-10 20:40:00 +00008729
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008730// A helper class to help with address of function resolution
8731// - allows us to avoid passing around all those ugly parameters
8732class AddressOfFunctionResolver
8733{
8734 Sema& S;
8735 Expr* SourceExpr;
8736 const QualType& TargetType;
8737 QualType TargetFunctionType; // Extracted function type from target type
8738
8739 bool Complain;
8740 //DeclAccessPair& ResultFunctionAccessPair;
8741 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008742
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008743 bool TargetTypeIsNonStaticMemberFunction;
8744 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008745
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008746 OverloadExpr::FindResult OvlExprInfo;
8747 OverloadExpr *OvlExpr;
8748 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008749 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008750
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008751public:
8752 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8753 const QualType& TargetType, bool Complain)
8754 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8755 Complain(Complain), Context(S.getASTContext()),
8756 TargetTypeIsNonStaticMemberFunction(
8757 !!TargetType->getAs<MemberPointerType>()),
8758 FoundNonTemplateFunction(false),
8759 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8760 OvlExpr(OvlExprInfo.Expression)
8761 {
8762 ExtractUnqualifiedFunctionTypeFromTargetType();
8763
8764 if (!TargetFunctionType->isFunctionType()) {
8765 if (OvlExpr->hasExplicitTemplateArgs()) {
8766 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008767 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008768 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008769
8770 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8771 if (!Method->isStatic()) {
8772 // If the target type is a non-function type and the function
8773 // found is a non-static member function, pretend as if that was
8774 // the target, it's the only possible type to end up with.
8775 TargetTypeIsNonStaticMemberFunction = true;
8776
8777 // And skip adding the function if its not in the proper form.
8778 // We'll diagnose this due to an empty set of functions.
8779 if (!OvlExprInfo.HasFormOfMemberPointer)
8780 return;
8781 }
8782 }
8783
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008784 Matches.push_back(std::make_pair(dap,Fn));
8785 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008786 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008787 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008788 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008789
8790 if (OvlExpr->hasExplicitTemplateArgs())
8791 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008792
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008793 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8794 // C++ [over.over]p4:
8795 // If more than one function is selected, [...]
8796 if (Matches.size() > 1) {
8797 if (FoundNonTemplateFunction)
8798 EliminateAllTemplateMatches();
8799 else
8800 EliminateAllExceptMostSpecializedTemplate();
8801 }
8802 }
8803 }
8804
8805private:
8806 bool isTargetTypeAFunction() const {
8807 return TargetFunctionType->isFunctionType();
8808 }
8809
8810 // [ToType] [Return]
8811
8812 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8813 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8814 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8815 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8816 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8817 }
8818
8819 // return true if any matching specializations were found
8820 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8821 const DeclAccessPair& CurAccessFunPair) {
8822 if (CXXMethodDecl *Method
8823 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8824 // Skip non-static function templates when converting to pointer, and
8825 // static when converting to member pointer.
8826 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8827 return false;
8828 }
8829 else if (TargetTypeIsNonStaticMemberFunction)
8830 return false;
8831
8832 // C++ [over.over]p2:
8833 // If the name is a function template, template argument deduction is
8834 // done (14.8.2.2), and if the argument deduction succeeds, the
8835 // resulting template argument list is used to generate a single
8836 // function template specialization, which is added to the set of
8837 // overloaded functions considered.
8838 FunctionDecl *Specialization = 0;
8839 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8840 if (Sema::TemplateDeductionResult Result
8841 = S.DeduceTemplateArguments(FunctionTemplate,
8842 &OvlExplicitTemplateArgs,
8843 TargetFunctionType, Specialization,
8844 Info)) {
8845 // FIXME: make a note of the failed deduction for diagnostics.
8846 (void)Result;
8847 return false;
8848 }
8849
8850 // Template argument deduction ensures that we have an exact match.
8851 // This function template specicalization works.
8852 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8853 assert(TargetFunctionType
8854 == Context.getCanonicalType(Specialization->getType()));
8855 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8856 return true;
8857 }
8858
8859 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8860 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008861 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008862 // Skip non-static functions when converting to pointer, and static
8863 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008864 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8865 return false;
8866 }
8867 else if (TargetTypeIsNonStaticMemberFunction)
8868 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008869
Chandler Carruthbd647292009-12-29 06:17:27 +00008870 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008871 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008872 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8873 if (S.CheckCUDATarget(Caller, FunDecl))
8874 return false;
8875
Douglas Gregor43c79c22009-12-09 00:47:37 +00008876 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008877 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8878 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008879 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8880 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008881 Matches.push_back(std::make_pair(CurAccessFunPair,
8882 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008883 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008884 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008885 }
Mike Stump1eb44332009-09-09 15:08:12 +00008886 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008887
8888 return false;
8889 }
8890
8891 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8892 bool Ret = false;
8893
8894 // If the overload expression doesn't have the form of a pointer to
8895 // member, don't try to convert it to a pointer-to-member type.
8896 if (IsInvalidFormOfPointerToMemberFunction())
8897 return false;
8898
8899 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8900 E = OvlExpr->decls_end();
8901 I != E; ++I) {
8902 // Look through any using declarations to find the underlying function.
8903 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8904
8905 // C++ [over.over]p3:
8906 // Non-member functions and static member functions match
8907 // targets of type "pointer-to-function" or "reference-to-function."
8908 // Nonstatic member functions match targets of
8909 // type "pointer-to-member-function."
8910 // Note that according to DR 247, the containing class does not matter.
8911 if (FunctionTemplateDecl *FunctionTemplate
8912 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8913 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8914 Ret = true;
8915 }
8916 // If we have explicit template arguments supplied, skip non-templates.
8917 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8918 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8919 Ret = true;
8920 }
8921 assert(Ret || Matches.empty());
8922 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008923 }
8924
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008925 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008926 // [...] and any given function template specialization F1 is
8927 // eliminated if the set contains a second function template
8928 // specialization whose function template is more specialized
8929 // than the function template of F1 according to the partial
8930 // ordering rules of 14.5.5.2.
8931
8932 // The algorithm specified above is quadratic. We instead use a
8933 // two-pass algorithm (similar to the one used to identify the
8934 // best viable function in an overload set) that identifies the
8935 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008936
8937 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8938 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8939 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008940
John McCallc373d482010-01-27 01:50:18 +00008941 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008942 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8943 TPOC_Other, 0, SourceExpr->getLocStart(),
8944 S.PDiag(),
8945 S.PDiag(diag::err_addr_ovl_ambiguous)
8946 << Matches[0].second->getDeclName(),
8947 S.PDiag(diag::note_ovl_candidate)
8948 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008949 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008950
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008951 if (Result != MatchesCopy.end()) {
8952 // Make it the first and only element
8953 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8954 Matches[0].second = cast<FunctionDecl>(*Result);
8955 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008956 }
8957 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008958
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008959 void EliminateAllTemplateMatches() {
8960 // [...] any function template specializations in the set are
8961 // eliminated if the set also contains a non-template function, [...]
8962 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8963 if (Matches[I].second->getPrimaryTemplate() == 0)
8964 ++I;
8965 else {
8966 Matches[I] = Matches[--N];
8967 Matches.set_size(N);
8968 }
8969 }
8970 }
8971
8972public:
8973 void ComplainNoMatchesFound() const {
8974 assert(Matches.empty());
8975 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8976 << OvlExpr->getName() << TargetFunctionType
8977 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008978 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008979 }
8980
8981 bool IsInvalidFormOfPointerToMemberFunction() const {
8982 return TargetTypeIsNonStaticMemberFunction &&
8983 !OvlExprInfo.HasFormOfMemberPointer;
8984 }
8985
8986 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8987 // TODO: Should we condition this on whether any functions might
8988 // have matched, or is it more appropriate to do that in callers?
8989 // TODO: a fixit wouldn't hurt.
8990 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8991 << TargetType << OvlExpr->getSourceRange();
8992 }
8993
8994 void ComplainOfInvalidConversion() const {
8995 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8996 << OvlExpr->getName() << TargetType;
8997 }
8998
8999 void ComplainMultipleMatchesFound() const {
9000 assert(Matches.size() > 1);
9001 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9002 << OvlExpr->getName()
9003 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009004 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009005 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009006
9007 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9008
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009009 int getNumMatches() const { return Matches.size(); }
9010
9011 FunctionDecl* getMatchingFunctionDecl() const {
9012 if (Matches.size() != 1) return 0;
9013 return Matches[0].second;
9014 }
9015
9016 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9017 if (Matches.size() != 1) return 0;
9018 return &Matches[0].first;
9019 }
9020};
9021
9022/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9023/// an overloaded function (C++ [over.over]), where @p From is an
9024/// expression with overloaded function type and @p ToType is the type
9025/// we're trying to resolve to. For example:
9026///
9027/// @code
9028/// int f(double);
9029/// int f(int);
9030///
9031/// int (*pfd)(double) = f; // selects f(double)
9032/// @endcode
9033///
9034/// This routine returns the resulting FunctionDecl if it could be
9035/// resolved, and NULL otherwise. When @p Complain is true, this
9036/// routine will emit diagnostics if there is an error.
9037FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009038Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9039 QualType TargetType,
9040 bool Complain,
9041 DeclAccessPair &FoundResult,
9042 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009043 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009044
9045 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9046 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009047 int NumMatches = Resolver.getNumMatches();
9048 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009049 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009050 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9051 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9052 else
9053 Resolver.ComplainNoMatchesFound();
9054 }
9055 else if (NumMatches > 1 && Complain)
9056 Resolver.ComplainMultipleMatchesFound();
9057 else if (NumMatches == 1) {
9058 Fn = Resolver.getMatchingFunctionDecl();
9059 assert(Fn);
9060 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009061 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009062 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009063 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009064 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009065
9066 if (pHadMultipleCandidates)
9067 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009068 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009069}
9070
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009071/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009072/// resolve that overloaded function expression down to a single function.
9073///
9074/// This routine can only resolve template-ids that refer to a single function
9075/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009076/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009077/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009078FunctionDecl *
9079Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9080 bool Complain,
9081 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009082 // C++ [over.over]p1:
9083 // [...] [Note: any redundant set of parentheses surrounding the
9084 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009085 // C++ [over.over]p1:
9086 // [...] The overloaded function name can be preceded by the &
9087 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009088
Douglas Gregor4b52e252009-12-21 23:17:24 +00009089 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009090 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009091 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009092
9093 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009094 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009095
Douglas Gregor4b52e252009-12-21 23:17:24 +00009096 // Look through all of the overloaded functions, searching for one
9097 // whose type matches exactly.
9098 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009099 for (UnresolvedSetIterator I = ovl->decls_begin(),
9100 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009101 // C++0x [temp.arg.explicit]p3:
9102 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009103 // where deduction is not done, if a template argument list is
9104 // specified and it, along with any default template arguments,
9105 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009106 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009107 FunctionTemplateDecl *FunctionTemplate
9108 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009109
Douglas Gregor4b52e252009-12-21 23:17:24 +00009110 // C++ [over.over]p2:
9111 // If the name is a function template, template argument deduction is
9112 // done (14.8.2.2), and if the argument deduction succeeds, the
9113 // resulting template argument list is used to generate a single
9114 // function template specialization, which is added to the set of
9115 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009116 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009117 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009118 if (TemplateDeductionResult Result
9119 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9120 Specialization, Info)) {
9121 // FIXME: make a note of the failed deduction for diagnostics.
9122 (void)Result;
9123 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009124 }
9125
John McCall864c0412011-04-26 20:42:42 +00009126 assert(Specialization && "no specialization and no error?");
9127
Douglas Gregor4b52e252009-12-21 23:17:24 +00009128 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009129 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009130 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009131 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9132 << ovl->getName();
9133 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009134 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009135 return 0;
John McCall864c0412011-04-26 20:42:42 +00009136 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009137
John McCall864c0412011-04-26 20:42:42 +00009138 Matched = Specialization;
9139 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009140 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009141
Douglas Gregor4b52e252009-12-21 23:17:24 +00009142 return Matched;
9143}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009144
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009145
9146
9147
John McCall6dbba4f2011-10-11 23:14:30 +00009148// Resolve and fix an overloaded expression that can be resolved
9149// because it identifies a single function template specialization.
9150//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009151// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009152//
9153// Return true if it was logically possible to so resolve the
9154// expression, regardless of whether or not it succeeded. Always
9155// returns true if 'complain' is set.
9156bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9157 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9158 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009159 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009160 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009161 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009162
John McCall6dbba4f2011-10-11 23:14:30 +00009163 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009164
John McCall864c0412011-04-26 20:42:42 +00009165 DeclAccessPair found;
9166 ExprResult SingleFunctionExpression;
9167 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9168 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009169 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009170 SrcExpr = ExprError();
9171 return true;
9172 }
John McCall864c0412011-04-26 20:42:42 +00009173
9174 // It is only correct to resolve to an instance method if we're
9175 // resolving a form that's permitted to be a pointer to member.
9176 // Otherwise we'll end up making a bound member expression, which
9177 // is illegal in all the contexts we resolve like this.
9178 if (!ovl.HasFormOfMemberPointer &&
9179 isa<CXXMethodDecl>(fn) &&
9180 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009181 if (!complain) return false;
9182
9183 Diag(ovl.Expression->getExprLoc(),
9184 diag::err_bound_member_function)
9185 << 0 << ovl.Expression->getSourceRange();
9186
9187 // TODO: I believe we only end up here if there's a mix of
9188 // static and non-static candidates (otherwise the expression
9189 // would have 'bound member' type, not 'overload' type).
9190 // Ideally we would note which candidate was chosen and why
9191 // the static candidates were rejected.
9192 SrcExpr = ExprError();
9193 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009194 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009195
John McCall864c0412011-04-26 20:42:42 +00009196 // Fix the expresion to refer to 'fn'.
9197 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009198 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009199
9200 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009201 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009202 SingleFunctionExpression =
9203 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009204 if (SingleFunctionExpression.isInvalid()) {
9205 SrcExpr = ExprError();
9206 return true;
9207 }
9208 }
John McCall864c0412011-04-26 20:42:42 +00009209 }
9210
9211 if (!SingleFunctionExpression.isUsable()) {
9212 if (complain) {
9213 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9214 << ovl.Expression->getName()
9215 << DestTypeForComplaining
9216 << OpRangeForComplaining
9217 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009218 NoteAllOverloadCandidates(SrcExpr.get());
9219
9220 SrcExpr = ExprError();
9221 return true;
9222 }
9223
9224 return false;
John McCall864c0412011-04-26 20:42:42 +00009225 }
9226
John McCall6dbba4f2011-10-11 23:14:30 +00009227 SrcExpr = SingleFunctionExpression;
9228 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009229}
9230
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009231/// \brief Add a single candidate to the overload set.
9232static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009233 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009234 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009235 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009236 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009237 bool PartialOverloading,
9238 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009239 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009240 if (isa<UsingShadowDecl>(Callee))
9241 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9242
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009243 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009244 if (ExplicitTemplateArgs) {
9245 assert(!KnownValid && "Explicit template arguments?");
9246 return;
9247 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009248 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9249 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009250 return;
John McCallba135432009-11-21 08:51:07 +00009251 }
9252
9253 if (FunctionTemplateDecl *FuncTemplate
9254 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009255 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009256 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009257 return;
9258 }
9259
Richard Smith2ced0442011-06-26 22:19:54 +00009260 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009261}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009262
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009263/// \brief Add the overload candidates named by callee and/or found by argument
9264/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009265void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009266 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009267 OverloadCandidateSet &CandidateSet,
9268 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009269
9270#ifndef NDEBUG
9271 // Verify that ArgumentDependentLookup is consistent with the rules
9272 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009273 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009274 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9275 // and let Y be the lookup set produced by argument dependent
9276 // lookup (defined as follows). If X contains
9277 //
9278 // -- a declaration of a class member, or
9279 //
9280 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009281 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009282 //
9283 // -- a declaration that is neither a function or a function
9284 // template
9285 //
9286 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009287
John McCall3b4294e2009-12-16 12:17:52 +00009288 if (ULE->requiresADL()) {
9289 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9290 E = ULE->decls_end(); I != E; ++I) {
9291 assert(!(*I)->getDeclContext()->isRecord());
9292 assert(isa<UsingShadowDecl>(*I) ||
9293 !(*I)->getDeclContext()->isFunctionOrMethod());
9294 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009295 }
9296 }
9297#endif
9298
John McCall3b4294e2009-12-16 12:17:52 +00009299 // It would be nice to avoid this copy.
9300 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009301 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009302 if (ULE->hasExplicitTemplateArgs()) {
9303 ULE->copyTemplateArgumentsInto(TABuffer);
9304 ExplicitTemplateArgs = &TABuffer;
9305 }
9306
9307 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9308 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009309 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9310 CandidateSet, PartialOverloading,
9311 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009312
John McCall3b4294e2009-12-16 12:17:52 +00009313 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009314 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009315 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009316 Args, ExplicitTemplateArgs,
9317 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009318 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009319}
John McCall578b69b2009-12-16 08:11:27 +00009320
Richard Smithf50e88a2011-06-05 22:42:48 +00009321/// Attempt to recover from an ill-formed use of a non-dependent name in a
9322/// template, where the non-dependent name was declared after the template
9323/// was defined. This is common in code written for a compilers which do not
9324/// correctly implement two-stage name lookup.
9325///
9326/// Returns true if a viable candidate was found and a diagnostic was issued.
9327static bool
9328DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9329 const CXXScopeSpec &SS, LookupResult &R,
9330 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009331 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009332 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9333 return false;
9334
9335 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009336 if (DC->isTransparentContext())
9337 continue;
9338
Richard Smithf50e88a2011-06-05 22:42:48 +00009339 SemaRef.LookupQualifiedName(R, DC);
9340
9341 if (!R.empty()) {
9342 R.suppressDiagnostics();
9343
9344 if (isa<CXXRecordDecl>(DC)) {
9345 // Don't diagnose names we find in classes; we get much better
9346 // diagnostics for these from DiagnoseEmptyLookup.
9347 R.clear();
9348 return false;
9349 }
9350
9351 OverloadCandidateSet Candidates(FnLoc);
9352 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9353 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009354 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009355 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009356
9357 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009358 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009359 // No viable functions. Don't bother the user with notes for functions
9360 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009361 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009362 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009363 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009364
9365 // Find the namespaces where ADL would have looked, and suggest
9366 // declaring the function there instead.
9367 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9368 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00009369 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009370 AssociatedNamespaces,
9371 AssociatedClasses);
9372 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009373 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009374 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009375 for (Sema::AssociatedNamespaceSet::iterator
9376 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009377 end = AssociatedNamespaces.end(); it != end; ++it) {
9378 if (!Std->Encloses(*it))
9379 SuggestedNamespaces.insert(*it);
9380 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009381 } else {
9382 // Lacking the 'std::' namespace, use all of the associated namespaces.
9383 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009384 }
9385
9386 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9387 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009388 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009389 SemaRef.Diag(Best->Function->getLocation(),
9390 diag::note_not_found_by_two_phase_lookup)
9391 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009392 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009393 SemaRef.Diag(Best->Function->getLocation(),
9394 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009395 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009396 } else {
9397 // FIXME: It would be useful to list the associated namespaces here,
9398 // but the diagnostics infrastructure doesn't provide a way to produce
9399 // a localized representation of a list of items.
9400 SemaRef.Diag(Best->Function->getLocation(),
9401 diag::note_not_found_by_two_phase_lookup)
9402 << R.getLookupName() << 2;
9403 }
9404
9405 // Try to recover by calling this function.
9406 return true;
9407 }
9408
9409 R.clear();
9410 }
9411
9412 return false;
9413}
9414
9415/// Attempt to recover from ill-formed use of a non-dependent operator in a
9416/// template, where the non-dependent operator was declared after the template
9417/// was defined.
9418///
9419/// Returns true if a viable candidate was found and a diagnostic was issued.
9420static bool
9421DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9422 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009423 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009424 DeclarationName OpName =
9425 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9426 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9427 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009428 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009429}
9430
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009431namespace {
9432// Callback to limit the allowed keywords and to only accept typo corrections
9433// that are keywords or whose decls refer to functions (or template functions)
9434// that accept the given number of arguments.
9435class RecoveryCallCCC : public CorrectionCandidateCallback {
9436 public:
9437 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9438 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009439 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009440 WantRemainingKeywords = false;
9441 }
9442
9443 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9444 if (!candidate.getCorrectionDecl())
9445 return candidate.isKeyword();
9446
9447 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9448 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9449 FunctionDecl *FD = 0;
9450 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9451 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9452 FD = FTD->getTemplatedDecl();
9453 if (!HasExplicitTemplateArgs && !FD) {
9454 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9455 // If the Decl is neither a function nor a template function,
9456 // determine if it is a pointer or reference to a function. If so,
9457 // check against the number of arguments expected for the pointee.
9458 QualType ValType = cast<ValueDecl>(ND)->getType();
9459 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9460 ValType = ValType->getPointeeType();
9461 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9462 if (FPT->getNumArgs() == NumArgs)
9463 return true;
9464 }
9465 }
9466 if (FD && FD->getNumParams() >= NumArgs &&
9467 FD->getMinRequiredArguments() <= NumArgs)
9468 return true;
9469 }
9470 return false;
9471 }
9472
9473 private:
9474 unsigned NumArgs;
9475 bool HasExplicitTemplateArgs;
9476};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009477
9478// Callback that effectively disabled typo correction
9479class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9480 public:
9481 NoTypoCorrectionCCC() {
9482 WantTypeSpecifiers = false;
9483 WantExpressionKeywords = false;
9484 WantCXXNamedCasts = false;
9485 WantRemainingKeywords = false;
9486 }
9487
9488 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9489 return false;
9490 }
9491};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009492}
9493
John McCall578b69b2009-12-16 08:11:27 +00009494/// Attempts to recover from a call where no functions were found.
9495///
9496/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009497static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009498BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009499 UnresolvedLookupExpr *ULE,
9500 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009501 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009502 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009503 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009504
9505 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009506 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009507 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009508
John McCall3b4294e2009-12-16 12:17:52 +00009509 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009510 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009511 if (ULE->hasExplicitTemplateArgs()) {
9512 ULE->copyTemplateArgumentsInto(TABuffer);
9513 ExplicitTemplateArgs = &TABuffer;
9514 }
9515
John McCall578b69b2009-12-16 08:11:27 +00009516 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9517 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009518 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009519 NoTypoCorrectionCCC RejectAll;
9520 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9521 (CorrectionCandidateCallback*)&Validator :
9522 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009523 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009524 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009525 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009526 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009527 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009528 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009529
John McCall3b4294e2009-12-16 12:17:52 +00009530 assert(!R.empty() && "lookup results empty despite recovery");
9531
9532 // Build an implicit member call if appropriate. Just drop the
9533 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009534 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009535 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009536 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9537 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009538 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009539 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009540 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009541 else
9542 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9543
9544 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009545 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009546
9547 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009548 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009549 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009550 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009551 MultiExprArg(Args.data(), Args.size()),
9552 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009553}
Douglas Gregord7a95972010-06-08 17:35:15 +00009554
Douglas Gregorf6b89692008-11-26 05:54:23 +00009555/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009556/// (which eventually refers to the declaration Func) and the call
9557/// arguments Args/NumArgs, attempt to resolve the function call down
9558/// to a specific function. If overload resolution succeeds, returns
9559/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009560/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009561/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009562ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009563Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009564 SourceLocation LParenLoc,
9565 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009566 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009567 Expr *ExecConfig,
9568 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009569#ifndef NDEBUG
9570 if (ULE->requiresADL()) {
9571 // To do ADL, we must have found an unqualified name.
9572 assert(!ULE->getQualifier() && "qualified name with ADL");
9573
9574 // We don't perform ADL for implicit declarations of builtins.
9575 // Verify that this was correctly set up.
9576 FunctionDecl *F;
9577 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9578 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9579 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009580 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009581
John McCall3b4294e2009-12-16 12:17:52 +00009582 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009583 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009584 } else
9585 assert(!ULE->isStdAssociatedNamespace() &&
9586 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009587#endif
9588
John McCall5acb0c92011-10-17 18:40:02 +00009589 UnbridgedCastsSet UnbridgedCasts;
9590 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9591 return ExprError();
9592
John McCall5769d612010-02-08 23:07:23 +00009593 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009594
John McCall3b4294e2009-12-16 12:17:52 +00009595 // Add the functions denoted by the callee to the set of candidate
9596 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009597 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9598 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009599
9600 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009601 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9602 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009603 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009604 // In Microsoft mode, if we are inside a template class member function then
9605 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009606 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009607 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009608 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009609 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009610 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9611 Context.DependentTy, VK_RValue,
9612 RParenLoc);
9613 CE->setTypeDependent(true);
9614 return Owned(CE);
9615 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009616 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9617 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009618 RParenLoc, /*EmptyLookup=*/true,
9619 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009620 }
John McCall578b69b2009-12-16 08:11:27 +00009621
John McCall5acb0c92011-10-17 18:40:02 +00009622 UnbridgedCasts.restore();
9623
Douglas Gregorf6b89692008-11-26 05:54:23 +00009624 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009625 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009626 case OR_Success: {
9627 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009628 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009629 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009630 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009631 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009632 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9633 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009634 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009635
Richard Smithf50e88a2011-06-05 22:42:48 +00009636 case OR_No_Viable_Function: {
9637 // Try to recover by looking for viable functions which the user might
9638 // have meant to call.
9639 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009640 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9641 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009642 /*EmptyLookup=*/false,
9643 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009644 if (!Recovery.isInvalid())
9645 return Recovery;
9646
Daniel Dunbar96a00142012-03-09 18:35:03 +00009647 Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009648 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009649 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009650 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9651 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009652 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009653 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009654
9655 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +00009656 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009657 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009658 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9659 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009660 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009661
9662 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009663 {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009664 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009665 << Best->Function->isDeleted()
9666 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009667 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009668 << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009669 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9670 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009671
9672 // We emitted an error for the unvailable/deleted function call but keep
9673 // the call in the AST.
9674 FunctionDecl *FDecl = Best->Function;
9675 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9676 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9677 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009678 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009679 }
9680
Douglas Gregorff331c12010-07-25 18:17:45 +00009681 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009682 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009683}
9684
John McCall6e266892010-01-26 03:27:55 +00009685static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009686 return Functions.size() > 1 ||
9687 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9688}
9689
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009690/// \brief Create a unary operation that may resolve to an overloaded
9691/// operator.
9692///
9693/// \param OpLoc The location of the operator itself (e.g., '*').
9694///
9695/// \param OpcIn The UnaryOperator::Opcode that describes this
9696/// operator.
9697///
9698/// \param Functions The set of non-member functions that will be
9699/// considered by overload resolution. The caller needs to build this
9700/// set based on the context using, e.g.,
9701/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9702/// set should not contain any member functions; those will be added
9703/// by CreateOverloadedUnaryOp().
9704///
9705/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009706ExprResult
John McCall6e266892010-01-26 03:27:55 +00009707Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9708 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009709 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009710 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009711
9712 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9713 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9714 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009715 // TODO: provide better source location info.
9716 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009717
John McCall5acb0c92011-10-17 18:40:02 +00009718 if (checkPlaceholderForOverload(*this, Input))
9719 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009720
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009721 Expr *Args[2] = { Input, 0 };
9722 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009723
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009724 // For post-increment and post-decrement, add the implicit '0' as
9725 // the second argument, so that we know this is a post-increment or
9726 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009727 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009728 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009729 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9730 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009731 NumArgs = 2;
9732 }
9733
9734 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009735 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009736 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009737 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009738 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009739 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009740 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009741
John McCallc373d482010-01-27 01:50:18 +00009742 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009743 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009744 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009745 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009746 /*ADL*/ true, IsOverloaded(Fns),
9747 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009748 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009749 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009750 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009751 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009752 OpLoc));
9753 }
9754
9755 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009756 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009757
9758 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009759 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9760 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009761
9762 // Add operator candidates that are member functions.
9763 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9764
John McCall6e266892010-01-26 03:27:55 +00009765 // Add candidates from ADL.
9766 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009767 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009768 /*ExplicitTemplateArgs*/ 0,
9769 CandidateSet);
9770
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009771 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009772 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009773
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009774 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9775
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009776 // Perform overload resolution.
9777 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009778 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009779 case OR_Success: {
9780 // We found a built-in operator or an overloaded operator.
9781 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009782
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009783 if (FnDecl) {
9784 // We matched an overloaded operator. Build a call to that
9785 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009786
Eli Friedman5f2987c2012-02-02 03:46:19 +00009787 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009788
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009789 // Convert the arguments.
9790 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009791 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009792
John Wiegley429bb272011-04-08 18:41:53 +00009793 ExprResult InputRes =
9794 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9795 Best->FoundDecl, Method);
9796 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009797 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009798 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009799 } else {
9800 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009801 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009802 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009803 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009804 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009805 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009806 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009807 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009808 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009809 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009810 }
9811
John McCallb697e082010-05-06 18:15:07 +00009812 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9813
John McCallf89e55a2010-11-18 06:31:45 +00009814 // Determine the result type.
9815 QualType ResultTy = FnDecl->getResultType();
9816 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9817 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009818
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009819 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009820 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009821 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009822 if (FnExpr.isInvalid())
9823 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009824
Eli Friedman4c3b8962009-11-18 03:58:17 +00009825 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009826 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009827 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009828 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009829
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009830 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009831 FnDecl))
9832 return ExprError();
9833
John McCall9ae2f072010-08-23 23:25:46 +00009834 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009835 } else {
9836 // We matched a built-in operator. Convert the arguments, then
9837 // break out so that we will build the appropriate built-in
9838 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009839 ExprResult InputRes =
9840 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9841 Best->Conversions[0], AA_Passing);
9842 if (InputRes.isInvalid())
9843 return ExprError();
9844 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009845 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009846 }
John Wiegley429bb272011-04-08 18:41:53 +00009847 }
9848
9849 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009850 // This is an erroneous use of an operator which can be overloaded by
9851 // a non-member function. Check for non-member operators which were
9852 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009853 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9854 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +00009855 // FIXME: Recover by calling the found function.
9856 return ExprError();
9857
John Wiegley429bb272011-04-08 18:41:53 +00009858 // No viable function; fall through to handling this as a
9859 // built-in operator, which will produce an error message for us.
9860 break;
9861
9862 case OR_Ambiguous:
9863 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9864 << UnaryOperator::getOpcodeStr(Opc)
9865 << Input->getType()
9866 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009867 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9868 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +00009869 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9870 return ExprError();
9871
9872 case OR_Deleted:
9873 Diag(OpLoc, diag::err_ovl_deleted_oper)
9874 << Best->Function->isDeleted()
9875 << UnaryOperator::getOpcodeStr(Opc)
9876 << getDeletedOrUnavailableSuffix(Best->Function)
9877 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009878 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9879 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +00009880 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009881 return ExprError();
9882 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009883
9884 // Either we found no viable overloaded operator or we matched a
9885 // built-in operator. In either case, fall through to trying to
9886 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009887 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009888}
9889
Douglas Gregor063daf62009-03-13 18:40:31 +00009890/// \brief Create a binary operation that may resolve to an overloaded
9891/// operator.
9892///
9893/// \param OpLoc The location of the operator itself (e.g., '+').
9894///
9895/// \param OpcIn The BinaryOperator::Opcode that describes this
9896/// operator.
9897///
9898/// \param Functions The set of non-member functions that will be
9899/// considered by overload resolution. The caller needs to build this
9900/// set based on the context using, e.g.,
9901/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9902/// set should not contain any member functions; those will be added
9903/// by CreateOverloadedBinOp().
9904///
9905/// \param LHS Left-hand argument.
9906/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009907ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009908Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009909 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009910 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009911 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009912 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009913 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009914
9915 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9916 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9917 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9918
9919 // If either side is type-dependent, create an appropriate dependent
9920 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009921 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009922 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009923 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009924 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009925 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009926 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009927 Context.DependentTy,
9928 VK_RValue, OK_Ordinary,
9929 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009930
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009931 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9932 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009933 VK_LValue,
9934 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009935 Context.DependentTy,
9936 Context.DependentTy,
9937 OpLoc));
9938 }
John McCall6e266892010-01-26 03:27:55 +00009939
9940 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009941 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009942 // TODO: provide better source location info in DNLoc component.
9943 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009944 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009945 = UnresolvedLookupExpr::Create(Context, NamingClass,
9946 NestedNameSpecifierLoc(), OpNameInfo,
9947 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009948 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009949 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009950 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009951 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009952 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009953 OpLoc));
9954 }
9955
John McCall5acb0c92011-10-17 18:40:02 +00009956 // Always do placeholder-like conversions on the RHS.
9957 if (checkPlaceholderForOverload(*this, Args[1]))
9958 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009959
John McCall3c3b7f92011-10-25 17:37:35 +00009960 // Do placeholder-like conversion on the LHS; note that we should
9961 // not get here with a PseudoObject LHS.
9962 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009963 if (checkPlaceholderForOverload(*this, Args[0]))
9964 return ExprError();
9965
Sebastian Redl275c2b42009-11-18 23:10:33 +00009966 // If this is the assignment operator, we only perform overload resolution
9967 // if the left-hand side is a class or enumeration type. This is actually
9968 // a hack. The standard requires that we do overload resolution between the
9969 // various built-in candidates, but as DR507 points out, this can lead to
9970 // problems. So we do it this way, which pretty much follows what GCC does.
9971 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009972 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009973 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009974
John McCall0e800c92010-12-04 08:14:53 +00009975 // If this is the .* operator, which is not overloadable, just
9976 // create a built-in binary operator.
9977 if (Opc == BO_PtrMemD)
9978 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9979
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009980 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009981 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009982
9983 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009984 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009985
9986 // Add operator candidates that are member functions.
9987 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9988
John McCall6e266892010-01-26 03:27:55 +00009989 // Add candidates from ADL.
9990 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009991 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +00009992 /*ExplicitTemplateArgs*/ 0,
9993 CandidateSet);
9994
Douglas Gregor063daf62009-03-13 18:40:31 +00009995 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009996 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009997
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009998 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9999
Douglas Gregor063daf62009-03-13 18:40:31 +000010000 // Perform overload resolution.
10001 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010002 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010003 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010004 // We found a built-in operator or an overloaded operator.
10005 FunctionDecl *FnDecl = Best->Function;
10006
10007 if (FnDecl) {
10008 // We matched an overloaded operator. Build a call to that
10009 // operator.
10010
Eli Friedman5f2987c2012-02-02 03:46:19 +000010011 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010012
Douglas Gregor063daf62009-03-13 18:40:31 +000010013 // Convert the arguments.
10014 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010015 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010016 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010017
Chandler Carruth6df868e2010-12-12 08:17:55 +000010018 ExprResult Arg1 =
10019 PerformCopyInitialization(
10020 InitializedEntity::InitializeParameter(Context,
10021 FnDecl->getParamDecl(0)),
10022 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010023 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010024 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010025
John Wiegley429bb272011-04-08 18:41:53 +000010026 ExprResult Arg0 =
10027 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10028 Best->FoundDecl, Method);
10029 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010030 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010031 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010032 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010033 } else {
10034 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010035 ExprResult Arg0 = PerformCopyInitialization(
10036 InitializedEntity::InitializeParameter(Context,
10037 FnDecl->getParamDecl(0)),
10038 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010039 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010040 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010041
Chandler Carruth6df868e2010-12-12 08:17:55 +000010042 ExprResult Arg1 =
10043 PerformCopyInitialization(
10044 InitializedEntity::InitializeParameter(Context,
10045 FnDecl->getParamDecl(1)),
10046 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010047 if (Arg1.isInvalid())
10048 return ExprError();
10049 Args[0] = LHS = Arg0.takeAs<Expr>();
10050 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010051 }
10052
John McCallb697e082010-05-06 18:15:07 +000010053 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10054
John McCallf89e55a2010-11-18 06:31:45 +000010055 // Determine the result type.
10056 QualType ResultTy = FnDecl->getResultType();
10057 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10058 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010059
10060 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010061 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10062 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010063 if (FnExpr.isInvalid())
10064 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010065
John McCall9ae2f072010-08-23 23:25:46 +000010066 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010067 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010068 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010069
10070 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010071 FnDecl))
10072 return ExprError();
10073
John McCall9ae2f072010-08-23 23:25:46 +000010074 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010075 } else {
10076 // We matched a built-in operator. Convert the arguments, then
10077 // break out so that we will build the appropriate built-in
10078 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010079 ExprResult ArgsRes0 =
10080 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10081 Best->Conversions[0], AA_Passing);
10082 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010083 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010084 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010085
John Wiegley429bb272011-04-08 18:41:53 +000010086 ExprResult ArgsRes1 =
10087 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10088 Best->Conversions[1], AA_Passing);
10089 if (ArgsRes1.isInvalid())
10090 return ExprError();
10091 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010092 break;
10093 }
10094 }
10095
Douglas Gregor33074752009-09-30 21:46:01 +000010096 case OR_No_Viable_Function: {
10097 // C++ [over.match.oper]p9:
10098 // If the operator is the operator , [...] and there are no
10099 // viable functions, then the operator is assumed to be the
10100 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010101 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010102 break;
10103
Chandler Carruth6df868e2010-12-12 08:17:55 +000010104 // For class as left operand for assignment or compound assigment
10105 // operator do not fall through to handling in built-in, but report that
10106 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010107 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010108 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010109 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010110 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10111 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010112 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010113 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010114 // This is an erroneous use of an operator which can be overloaded by
10115 // a non-member function. Check for non-member operators which were
10116 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010117 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010118 // FIXME: Recover by calling the found function.
10119 return ExprError();
10120
Douglas Gregor33074752009-09-30 21:46:01 +000010121 // No viable function; try to create a built-in operation, which will
10122 // produce an error. Then, show the non-viable candidates.
10123 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010124 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010125 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010126 "C++ binary operator overloading is missing candidates!");
10127 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010128 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010129 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010130 return move(Result);
10131 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010132
10133 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010134 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010135 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010136 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010137 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010138 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010139 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010140 return ExprError();
10141
10142 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010143 if (isImplicitlyDeleted(Best->Function)) {
10144 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10145 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10146 << getSpecialMember(Method)
10147 << BinaryOperator::getOpcodeStr(Opc)
10148 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010149
10150 if (getSpecialMember(Method) != CXXInvalid) {
10151 // The user probably meant to call this special member. Just
10152 // explain why it's deleted.
10153 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010154 return ExprError();
10155 }
10156 } else {
10157 Diag(OpLoc, diag::err_ovl_deleted_oper)
10158 << Best->Function->isDeleted()
10159 << BinaryOperator::getOpcodeStr(Opc)
10160 << getDeletedOrUnavailableSuffix(Best->Function)
10161 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10162 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010163 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010164 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010165 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010166 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010167
Douglas Gregor33074752009-09-30 21:46:01 +000010168 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010169 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010170}
10171
John McCall60d7b3a2010-08-24 06:29:42 +000010172ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010173Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10174 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010175 Expr *Base, Expr *Idx) {
10176 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010177 DeclarationName OpName =
10178 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10179
10180 // If either side is type-dependent, create an appropriate dependent
10181 // expression.
10182 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10183
John McCallc373d482010-01-27 01:50:18 +000010184 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010185 // CHECKME: no 'operator' keyword?
10186 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10187 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010188 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010189 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010190 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010191 /*ADL*/ true, /*Overloaded*/ false,
10192 UnresolvedSetIterator(),
10193 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010194 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010195
Sebastian Redlf322ed62009-10-29 20:17:01 +000010196 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10197 Args, 2,
10198 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010199 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010200 RLoc));
10201 }
10202
John McCall5acb0c92011-10-17 18:40:02 +000010203 // Handle placeholders on both operands.
10204 if (checkPlaceholderForOverload(*this, Args[0]))
10205 return ExprError();
10206 if (checkPlaceholderForOverload(*this, Args[1]))
10207 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010208
Sebastian Redlf322ed62009-10-29 20:17:01 +000010209 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010210 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010211
10212 // Subscript can only be overloaded as a member function.
10213
10214 // Add operator candidates that are member functions.
10215 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10216
10217 // Add builtin operator candidates.
10218 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10219
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010220 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10221
Sebastian Redlf322ed62009-10-29 20:17:01 +000010222 // Perform overload resolution.
10223 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010224 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010225 case OR_Success: {
10226 // We found a built-in operator or an overloaded operator.
10227 FunctionDecl *FnDecl = Best->Function;
10228
10229 if (FnDecl) {
10230 // We matched an overloaded operator. Build a call to that
10231 // operator.
10232
Eli Friedman5f2987c2012-02-02 03:46:19 +000010233 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010234
John McCall9aa472c2010-03-19 07:35:19 +000010235 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010236 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010237
Sebastian Redlf322ed62009-10-29 20:17:01 +000010238 // Convert the arguments.
10239 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010240 ExprResult Arg0 =
10241 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10242 Best->FoundDecl, Method);
10243 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010244 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010245 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010246
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010247 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010248 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010249 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010250 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010251 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010252 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010253 Owned(Args[1]));
10254 if (InputInit.isInvalid())
10255 return ExprError();
10256
10257 Args[1] = InputInit.takeAs<Expr>();
10258
Sebastian Redlf322ed62009-10-29 20:17:01 +000010259 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010260 QualType ResultTy = FnDecl->getResultType();
10261 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10262 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010263
10264 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010265 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10266 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010267 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10268 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010269 OpLocInfo.getLoc(),
10270 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010271 if (FnExpr.isInvalid())
10272 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010273
John McCall9ae2f072010-08-23 23:25:46 +000010274 CXXOperatorCallExpr *TheCall =
10275 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010276 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010277 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010278
John McCall9ae2f072010-08-23 23:25:46 +000010279 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010280 FnDecl))
10281 return ExprError();
10282
John McCall9ae2f072010-08-23 23:25:46 +000010283 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010284 } else {
10285 // We matched a built-in operator. Convert the arguments, then
10286 // break out so that we will build the appropriate built-in
10287 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010288 ExprResult ArgsRes0 =
10289 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10290 Best->Conversions[0], AA_Passing);
10291 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010292 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010293 Args[0] = ArgsRes0.take();
10294
10295 ExprResult ArgsRes1 =
10296 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10297 Best->Conversions[1], AA_Passing);
10298 if (ArgsRes1.isInvalid())
10299 return ExprError();
10300 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010301
10302 break;
10303 }
10304 }
10305
10306 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010307 if (CandidateSet.empty())
10308 Diag(LLoc, diag::err_ovl_no_oper)
10309 << Args[0]->getType() << /*subscript*/ 0
10310 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10311 else
10312 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10313 << Args[0]->getType()
10314 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010315 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010316 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010317 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010318 }
10319
10320 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010321 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010322 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010323 << Args[0]->getType() << Args[1]->getType()
10324 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010325 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010326 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010327 return ExprError();
10328
10329 case OR_Deleted:
10330 Diag(LLoc, diag::err_ovl_deleted_oper)
10331 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010332 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010333 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010334 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010335 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010336 return ExprError();
10337 }
10338
10339 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010340 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010341}
10342
Douglas Gregor88a35142008-12-22 05:46:06 +000010343/// BuildCallToMemberFunction - Build a call to a member
10344/// function. MemExpr is the expression that refers to the member
10345/// function (and includes the object parameter), Args/NumArgs are the
10346/// arguments to the function call (not including the object
10347/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010348/// expression refers to a non-static member function or an overloaded
10349/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010350ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010351Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10352 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010353 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010354 assert(MemExprE->getType() == Context.BoundMemberTy ||
10355 MemExprE->getType() == Context.OverloadTy);
10356
Douglas Gregor88a35142008-12-22 05:46:06 +000010357 // Dig out the member expression. This holds both the object
10358 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010359 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010360
John McCall864c0412011-04-26 20:42:42 +000010361 // Determine whether this is a call to a pointer-to-member function.
10362 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10363 assert(op->getType() == Context.BoundMemberTy);
10364 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10365
10366 QualType fnType =
10367 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10368
10369 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10370 QualType resultType = proto->getCallResultType(Context);
10371 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10372
10373 // Check that the object type isn't more qualified than the
10374 // member function we're calling.
10375 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10376
10377 QualType objectType = op->getLHS()->getType();
10378 if (op->getOpcode() == BO_PtrMemI)
10379 objectType = objectType->castAs<PointerType>()->getPointeeType();
10380 Qualifiers objectQuals = objectType.getQualifiers();
10381
10382 Qualifiers difference = objectQuals - funcQuals;
10383 difference.removeObjCGCAttr();
10384 difference.removeAddressSpace();
10385 if (difference) {
10386 std::string qualsString = difference.getAsString();
10387 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10388 << fnType.getUnqualifiedType()
10389 << qualsString
10390 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10391 }
10392
10393 CXXMemberCallExpr *call
10394 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10395 resultType, valueKind, RParenLoc);
10396
10397 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010398 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010399 call, 0))
10400 return ExprError();
10401
10402 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10403 return ExprError();
10404
10405 return MaybeBindToTemporary(call);
10406 }
10407
John McCall5acb0c92011-10-17 18:40:02 +000010408 UnbridgedCastsSet UnbridgedCasts;
10409 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10410 return ExprError();
10411
John McCall129e2df2009-11-30 22:42:35 +000010412 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010413 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010414 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010415 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010416 if (isa<MemberExpr>(NakedMemExpr)) {
10417 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010418 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010419 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010420 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010421 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010422 } else {
10423 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010424 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010425
John McCall701c89e2009-12-03 04:06:58 +000010426 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010427 Expr::Classification ObjectClassification
10428 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10429 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010430
Douglas Gregor88a35142008-12-22 05:46:06 +000010431 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010432 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010433
John McCallaa81e162009-12-01 22:10:20 +000010434 // FIXME: avoid copy.
10435 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10436 if (UnresExpr->hasExplicitTemplateArgs()) {
10437 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10438 TemplateArgs = &TemplateArgsBuffer;
10439 }
10440
John McCall129e2df2009-11-30 22:42:35 +000010441 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10442 E = UnresExpr->decls_end(); I != E; ++I) {
10443
John McCall701c89e2009-12-03 04:06:58 +000010444 NamedDecl *Func = *I;
10445 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10446 if (isa<UsingShadowDecl>(Func))
10447 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10448
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010449
Francois Pichetdbee3412011-01-18 05:04:39 +000010450 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010451 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010452 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10453 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010454 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010455 // If explicit template arguments were provided, we can't call a
10456 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010457 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010458 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010459
John McCall9aa472c2010-03-19 07:35:19 +000010460 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010461 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010462 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010463 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010464 } else {
John McCall129e2df2009-11-30 22:42:35 +000010465 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010466 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010467 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010468 llvm::makeArrayRef(Args, NumArgs),
10469 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010470 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010471 }
Douglas Gregordec06662009-08-21 18:42:58 +000010472 }
Mike Stump1eb44332009-09-09 15:08:12 +000010473
John McCall129e2df2009-11-30 22:42:35 +000010474 DeclarationName DeclName = UnresExpr->getMemberName();
10475
John McCall5acb0c92011-10-17 18:40:02 +000010476 UnbridgedCasts.restore();
10477
Douglas Gregor88a35142008-12-22 05:46:06 +000010478 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010479 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010480 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010481 case OR_Success:
10482 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010483 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010484 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010485 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010486 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010487 break;
10488
10489 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010490 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010491 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010492 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010493 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10494 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010495 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010496 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010497
10498 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010499 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010500 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010501 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10502 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010503 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010504 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010505
10506 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010507 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010508 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010509 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010510 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010511 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010512 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10513 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010514 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010515 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010516 }
10517
John McCall6bb80172010-03-30 21:47:33 +000010518 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010519
John McCallaa81e162009-12-01 22:10:20 +000010520 // If overload resolution picked a static member, build a
10521 // non-member call based on that function.
10522 if (Method->isStatic()) {
10523 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10524 Args, NumArgs, RParenLoc);
10525 }
10526
John McCall129e2df2009-11-30 22:42:35 +000010527 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010528 }
10529
John McCallf89e55a2010-11-18 06:31:45 +000010530 QualType ResultType = Method->getResultType();
10531 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10532 ResultType = ResultType.getNonLValueExprType(Context);
10533
Douglas Gregor88a35142008-12-22 05:46:06 +000010534 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010535 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010536 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010537 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010538
Anders Carlssoneed3e692009-10-10 00:06:20 +000010539 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010540 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010541 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010542 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010543
Douglas Gregor88a35142008-12-22 05:46:06 +000010544 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010545 // We only need to do this if there was actually an overload; otherwise
10546 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010547 if (!Method->isStatic()) {
10548 ExprResult ObjectArg =
10549 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10550 FoundDecl, Method);
10551 if (ObjectArg.isInvalid())
10552 return ExprError();
10553 MemExpr->setBase(ObjectArg.take());
10554 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010555
10556 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010557 const FunctionProtoType *Proto =
10558 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010559 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010560 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010561 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010562
Eli Friedmane61eb042012-02-18 04:48:30 +000010563 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10564
John McCall9ae2f072010-08-23 23:25:46 +000010565 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +000010566 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010567
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010568 if ((isa<CXXConstructorDecl>(CurContext) ||
10569 isa<CXXDestructorDecl>(CurContext)) &&
10570 TheCall->getMethodDecl()->isPure()) {
10571 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10572
Chandler Carruthae198062011-06-27 08:31:58 +000010573 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010574 Diag(MemExpr->getLocStart(),
10575 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10576 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10577 << MD->getParent()->getDeclName();
10578
10579 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010580 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010581 }
John McCall9ae2f072010-08-23 23:25:46 +000010582 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010583}
10584
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010585/// BuildCallToObjectOfClassType - Build a call to an object of class
10586/// type (C++ [over.call.object]), which can end up invoking an
10587/// overloaded function call operator (@c operator()) or performing a
10588/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010589ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010590Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010591 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010592 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010593 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010594 if (checkPlaceholderForOverload(*this, Obj))
10595 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010596 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010597
10598 UnbridgedCastsSet UnbridgedCasts;
10599 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10600 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010601
John Wiegley429bb272011-04-08 18:41:53 +000010602 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10603 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010604
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010605 // C++ [over.call.object]p1:
10606 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010607 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010608 // candidate functions includes at least the function call
10609 // operators of T. The function call operators of T are obtained by
10610 // ordinary lookup of the name operator() in the context of
10611 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010612 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010613 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010614
John Wiegley429bb272011-04-08 18:41:53 +000010615 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010616 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010617 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010618
John McCalla24dc2e2009-11-17 02:14:36 +000010619 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10620 LookupQualifiedName(R, Record->getDecl());
10621 R.suppressDiagnostics();
10622
Douglas Gregor593564b2009-11-15 07:48:03 +000010623 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010624 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010625 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10626 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010627 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010628 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010629
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010630 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010631 // In addition, for each (non-explicit in C++0x) conversion function
10632 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010633 //
10634 // operator conversion-type-id () cv-qualifier;
10635 //
10636 // where cv-qualifier is the same cv-qualification as, or a
10637 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010638 // denotes the type "pointer to function of (P1,...,Pn) returning
10639 // R", or the type "reference to pointer to function of
10640 // (P1,...,Pn) returning R", or the type "reference to function
10641 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010642 // is also considered as a candidate function. Similarly,
10643 // surrogate call functions are added to the set of candidate
10644 // functions for each conversion function declared in an
10645 // accessible base class provided the function is not hidden
10646 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010647 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010648 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010649 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010650 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010651 NamedDecl *D = *I;
10652 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10653 if (isa<UsingShadowDecl>(D))
10654 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010655
Douglas Gregor4a27d702009-10-21 06:18:39 +000010656 // Skip over templated conversion functions; they aren't
10657 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010658 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010659 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010660
John McCall701c89e2009-12-03 04:06:58 +000010661 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010662 if (!Conv->isExplicit()) {
10663 // Strip the reference type (if any) and then the pointer type (if
10664 // any) to get down to what might be a function type.
10665 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10666 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10667 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010668
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010669 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10670 {
10671 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010672 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10673 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010674 }
10675 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010676 }
Mike Stump1eb44332009-09-09 15:08:12 +000010677
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010678 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10679
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010680 // Perform overload resolution.
10681 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010682 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010683 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010684 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010685 // Overload resolution succeeded; we'll build the appropriate call
10686 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010687 break;
10688
10689 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010690 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010691 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010692 << Object.get()->getType() << /*call*/ 1
10693 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010694 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010695 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010696 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010697 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010698 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10699 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010700 break;
10701
10702 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010703 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010704 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010705 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010706 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10707 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010708 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010709
10710 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010711 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010712 diag::err_ovl_deleted_object_call)
10713 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010714 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010715 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010716 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010717 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10718 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010719 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010720 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010721
Douglas Gregorff331c12010-07-25 18:17:45 +000010722 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010723 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010724
John McCall5acb0c92011-10-17 18:40:02 +000010725 UnbridgedCasts.restore();
10726
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010727 if (Best->Function == 0) {
10728 // Since there is no function declaration, this is one of the
10729 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010730 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010731 = cast<CXXConversionDecl>(
10732 Best->Conversions[0].UserDefined.ConversionFunction);
10733
John Wiegley429bb272011-04-08 18:41:53 +000010734 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010735 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010736
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010737 // We selected one of the surrogate functions that converts the
10738 // object parameter to a function pointer. Perform the conversion
10739 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010740
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010741 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010742 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010743 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10744 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010745 if (Call.isInvalid())
10746 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010747 // Record usage of conversion in an implicit cast.
10748 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10749 CK_UserDefinedConversion,
10750 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010751
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010752 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010753 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010754 }
10755
Eli Friedman5f2987c2012-02-02 03:46:19 +000010756 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010757 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010758 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010759
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010760 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10761 // that calls this method, using Object for the implicit object
10762 // parameter and passing along the remaining arguments.
10763 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010764 const FunctionProtoType *Proto =
10765 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010766
10767 unsigned NumArgsInProto = Proto->getNumArgs();
10768 unsigned NumArgsToCheck = NumArgs;
10769
10770 // Build the full argument list for the method call (the
10771 // implicit object parameter is placed at the beginning of the
10772 // list).
10773 Expr **MethodArgs;
10774 if (NumArgs < NumArgsInProto) {
10775 NumArgsToCheck = NumArgsInProto;
10776 MethodArgs = new Expr*[NumArgsInProto + 1];
10777 } else {
10778 MethodArgs = new Expr*[NumArgs + 1];
10779 }
John Wiegley429bb272011-04-08 18:41:53 +000010780 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010781 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10782 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010783
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010784 DeclarationNameInfo OpLocInfo(
10785 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10786 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010787 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010788 HadMultipleCandidates,
10789 OpLocInfo.getLoc(),
10790 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010791 if (NewFn.isInvalid())
10792 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010793
10794 // Once we've built TheCall, all of the expressions are properly
10795 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010796 QualType ResultTy = Method->getResultType();
10797 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10798 ResultTy = ResultTy.getNonLValueExprType(Context);
10799
John McCall9ae2f072010-08-23 23:25:46 +000010800 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010801 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010802 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010803 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010804 delete [] MethodArgs;
10805
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010806 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010807 Method))
10808 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010809
Douglas Gregor518fda12009-01-13 05:10:00 +000010810 // We may have default arguments. If so, we need to allocate more
10811 // slots in the call for them.
10812 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010813 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010814 else if (NumArgs > NumArgsInProto)
10815 NumArgsToCheck = NumArgsInProto;
10816
Chris Lattner312531a2009-04-12 08:11:20 +000010817 bool IsError = false;
10818
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010819 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010820 ExprResult ObjRes =
10821 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10822 Best->FoundDecl, Method);
10823 if (ObjRes.isInvalid())
10824 IsError = true;
10825 else
10826 Object = move(ObjRes);
10827 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010828
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010829 // Check the argument types.
10830 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010831 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010832 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010833 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010834
Douglas Gregor518fda12009-01-13 05:10:00 +000010835 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010836
John McCall60d7b3a2010-08-24 06:29:42 +000010837 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010838 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010839 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010840 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010841 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010842
Anders Carlsson3faa4862010-01-29 18:43:53 +000010843 IsError |= InputInit.isInvalid();
10844 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010845 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010846 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010847 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10848 if (DefArg.isInvalid()) {
10849 IsError = true;
10850 break;
10851 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010852
Douglas Gregord47c47d2009-11-09 19:27:57 +000010853 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010854 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010855
10856 TheCall->setArg(i + 1, Arg);
10857 }
10858
10859 // If this is a variadic call, handle args passed through "...".
10860 if (Proto->isVariadic()) {
10861 // Promote the arguments (C99 6.5.2.2p7).
10862 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010863 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10864 IsError |= Arg.isInvalid();
10865 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010866 }
10867 }
10868
Chris Lattner312531a2009-04-12 08:11:20 +000010869 if (IsError) return true;
10870
Eli Friedmane61eb042012-02-18 04:48:30 +000010871 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10872
John McCall9ae2f072010-08-23 23:25:46 +000010873 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010874 return true;
10875
John McCall182f7092010-08-24 06:09:16 +000010876 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010877}
10878
Douglas Gregor8ba10742008-11-20 16:27:02 +000010879/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010880/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010881/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010882ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010883Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010884 assert(Base->getType()->isRecordType() &&
10885 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010886
John McCall5acb0c92011-10-17 18:40:02 +000010887 if (checkPlaceholderForOverload(*this, Base))
10888 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010889
John McCall5769d612010-02-08 23:07:23 +000010890 SourceLocation Loc = Base->getExprLoc();
10891
Douglas Gregor8ba10742008-11-20 16:27:02 +000010892 // C++ [over.ref]p1:
10893 //
10894 // [...] An expression x->m is interpreted as (x.operator->())->m
10895 // for a class object x of type T if T::operator->() exists and if
10896 // the operator is selected as the best match function by the
10897 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010898 DeclarationName OpName =
10899 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010900 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010901 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010902
John McCall5769d612010-02-08 23:07:23 +000010903 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010904 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000010905 return ExprError();
10906
John McCalla24dc2e2009-11-17 02:14:36 +000010907 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10908 LookupQualifiedName(R, BaseRecord->getDecl());
10909 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010910
10911 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010912 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010913 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10914 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010915 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010916
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010917 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10918
Douglas Gregor8ba10742008-11-20 16:27:02 +000010919 // Perform overload resolution.
10920 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010921 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010922 case OR_Success:
10923 // Overload resolution succeeded; we'll build the call below.
10924 break;
10925
10926 case OR_No_Viable_Function:
10927 if (CandidateSet.empty())
10928 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010929 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010930 else
10931 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010932 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010933 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010934 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010935
10936 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010937 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10938 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010939 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010940 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010941
10942 case OR_Deleted:
10943 Diag(OpLoc, diag::err_ovl_deleted_oper)
10944 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010945 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010946 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010947 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010948 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010949 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010950 }
10951
Eli Friedman5f2987c2012-02-02 03:46:19 +000010952 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010953 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010954 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010955
Douglas Gregor8ba10742008-11-20 16:27:02 +000010956 // Convert the object parameter.
10957 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010958 ExprResult BaseResult =
10959 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10960 Best->FoundDecl, Method);
10961 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010962 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010963 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010964
Douglas Gregor8ba10742008-11-20 16:27:02 +000010965 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010966 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010967 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010968 if (FnExpr.isInvalid())
10969 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010970
John McCallf89e55a2010-11-18 06:31:45 +000010971 QualType ResultTy = Method->getResultType();
10972 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10973 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010974 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010975 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010976 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010977
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010978 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010979 Method))
10980 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010981
10982 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010983}
10984
Richard Smith36f5cfe2012-03-09 08:00:36 +000010985/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10986/// a literal operator described by the provided lookup results.
10987ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10988 DeclarationNameInfo &SuffixInfo,
10989 ArrayRef<Expr*> Args,
10990 SourceLocation LitEndLoc,
10991 TemplateArgumentListInfo *TemplateArgs) {
10992 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000010993
Richard Smith36f5cfe2012-03-09 08:00:36 +000010994 OverloadCandidateSet CandidateSet(UDSuffixLoc);
10995 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10996 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000010997
Richard Smith36f5cfe2012-03-09 08:00:36 +000010998 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10999
Richard Smith36f5cfe2012-03-09 08:00:36 +000011000 // Perform overload resolution. This will usually be trivial, but might need
11001 // to perform substitutions for a literal operator template.
11002 OverloadCandidateSet::iterator Best;
11003 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11004 case OR_Success:
11005 case OR_Deleted:
11006 break;
11007
11008 case OR_No_Viable_Function:
11009 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11010 << R.getLookupName();
11011 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11012 return ExprError();
11013
11014 case OR_Ambiguous:
11015 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11016 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11017 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011018 }
11019
Richard Smith36f5cfe2012-03-09 08:00:36 +000011020 FunctionDecl *FD = Best->Function;
11021 MarkFunctionReferenced(UDSuffixLoc, FD);
11022 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011023
Richard Smith36f5cfe2012-03-09 08:00:36 +000011024 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11025 SuffixInfo.getLoc(),
11026 SuffixInfo.getInfo());
11027 if (Fn.isInvalid())
11028 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011029
11030 // Check the argument types. This should almost always be a no-op, except
11031 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011032 Expr *ConvArgs[2];
11033 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11034 ExprResult InputInit = PerformCopyInitialization(
11035 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11036 SourceLocation(), Args[ArgIdx]);
11037 if (InputInit.isInvalid())
11038 return true;
11039 ConvArgs[ArgIdx] = InputInit.take();
11040 }
11041
Richard Smith9fcce652012-03-07 08:35:16 +000011042 QualType ResultTy = FD->getResultType();
11043 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11044 ResultTy = ResultTy.getNonLValueExprType(Context);
11045
Richard Smith9fcce652012-03-07 08:35:16 +000011046 UserDefinedLiteral *UDL =
11047 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11048 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11049
11050 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11051 return ExprError();
11052
11053 if (CheckFunctionCall(FD, UDL))
11054 return ExprError();
11055
11056 return MaybeBindToTemporary(UDL);
11057}
11058
Douglas Gregor904eed32008-11-10 20:40:00 +000011059/// FixOverloadedFunctionReference - E is an expression that refers to
11060/// a C++ overloaded function (possibly with some parentheses and
11061/// perhaps a '&' around it). We have resolved the overloaded function
11062/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011063/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011064Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011065 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011066 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011067 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11068 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011069 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011070 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011071
Douglas Gregor699ee522009-11-20 19:42:02 +000011072 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011073 }
11074
Douglas Gregor699ee522009-11-20 19:42:02 +000011075 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011076 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11077 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011078 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011079 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011080 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011081 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011082 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011083 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011084
11085 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011086 ICE->getCastKind(),
11087 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011088 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011089 }
11090
Douglas Gregor699ee522009-11-20 19:42:02 +000011091 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011092 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011093 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011094 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11095 if (Method->isStatic()) {
11096 // Do nothing: static member functions aren't any different
11097 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011098 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011099 // Fix the sub expression, which really has to be an
11100 // UnresolvedLookupExpr holding an overloaded member function
11101 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011102 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11103 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011104 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011105 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011106
John McCallba135432009-11-21 08:51:07 +000011107 assert(isa<DeclRefExpr>(SubExpr)
11108 && "fixed to something other than a decl ref");
11109 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11110 && "fixed to a member ref with no nested name qualifier");
11111
11112 // We have taken the address of a pointer to member
11113 // function. Perform the computation here so that we get the
11114 // appropriate pointer to member type.
11115 QualType ClassType
11116 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11117 QualType MemPtrType
11118 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11119
John McCallf89e55a2010-11-18 06:31:45 +000011120 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11121 VK_RValue, OK_Ordinary,
11122 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011123 }
11124 }
John McCall6bb80172010-03-30 21:47:33 +000011125 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11126 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011127 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011128 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011129
John McCall2de56d12010-08-25 11:45:40 +000011130 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011131 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011132 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011133 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011134 }
John McCallba135432009-11-21 08:51:07 +000011135
11136 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011137 // FIXME: avoid copy.
11138 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011139 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011140 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11141 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011142 }
11143
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011144 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11145 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011146 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011147 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011148 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011149 ULE->getNameLoc(),
11150 Fn->getType(),
11151 VK_LValue,
11152 Found.getDecl(),
11153 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011154 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011155 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11156 return DRE;
John McCallba135432009-11-21 08:51:07 +000011157 }
11158
John McCall129e2df2009-11-30 22:42:35 +000011159 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011160 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011161 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11162 if (MemExpr->hasExplicitTemplateArgs()) {
11163 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11164 TemplateArgs = &TemplateArgsBuffer;
11165 }
John McCalld5532b62009-11-23 01:53:49 +000011166
John McCallaa81e162009-12-01 22:10:20 +000011167 Expr *Base;
11168
John McCallf89e55a2010-11-18 06:31:45 +000011169 // If we're filling in a static method where we used to have an
11170 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011171 if (MemExpr->isImplicitAccess()) {
11172 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011173 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11174 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011175 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011176 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011177 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011178 MemExpr->getMemberLoc(),
11179 Fn->getType(),
11180 VK_LValue,
11181 Found.getDecl(),
11182 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011183 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011184 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11185 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011186 } else {
11187 SourceLocation Loc = MemExpr->getMemberLoc();
11188 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011189 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011190 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011191 Base = new (Context) CXXThisExpr(Loc,
11192 MemExpr->getBaseType(),
11193 /*isImplicit=*/true);
11194 }
John McCallaa81e162009-12-01 22:10:20 +000011195 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011196 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011197
John McCallf5307512011-04-27 00:36:17 +000011198 ExprValueKind valueKind;
11199 QualType type;
11200 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11201 valueKind = VK_LValue;
11202 type = Fn->getType();
11203 } else {
11204 valueKind = VK_RValue;
11205 type = Context.BoundMemberTy;
11206 }
11207
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011208 MemberExpr *ME = MemberExpr::Create(Context, Base,
11209 MemExpr->isArrow(),
11210 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011211 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011212 Fn,
11213 Found,
11214 MemExpr->getMemberNameInfo(),
11215 TemplateArgs,
11216 type, valueKind, OK_Ordinary);
11217 ME->setHadMultipleCandidates(true);
11218 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011219 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011220
John McCall3fa5cae2010-10-26 07:05:15 +000011221 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011222}
11223
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011224ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011225 DeclAccessPair Found,
11226 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011227 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011228}
11229
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011230} // end namespace clang