blob: e4c6fdfb59c2f2e870e62d267e96011993332739 [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 Gregor60d62c22008-10-31 16:23:19 +00001297/// IsStandardConversion - Determines whether there is a standard
1298/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1299/// expression From to the type ToType. Standard conversion sequences
1300/// only consider non-class types; for conversions that involve class
1301/// types, use TryImplicitConversion. If a conversion exists, SCS will
1302/// contain the standard conversion sequence required to perform this
1303/// conversion and this routine will return true. Otherwise, this
1304/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001305static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1306 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001307 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001308 bool CStyle,
1309 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001310 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001311
Douglas Gregor60d62c22008-10-31 16:23:19 +00001312 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001313 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001314 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001315 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001316 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001317 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001318
Douglas Gregorf9201e02009-02-11 23:02:49 +00001319 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001320 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001321 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001322 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001323 return false;
1324
Mike Stump1eb44332009-09-09 15:08:12 +00001325 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001326 }
1327
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001328 // The first conversion can be an lvalue-to-rvalue conversion,
1329 // array-to-pointer conversion, or function-to-pointer conversion
1330 // (C++ 4p1).
1331
John McCall120d63c2010-08-24 20:38:10 +00001332 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001333 DeclAccessPair AccessPair;
1334 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001335 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001336 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001337 // We were able to resolve the address of the overloaded function,
1338 // so we can convert to the type of that function.
1339 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001340
1341 // we can sometimes resolve &foo<int> regardless of ToType, so check
1342 // if the type matches (identity) or we are converting to bool
1343 if (!S.Context.hasSameUnqualifiedType(
1344 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1345 QualType resultTy;
1346 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001347 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001348 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1349 // otherwise, only a boolean conversion is standard
1350 if (!ToType->isBooleanType())
1351 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001352 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001353
Chandler Carruth90434232011-03-29 08:08:18 +00001354 // Check if the "from" expression is taking the address of an overloaded
1355 // function and recompute the FromType accordingly. Take advantage of the
1356 // fact that non-static member functions *must* have such an address-of
1357 // expression.
1358 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1359 if (Method && !Method->isStatic()) {
1360 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1361 "Non-unary operator on non-static member address");
1362 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1363 == UO_AddrOf &&
1364 "Non-address-of operator on non-static member address");
1365 const Type *ClassType
1366 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1367 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001368 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1369 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1370 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001371 "Non-address-of operator for overloaded function expression");
1372 FromType = S.Context.getPointerType(FromType);
1373 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001374
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001375 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001376 assert(S.Context.hasSameType(
1377 FromType,
1378 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001379 } else {
1380 return false;
1381 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001382 }
John McCall21480112011-08-30 00:57:29 +00001383 // Lvalue-to-rvalue conversion (C++11 4.1):
1384 // A glvalue (3.10) of a non-function, non-array type T can
1385 // be converted to a prvalue.
1386 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001387 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001388 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001389 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001390 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001391
1392 // If T is a non-class type, the type of the rvalue is the
1393 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001394 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1395 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001396 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001397 } else if (FromType->isArrayType()) {
1398 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001399 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001400
1401 // An lvalue or rvalue of type "array of N T" or "array of unknown
1402 // bound of T" can be converted to an rvalue of type "pointer to
1403 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001404 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001405
John McCall120d63c2010-08-24 20:38:10 +00001406 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001407 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001408 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001409
1410 // For the purpose of ranking in overload resolution
1411 // (13.3.3.1.1), this conversion is considered an
1412 // array-to-pointer conversion followed by a qualification
1413 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001414 SCS.Second = ICK_Identity;
1415 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001416 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001417 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001418 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001419 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001420 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001421 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001422 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001423
1424 // An lvalue of function type T can be converted to an rvalue of
1425 // type "pointer to T." The result is a pointer to the
1426 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001427 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001428 } else {
1429 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001430 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001431 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001432 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001433
1434 // The second conversion can be an integral promotion, floating
1435 // point promotion, integral conversion, floating point conversion,
1436 // floating-integral conversion, pointer conversion,
1437 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001438 // For overloading in C, this can also be a "compatible-type"
1439 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001440 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001441 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001442 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001443 // The unqualified versions of the types are the same: there's no
1444 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001445 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001446 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001447 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001448 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001449 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001450 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001451 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001452 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001453 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001454 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001455 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001456 SCS.Second = ICK_Complex_Promotion;
1457 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001458 } else if (ToType->isBooleanType() &&
1459 (FromType->isArithmeticType() ||
1460 FromType->isAnyPointerType() ||
1461 FromType->isBlockPointerType() ||
1462 FromType->isMemberPointerType() ||
1463 FromType->isNullPtrType())) {
1464 // Boolean conversions (C++ 4.12).
1465 SCS.Second = ICK_Boolean_Conversion;
1466 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001467 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001468 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001469 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001470 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001471 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001472 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001473 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001474 SCS.Second = ICK_Complex_Conversion;
1475 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001476 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1477 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001478 // Complex-real conversions (C99 6.3.1.7)
1479 SCS.Second = ICK_Complex_Real;
1480 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001481 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001482 // Floating point conversions (C++ 4.8).
1483 SCS.Second = ICK_Floating_Conversion;
1484 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001485 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001486 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001487 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001488 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001489 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001490 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001491 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001492 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001493 SCS.Second = ICK_Block_Pointer_Conversion;
1494 } else if (AllowObjCWritebackConversion &&
1495 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1496 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001497 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1498 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001499 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001500 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001501 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001502 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001503 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001504 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001505 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001506 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001507 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001508 SCS.Second = SecondICK;
1509 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001510 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001511 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001512 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001513 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001514 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001515 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001516 // Treat a conversion that strips "noreturn" as an identity conversion.
1517 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001518 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1519 InOverloadResolution,
1520 SCS, CStyle)) {
1521 SCS.Second = ICK_TransparentUnionConversion;
1522 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001523 } else {
1524 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001525 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001526 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001527 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001528
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001529 QualType CanonFrom;
1530 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001532 bool ObjCLifetimeConversion;
1533 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1534 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001535 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001536 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001537 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001538 CanonFrom = S.Context.getCanonicalType(FromType);
1539 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001540 } else {
1541 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001542 SCS.Third = ICK_Identity;
1543
Mike Stump1eb44332009-09-09 15:08:12 +00001544 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001545 // [...] Any difference in top-level cv-qualification is
1546 // subsumed by the initialization itself and does not constitute
1547 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001548 CanonFrom = S.Context.getCanonicalType(FromType);
1549 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001550 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001551 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001552 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001553 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1554 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001555 FromType = ToType;
1556 CanonFrom = CanonTo;
1557 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001558 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001559 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001560
1561 // If we have not converted the argument type to the parameter type,
1562 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001563 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001564 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001565
Douglas Gregor60d62c22008-10-31 16:23:19 +00001566 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001567}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001568
1569static bool
1570IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1571 QualType &ToType,
1572 bool InOverloadResolution,
1573 StandardConversionSequence &SCS,
1574 bool CStyle) {
1575
1576 const RecordType *UT = ToType->getAsUnionType();
1577 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1578 return false;
1579 // The field to initialize within the transparent union.
1580 RecordDecl *UD = UT->getDecl();
1581 // It's compatible if the expression matches any of the fields.
1582 for (RecordDecl::field_iterator it = UD->field_begin(),
1583 itend = UD->field_end();
1584 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001585 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1586 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001587 ToType = it->getType();
1588 return true;
1589 }
1590 }
1591 return false;
1592}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001593
1594/// IsIntegralPromotion - Determines whether the conversion from the
1595/// expression From (whose potentially-adjusted type is FromType) to
1596/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1597/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001598bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001599 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001600 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001601 if (!To) {
1602 return false;
1603 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001604
1605 // An rvalue of type char, signed char, unsigned char, short int, or
1606 // unsigned short int can be converted to an rvalue of type int if
1607 // int can represent all the values of the source type; otherwise,
1608 // the source rvalue can be converted to an rvalue of type unsigned
1609 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001610 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1611 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001612 if (// We can promote any signed, promotable integer type to an int
1613 (FromType->isSignedIntegerType() ||
1614 // We can promote any unsigned integer type whose size is
1615 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001616 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001617 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001618 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001619 }
1620
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001621 return To->getKind() == BuiltinType::UInt;
1622 }
1623
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001624 // C++0x [conv.prom]p3:
1625 // A prvalue of an unscoped enumeration type whose underlying type is not
1626 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1627 // following types that can represent all the values of the enumeration
1628 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1629 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001630 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001631 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001632 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633 // with lowest integer conversion rank (4.13) greater than the rank of long
1634 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001635 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001636 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1637 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1638 // provided for a scoped enumeration.
1639 if (FromEnumType->getDecl()->isScoped())
1640 return false;
1641
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001642 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001643 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001644 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001645 return Context.hasSameUnqualifiedType(ToType,
1646 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001647 }
John McCall842aef82009-12-09 09:09:27 +00001648
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001649 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001650 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1651 // to an rvalue a prvalue of the first of the following types that can
1652 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001653 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001654 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001655 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001656 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001657 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001658 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001659 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001660 // Determine whether the type we're converting from is signed or
1661 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001662 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001663 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001664
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001665 // The types we'll try to promote to, in the appropriate
1666 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001667 QualType PromoteTypes[6] = {
1668 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001669 Context.LongTy, Context.UnsignedLongTy ,
1670 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001671 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001672 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001673 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1674 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001675 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1677 // We found the type that we can promote to. If this is the
1678 // type we wanted, we have a promotion. Otherwise, no
1679 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001680 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001681 }
1682 }
1683 }
1684
1685 // An rvalue for an integral bit-field (9.6) can be converted to an
1686 // rvalue of type int if int can represent all the values of the
1687 // bit-field; otherwise, it can be converted to unsigned int if
1688 // unsigned int can represent all the values of the bit-field. If
1689 // the bit-field is larger yet, no integral promotion applies to
1690 // it. If the bit-field has an enumerated type, it is treated as any
1691 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001692 // FIXME: We should delay checking of bit-fields until we actually perform the
1693 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001694 using llvm::APSInt;
1695 if (From)
1696 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001697 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001698 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001699 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1700 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1701 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Douglas Gregor86f19402008-12-20 23:49:58 +00001703 // Are we promoting to an int from a bitfield that fits in an int?
1704 if (BitWidth < ToSize ||
1705 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1706 return To->getKind() == BuiltinType::Int;
1707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Douglas Gregor86f19402008-12-20 23:49:58 +00001709 // Are we promoting to an unsigned int from an unsigned bitfield
1710 // that fits into an unsigned int?
1711 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1712 return To->getKind() == BuiltinType::UInt;
1713 }
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Douglas Gregor86f19402008-12-20 23:49:58 +00001715 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001716 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001717 }
Mike Stump1eb44332009-09-09 15:08:12 +00001718
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001719 // An rvalue of type bool can be converted to an rvalue of type int,
1720 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001721 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001722 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001723 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001724
1725 return false;
1726}
1727
1728/// IsFloatingPointPromotion - Determines whether the conversion from
1729/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1730/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001731bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001732 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1733 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001734 /// An rvalue of type float can be converted to an rvalue of type
1735 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001736 if (FromBuiltin->getKind() == BuiltinType::Float &&
1737 ToBuiltin->getKind() == BuiltinType::Double)
1738 return true;
1739
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001740 // C99 6.3.1.5p1:
1741 // When a float is promoted to double or long double, or a
1742 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001743 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001744 (FromBuiltin->getKind() == BuiltinType::Float ||
1745 FromBuiltin->getKind() == BuiltinType::Double) &&
1746 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1747 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001748
1749 // Half can be promoted to float.
1750 if (FromBuiltin->getKind() == BuiltinType::Half &&
1751 ToBuiltin->getKind() == BuiltinType::Float)
1752 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001753 }
1754
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001755 return false;
1756}
1757
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001758/// \brief Determine if a conversion is a complex promotion.
1759///
1760/// A complex promotion is defined as a complex -> complex conversion
1761/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001762/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001763bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001764 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001765 if (!FromComplex)
1766 return false;
1767
John McCall183700f2009-09-21 23:43:11 +00001768 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001769 if (!ToComplex)
1770 return false;
1771
1772 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001773 ToComplex->getElementType()) ||
1774 IsIntegralPromotion(0, FromComplex->getElementType(),
1775 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001776}
1777
Douglas Gregorcb7de522008-11-26 23:31:11 +00001778/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1779/// the pointer type FromPtr to a pointer to type ToPointee, with the
1780/// same type qualifiers as FromPtr has on its pointee type. ToType,
1781/// if non-empty, will be a pointer to ToType that may or may not have
1782/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001783///
Mike Stump1eb44332009-09-09 15:08:12 +00001784static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001785BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001786 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001787 ASTContext &Context,
1788 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001789 assert((FromPtr->getTypeClass() == Type::Pointer ||
1790 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1791 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001792
John McCallf85e1932011-06-15 23:02:42 +00001793 /// Conversions to 'id' subsume cv-qualifier conversions.
1794 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001795 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001796
1797 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001798 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001799 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001800 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001801
John McCallf85e1932011-06-15 23:02:42 +00001802 if (StripObjCLifetime)
1803 Quals.removeObjCLifetime();
1804
Mike Stump1eb44332009-09-09 15:08:12 +00001805 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001806 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001807 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001808 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001809 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001810
1811 // Build a pointer to ToPointee. It has the right qualifiers
1812 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001813 if (isa<ObjCObjectPointerType>(ToType))
1814 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001815 return Context.getPointerType(ToPointee);
1816 }
1817
1818 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001819 QualType QualifiedCanonToPointee
1820 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001821
Douglas Gregorda80f742010-12-01 21:43:58 +00001822 if (isa<ObjCObjectPointerType>(ToType))
1823 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1824 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001825}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001826
Mike Stump1eb44332009-09-09 15:08:12 +00001827static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001828 bool InOverloadResolution,
1829 ASTContext &Context) {
1830 // Handle value-dependent integral null pointer constants correctly.
1831 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1832 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001833 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001834 return !InOverloadResolution;
1835
Douglas Gregorce940492009-09-25 04:25:58 +00001836 return Expr->isNullPointerConstant(Context,
1837 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1838 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001839}
Mike Stump1eb44332009-09-09 15:08:12 +00001840
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001841/// IsPointerConversion - Determines whether the conversion of the
1842/// expression From, which has the (possibly adjusted) type FromType,
1843/// can be converted to the type ToType via a pointer conversion (C++
1844/// 4.10). If so, returns true and places the converted type (that
1845/// might differ from ToType in its cv-qualifiers at some level) into
1846/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001847///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001848/// This routine also supports conversions to and from block pointers
1849/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1850/// pointers to interfaces. FIXME: Once we've determined the
1851/// appropriate overloading rules for Objective-C, we may want to
1852/// split the Objective-C checks into a different routine; however,
1853/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001854/// conversions, so for now they live here. IncompatibleObjC will be
1855/// set if the conversion is an allowed Objective-C conversion that
1856/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001857bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001858 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001859 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001860 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001861 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001862 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1863 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001864 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001865
Mike Stump1eb44332009-09-09 15:08:12 +00001866 // Conversion from a null pointer constant to any Objective-C pointer type.
1867 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001868 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001869 ConvertedType = ToType;
1870 return true;
1871 }
1872
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001873 // Blocks: Block pointers can be converted to void*.
1874 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001875 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001876 ConvertedType = ToType;
1877 return true;
1878 }
1879 // Blocks: A null pointer constant can be converted to a block
1880 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001881 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001882 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001883 ConvertedType = ToType;
1884 return true;
1885 }
1886
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001887 // If the left-hand-side is nullptr_t, the right side can be a null
1888 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001889 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001890 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001891 ConvertedType = ToType;
1892 return true;
1893 }
1894
Ted Kremenek6217b802009-07-29 21:53:49 +00001895 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001896 if (!ToTypePtr)
1897 return false;
1898
1899 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001900 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001901 ConvertedType = ToType;
1902 return true;
1903 }
Sebastian Redl07779722008-10-31 14:43:28 +00001904
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001905 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001906 // , including objective-c pointers.
1907 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001908 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001909 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001910 ConvertedType = BuildSimilarlyQualifiedPointerType(
1911 FromType->getAs<ObjCObjectPointerType>(),
1912 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001913 ToType, Context);
1914 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001915 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001916 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001917 if (!FromTypePtr)
1918 return false;
1919
1920 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001921
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001922 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001923 // pointer conversion, so don't do all of the work below.
1924 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1925 return false;
1926
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001927 // An rvalue of type "pointer to cv T," where T is an object type,
1928 // can be converted to an rvalue of type "pointer to cv void" (C++
1929 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001930 if (FromPointeeType->isIncompleteOrObjectType() &&
1931 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001932 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001933 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001934 ToType, Context,
1935 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001936 return true;
1937 }
1938
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001939 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001940 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001941 ToPointeeType->isVoidType()) {
1942 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1943 ToPointeeType,
1944 ToType, Context);
1945 return true;
1946 }
1947
Douglas Gregorf9201e02009-02-11 23:02:49 +00001948 // When we're overloading in C, we allow a special kind of pointer
1949 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00001950 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001951 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001952 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001953 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001954 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001955 return true;
1956 }
1957
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001958 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001959 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001960 // An rvalue of type "pointer to cv D," where D is a class type,
1961 // can be converted to an rvalue of type "pointer to cv B," where
1962 // B is a base class (clause 10) of D. If B is an inaccessible
1963 // (clause 11) or ambiguous (10.2) base class of D, a program that
1964 // necessitates this conversion is ill-formed. The result of the
1965 // conversion is a pointer to the base class sub-object of the
1966 // derived class object. The null pointer value is converted to
1967 // the null pointer value of the destination type.
1968 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001969 // Note that we do not check for ambiguity or inaccessibility
1970 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00001971 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001972 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001973 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001974 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001975 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001976 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001977 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001978 ToType, Context);
1979 return true;
1980 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001981
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001982 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1983 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1984 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1985 ToPointeeType,
1986 ToType, Context);
1987 return true;
1988 }
1989
Douglas Gregorc7887512008-12-19 19:13:09 +00001990 return false;
1991}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001992
1993/// \brief Adopt the given qualifiers for the given type.
1994static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1995 Qualifiers TQs = T.getQualifiers();
1996
1997 // Check whether qualifiers already match.
1998 if (TQs == Qs)
1999 return T;
2000
2001 if (Qs.compatiblyIncludes(TQs))
2002 return Context.getQualifiedType(T, Qs);
2003
2004 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2005}
Douglas Gregorc7887512008-12-19 19:13:09 +00002006
2007/// isObjCPointerConversion - Determines whether this is an
2008/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2009/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002010bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002011 QualType& ConvertedType,
2012 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002013 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002014 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002015
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002016 // The set of qualifiers on the type we're converting from.
2017 Qualifiers FromQualifiers = FromType.getQualifiers();
2018
Steve Naroff14108da2009-07-10 23:34:53 +00002019 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002020 const ObjCObjectPointerType* ToObjCPtr =
2021 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002022 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002023 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002024
Steve Naroff14108da2009-07-10 23:34:53 +00002025 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002026 // If the pointee types are the same (ignoring qualifications),
2027 // then this is not a pointer conversion.
2028 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2029 FromObjCPtr->getPointeeType()))
2030 return false;
2031
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002032 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002033 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002034 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002035 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002036 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002037 return true;
2038 }
2039 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002040 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002041 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002042 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002043 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002044 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002045 return true;
2046 }
2047 // Objective C++: We're able to convert from a pointer to an
2048 // interface to a pointer to a different interface.
2049 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002050 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2051 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002052 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002053 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2054 FromObjCPtr->getPointeeType()))
2055 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002057 ToObjCPtr->getPointeeType(),
2058 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002059 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002060 return true;
2061 }
2062
2063 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2064 // Okay: this is some kind of implicit downcast of Objective-C
2065 // interfaces, which is permitted. However, we're going to
2066 // complain about it.
2067 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002068 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002069 ToObjCPtr->getPointeeType(),
2070 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002071 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002072 return true;
2073 }
Mike Stump1eb44332009-09-09 15:08:12 +00002074 }
Steve Naroff14108da2009-07-10 23:34:53 +00002075 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002076 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002077 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002078 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002079 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002080 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002081 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002082 // to a block pointer type.
2083 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002084 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002085 return true;
2086 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002087 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002088 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002089 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002090 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002091 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002092 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002093 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002094 return true;
2095 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002096 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002097 return false;
2098
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002099 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002100 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002101 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002102 else if (const BlockPointerType *FromBlockPtr =
2103 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002104 FromPointeeType = FromBlockPtr->getPointeeType();
2105 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002106 return false;
2107
Douglas Gregorc7887512008-12-19 19:13:09 +00002108 // If we have pointers to pointers, recursively check whether this
2109 // is an Objective-C conversion.
2110 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2111 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2112 IncompatibleObjC)) {
2113 // We always complain about this conversion.
2114 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002115 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002116 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002117 return true;
2118 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002119 // Allow conversion of pointee being objective-c pointer to another one;
2120 // as in I* to id.
2121 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2122 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2123 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2124 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002125
Douglas Gregorda80f742010-12-01 21:43:58 +00002126 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002127 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002128 return true;
2129 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002130
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002131 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002132 // differences in the argument and result types are in Objective-C
2133 // pointer conversions. If so, we permit the conversion (but
2134 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002135 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002136 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002137 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002138 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002139 if (FromFunctionType && ToFunctionType) {
2140 // If the function types are exactly the same, this isn't an
2141 // Objective-C pointer conversion.
2142 if (Context.getCanonicalType(FromPointeeType)
2143 == Context.getCanonicalType(ToPointeeType))
2144 return false;
2145
2146 // Perform the quick checks that will tell us whether these
2147 // function types are obviously different.
2148 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2149 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2150 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2151 return false;
2152
2153 bool HasObjCConversion = false;
2154 if (Context.getCanonicalType(FromFunctionType->getResultType())
2155 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2156 // Okay, the types match exactly. Nothing to do.
2157 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2158 ToFunctionType->getResultType(),
2159 ConvertedType, IncompatibleObjC)) {
2160 // Okay, we have an Objective-C pointer conversion.
2161 HasObjCConversion = true;
2162 } else {
2163 // Function types are too different. Abort.
2164 return false;
2165 }
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Douglas Gregorc7887512008-12-19 19:13:09 +00002167 // Check argument types.
2168 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2169 ArgIdx != NumArgs; ++ArgIdx) {
2170 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2171 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2172 if (Context.getCanonicalType(FromArgType)
2173 == Context.getCanonicalType(ToArgType)) {
2174 // Okay, the types match exactly. Nothing to do.
2175 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2176 ConvertedType, IncompatibleObjC)) {
2177 // Okay, we have an Objective-C pointer conversion.
2178 HasObjCConversion = true;
2179 } else {
2180 // Argument types are too different. Abort.
2181 return false;
2182 }
2183 }
2184
2185 if (HasObjCConversion) {
2186 // We had an Objective-C conversion. Allow this pointer
2187 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002189 IncompatibleObjC = true;
2190 return true;
2191 }
2192 }
2193
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002194 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002195}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002196
John McCallf85e1932011-06-15 23:02:42 +00002197/// \brief Determine whether this is an Objective-C writeback conversion,
2198/// used for parameter passing when performing automatic reference counting.
2199///
2200/// \param FromType The type we're converting form.
2201///
2202/// \param ToType The type we're converting to.
2203///
2204/// \param ConvertedType The type that will be produced after applying
2205/// this conversion.
2206bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2207 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002208 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002209 Context.hasSameUnqualifiedType(FromType, ToType))
2210 return false;
2211
2212 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2213 QualType ToPointee;
2214 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2215 ToPointee = ToPointer->getPointeeType();
2216 else
2217 return false;
2218
2219 Qualifiers ToQuals = ToPointee.getQualifiers();
2220 if (!ToPointee->isObjCLifetimeType() ||
2221 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002222 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002223 return false;
2224
2225 // Argument must be a pointer to __strong to __weak.
2226 QualType FromPointee;
2227 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2228 FromPointee = FromPointer->getPointeeType();
2229 else
2230 return false;
2231
2232 Qualifiers FromQuals = FromPointee.getQualifiers();
2233 if (!FromPointee->isObjCLifetimeType() ||
2234 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2235 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2236 return false;
2237
2238 // Make sure that we have compatible qualifiers.
2239 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2240 if (!ToQuals.compatiblyIncludes(FromQuals))
2241 return false;
2242
2243 // Remove qualifiers from the pointee type we're converting from; they
2244 // aren't used in the compatibility check belong, and we'll be adding back
2245 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2246 FromPointee = FromPointee.getUnqualifiedType();
2247
2248 // The unqualified form of the pointee types must be compatible.
2249 ToPointee = ToPointee.getUnqualifiedType();
2250 bool IncompatibleObjC;
2251 if (Context.typesAreCompatible(FromPointee, ToPointee))
2252 FromPointee = ToPointee;
2253 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2254 IncompatibleObjC))
2255 return false;
2256
2257 /// \brief Construct the type we're converting to, which is a pointer to
2258 /// __autoreleasing pointee.
2259 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2260 ConvertedType = Context.getPointerType(FromPointee);
2261 return true;
2262}
2263
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002264bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2265 QualType& ConvertedType) {
2266 QualType ToPointeeType;
2267 if (const BlockPointerType *ToBlockPtr =
2268 ToType->getAs<BlockPointerType>())
2269 ToPointeeType = ToBlockPtr->getPointeeType();
2270 else
2271 return false;
2272
2273 QualType FromPointeeType;
2274 if (const BlockPointerType *FromBlockPtr =
2275 FromType->getAs<BlockPointerType>())
2276 FromPointeeType = FromBlockPtr->getPointeeType();
2277 else
2278 return false;
2279 // We have pointer to blocks, check whether the only
2280 // differences in the argument and result types are in Objective-C
2281 // pointer conversions. If so, we permit the conversion.
2282
2283 const FunctionProtoType *FromFunctionType
2284 = FromPointeeType->getAs<FunctionProtoType>();
2285 const FunctionProtoType *ToFunctionType
2286 = ToPointeeType->getAs<FunctionProtoType>();
2287
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002288 if (!FromFunctionType || !ToFunctionType)
2289 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002290
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002291 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002292 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002293
2294 // Perform the quick checks that will tell us whether these
2295 // function types are obviously different.
2296 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2297 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2298 return false;
2299
2300 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2301 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2302 if (FromEInfo != ToEInfo)
2303 return false;
2304
2305 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002306 if (Context.hasSameType(FromFunctionType->getResultType(),
2307 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002308 // Okay, the types match exactly. Nothing to do.
2309 } else {
2310 QualType RHS = FromFunctionType->getResultType();
2311 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002312 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002313 !RHS.hasQualifiers() && LHS.hasQualifiers())
2314 LHS = LHS.getUnqualifiedType();
2315
2316 if (Context.hasSameType(RHS,LHS)) {
2317 // OK exact match.
2318 } else if (isObjCPointerConversion(RHS, LHS,
2319 ConvertedType, IncompatibleObjC)) {
2320 if (IncompatibleObjC)
2321 return false;
2322 // Okay, we have an Objective-C pointer conversion.
2323 }
2324 else
2325 return false;
2326 }
2327
2328 // Check argument types.
2329 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2330 ArgIdx != NumArgs; ++ArgIdx) {
2331 IncompatibleObjC = false;
2332 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2333 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2334 if (Context.hasSameType(FromArgType, ToArgType)) {
2335 // Okay, the types match exactly. Nothing to do.
2336 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2337 ConvertedType, IncompatibleObjC)) {
2338 if (IncompatibleObjC)
2339 return false;
2340 // Okay, we have an Objective-C pointer conversion.
2341 } else
2342 // Argument types are too different. Abort.
2343 return false;
2344 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002345 if (LangOpts.ObjCAutoRefCount &&
2346 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2347 ToFunctionType))
2348 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002349
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002350 ConvertedType = ToType;
2351 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002352}
2353
Richard Trieu6efd4c52011-11-23 22:32:32 +00002354enum {
2355 ft_default,
2356 ft_different_class,
2357 ft_parameter_arity,
2358 ft_parameter_mismatch,
2359 ft_return_type,
2360 ft_qualifer_mismatch
2361};
2362
2363/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2364/// function types. Catches different number of parameter, mismatch in
2365/// parameter types, and different return types.
2366void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2367 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002368 // If either type is not valid, include no extra info.
2369 if (FromType.isNull() || ToType.isNull()) {
2370 PDiag << ft_default;
2371 return;
2372 }
2373
Richard Trieu6efd4c52011-11-23 22:32:32 +00002374 // Get the function type from the pointers.
2375 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2376 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2377 *ToMember = ToType->getAs<MemberPointerType>();
2378 if (FromMember->getClass() != ToMember->getClass()) {
2379 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2380 << QualType(FromMember->getClass(), 0);
2381 return;
2382 }
2383 FromType = FromMember->getPointeeType();
2384 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002385 }
2386
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002387 if (FromType->isPointerType())
2388 FromType = FromType->getPointeeType();
2389 if (ToType->isPointerType())
2390 ToType = ToType->getPointeeType();
2391
2392 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002393 FromType = FromType.getNonReferenceType();
2394 ToType = ToType.getNonReferenceType();
2395
Richard Trieu6efd4c52011-11-23 22:32:32 +00002396 // Don't print extra info for non-specialized template functions.
2397 if (FromType->isInstantiationDependentType() &&
2398 !FromType->getAs<TemplateSpecializationType>()) {
2399 PDiag << ft_default;
2400 return;
2401 }
2402
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002403 // No extra info for same types.
2404 if (Context.hasSameType(FromType, ToType)) {
2405 PDiag << ft_default;
2406 return;
2407 }
2408
Richard Trieu6efd4c52011-11-23 22:32:32 +00002409 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2410 *ToFunction = ToType->getAs<FunctionProtoType>();
2411
2412 // Both types need to be function types.
2413 if (!FromFunction || !ToFunction) {
2414 PDiag << ft_default;
2415 return;
2416 }
2417
2418 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2419 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2420 << FromFunction->getNumArgs();
2421 return;
2422 }
2423
2424 // Handle different parameter types.
2425 unsigned ArgPos;
2426 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2427 PDiag << ft_parameter_mismatch << ArgPos + 1
2428 << ToFunction->getArgType(ArgPos)
2429 << FromFunction->getArgType(ArgPos);
2430 return;
2431 }
2432
2433 // Handle different return type.
2434 if (!Context.hasSameType(FromFunction->getResultType(),
2435 ToFunction->getResultType())) {
2436 PDiag << ft_return_type << ToFunction->getResultType()
2437 << FromFunction->getResultType();
2438 return;
2439 }
2440
2441 unsigned FromQuals = FromFunction->getTypeQuals(),
2442 ToQuals = ToFunction->getTypeQuals();
2443 if (FromQuals != ToQuals) {
2444 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2445 return;
2446 }
2447
2448 // Unable to find a difference, so add no extra info.
2449 PDiag << ft_default;
2450}
2451
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002452/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002453/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002454/// they have same number of arguments. This routine assumes that Objective-C
2455/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002456/// If the parameters are different, ArgPos will have the the parameter index
2457/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002458bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002459 const FunctionProtoType *NewType,
2460 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002461 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002462 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2463 N = NewType->arg_type_begin(),
2464 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2465 if (!Context.hasSameType(*O, *N)) {
2466 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2467 return false;
2468 }
2469 }
2470 return true;
2471 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002472
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002473 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2474 N = NewType->arg_type_begin(),
2475 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2476 QualType ToType = (*O);
2477 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002478 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002479 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2480 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002481 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2482 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2483 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2484 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002485 continue;
2486 }
John McCallc12c5bb2010-05-15 11:32:37 +00002487 else if (const ObjCObjectPointerType *PTTo =
2488 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002489 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002490 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002491 if (Context.hasSameUnqualifiedType(
2492 PTTo->getObjectType()->getBaseType(),
2493 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002494 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002495 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002496 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002497 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002498 }
2499 }
2500 return true;
2501}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002502
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002503/// CheckPointerConversion - Check the pointer conversion from the
2504/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002505/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002506/// conversions for which IsPointerConversion has already returned
2507/// true. It returns true and produces a diagnostic if there was an
2508/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002509bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002510 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002511 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002512 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002513 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002514 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002515
John McCalldaa8e4e2010-11-15 09:13:47 +00002516 Kind = CK_BitCast;
2517
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002518 if (!IsCStyleOrFunctionalCast &&
2519 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2520 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2521 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002522 PDiag(diag::warn_impcast_bool_to_null_pointer)
2523 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002524
John McCall1d9b3b22011-09-09 05:25:32 +00002525 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2526 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002527 QualType FromPointeeType = FromPtrType->getPointeeType(),
2528 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002529
Douglas Gregor5fccd362010-03-03 23:55:11 +00002530 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2531 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002532 // We must have a derived-to-base conversion. Check an
2533 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002534 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2535 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002536 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002537 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002538 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002539
Anders Carlsson61faec12009-09-12 04:46:44 +00002540 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002541 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002542 }
2543 }
John McCall1d9b3b22011-09-09 05:25:32 +00002544 } else if (const ObjCObjectPointerType *ToPtrType =
2545 ToType->getAs<ObjCObjectPointerType>()) {
2546 if (const ObjCObjectPointerType *FromPtrType =
2547 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002548 // Objective-C++ conversions are always okay.
2549 // FIXME: We should have a different class of conversions for the
2550 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002551 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002552 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002553 } else if (FromType->isBlockPointerType()) {
2554 Kind = CK_BlockPointerToObjCPointerCast;
2555 } else {
2556 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002557 }
John McCall1d9b3b22011-09-09 05:25:32 +00002558 } else if (ToType->isBlockPointerType()) {
2559 if (!FromType->isBlockPointerType())
2560 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002561 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002562
2563 // We shouldn't fall into this case unless it's valid for other
2564 // reasons.
2565 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2566 Kind = CK_NullToPointer;
2567
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002568 return false;
2569}
2570
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002571/// IsMemberPointerConversion - Determines whether the conversion of the
2572/// expression From, which has the (possibly adjusted) type FromType, can be
2573/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2574/// If so, returns true and places the converted type (that might differ from
2575/// ToType in its cv-qualifiers at some level) into ConvertedType.
2576bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002577 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002578 bool InOverloadResolution,
2579 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002580 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002581 if (!ToTypePtr)
2582 return false;
2583
2584 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002585 if (From->isNullPointerConstant(Context,
2586 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2587 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002588 ConvertedType = ToType;
2589 return true;
2590 }
2591
2592 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002593 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002594 if (!FromTypePtr)
2595 return false;
2596
2597 // A pointer to member of B can be converted to a pointer to member of D,
2598 // where D is derived from B (C++ 4.11p2).
2599 QualType FromClass(FromTypePtr->getClass(), 0);
2600 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002601
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002602 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2603 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2604 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002605 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2606 ToClass.getTypePtr());
2607 return true;
2608 }
2609
2610 return false;
2611}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002612
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002613/// CheckMemberPointerConversion - Check the member pointer conversion from the
2614/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002615/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002616/// for which IsMemberPointerConversion has already returned true. It returns
2617/// true and produces a diagnostic if there was an error, or returns false
2618/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002619bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002620 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002621 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002622 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002623 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002624 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002625 if (!FromPtrType) {
2626 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002627 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002628 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002629 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002630 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002631 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002632 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002633
Ted Kremenek6217b802009-07-29 21:53:49 +00002634 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002635 assert(ToPtrType && "No member pointer cast has a target type "
2636 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002637
Sebastian Redl21593ac2009-01-28 18:33:18 +00002638 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2639 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002640
Sebastian Redl21593ac2009-01-28 18:33:18 +00002641 // FIXME: What about dependent types?
2642 assert(FromClass->isRecordType() && "Pointer into non-class.");
2643 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002644
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002645 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002646 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002647 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2648 assert(DerivationOkay &&
2649 "Should not have been called if derivation isn't OK.");
2650 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002651
Sebastian Redl21593ac2009-01-28 18:33:18 +00002652 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2653 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002654 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2655 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2656 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2657 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002658 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002659
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002660 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002661 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2662 << FromClass << ToClass << QualType(VBase, 0)
2663 << From->getSourceRange();
2664 return true;
2665 }
2666
John McCall6b2accb2010-02-10 09:31:12 +00002667 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002668 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2669 Paths.front(),
2670 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002671
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002672 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002673 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002674 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002675 return false;
2676}
2677
Douglas Gregor98cd5992008-10-21 23:43:52 +00002678/// IsQualificationConversion - Determines whether the conversion from
2679/// an rvalue of type FromType to ToType is a qualification conversion
2680/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002681///
2682/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2683/// when the qualification conversion involves a change in the Objective-C
2684/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002685bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002686Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002687 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002688 FromType = Context.getCanonicalType(FromType);
2689 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002690 ObjCLifetimeConversion = false;
2691
Douglas Gregor98cd5992008-10-21 23:43:52 +00002692 // If FromType and ToType are the same type, this is not a
2693 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002694 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002695 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002696
Douglas Gregor98cd5992008-10-21 23:43:52 +00002697 // (C++ 4.4p4):
2698 // A conversion can add cv-qualifiers at levels other than the first
2699 // in multi-level pointers, subject to the following rules: [...]
2700 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002701 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002702 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002703 // Within each iteration of the loop, we check the qualifiers to
2704 // determine if this still looks like a qualification
2705 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002706 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002707 // until there are no more pointers or pointers-to-members left to
2708 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002709 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002710
Douglas Gregor621c92a2011-04-25 18:40:17 +00002711 Qualifiers FromQuals = FromType.getQualifiers();
2712 Qualifiers ToQuals = ToType.getQualifiers();
2713
John McCallf85e1932011-06-15 23:02:42 +00002714 // Objective-C ARC:
2715 // Check Objective-C lifetime conversions.
2716 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2717 UnwrappedAnyPointer) {
2718 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2719 ObjCLifetimeConversion = true;
2720 FromQuals.removeObjCLifetime();
2721 ToQuals.removeObjCLifetime();
2722 } else {
2723 // Qualification conversions cannot cast between different
2724 // Objective-C lifetime qualifiers.
2725 return false;
2726 }
2727 }
2728
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002729 // Allow addition/removal of GC attributes but not changing GC attributes.
2730 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2731 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2732 FromQuals.removeObjCGCAttr();
2733 ToQuals.removeObjCGCAttr();
2734 }
2735
Douglas Gregor98cd5992008-10-21 23:43:52 +00002736 // -- for every j > 0, if const is in cv 1,j then const is in cv
2737 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002738 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002739 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002740
Douglas Gregor98cd5992008-10-21 23:43:52 +00002741 // -- if the cv 1,j and cv 2,j are different, then const is in
2742 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002743 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002744 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002745 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002746
Douglas Gregor98cd5992008-10-21 23:43:52 +00002747 // Keep track of whether all prior cv-qualifiers in the "to" type
2748 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002749 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002750 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002751 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002752
2753 // We are left with FromType and ToType being the pointee types
2754 // after unwrapping the original FromType and ToType the same number
2755 // of types. If we unwrapped any pointers, and if FromType and
2756 // ToType have the same unqualified type (since we checked
2757 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002758 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002759}
2760
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002761static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2762 CXXConstructorDecl *Constructor,
2763 QualType Type) {
2764 const FunctionProtoType *CtorType =
2765 Constructor->getType()->getAs<FunctionProtoType>();
2766 if (CtorType->getNumArgs() > 0) {
2767 QualType FirstArg = CtorType->getArgType(0);
2768 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2769 return true;
2770 }
2771 return false;
2772}
2773
Sebastian Redl56a04282012-02-11 23:51:08 +00002774static OverloadingResult
2775IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2776 CXXRecordDecl *To,
2777 UserDefinedConversionSequence &User,
2778 OverloadCandidateSet &CandidateSet,
2779 bool AllowExplicit) {
2780 DeclContext::lookup_iterator Con, ConEnd;
2781 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(To);
2782 Con != ConEnd; ++Con) {
2783 NamedDecl *D = *Con;
2784 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2785
2786 // Find the constructor (which may be a template).
2787 CXXConstructorDecl *Constructor = 0;
2788 FunctionTemplateDecl *ConstructorTmpl
2789 = dyn_cast<FunctionTemplateDecl>(D);
2790 if (ConstructorTmpl)
2791 Constructor
2792 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2793 else
2794 Constructor = cast<CXXConstructorDecl>(D);
2795
2796 bool Usable = !Constructor->isInvalidDecl() &&
2797 S.isInitListConstructor(Constructor) &&
2798 (AllowExplicit || !Constructor->isExplicit());
2799 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002800 // If the first argument is (a reference to) the target type,
2801 // suppress conversions.
2802 bool SuppressUserConversions =
2803 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002804 if (ConstructorTmpl)
2805 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2806 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002807 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002808 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002809 else
2810 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002811 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002812 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002813 }
2814 }
2815
2816 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2817
2818 OverloadCandidateSet::iterator Best;
2819 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2820 case OR_Success: {
2821 // Record the standard conversion we used and the conversion function.
2822 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
2823 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
2824
2825 QualType ThisType = Constructor->getThisType(S.Context);
2826 // Initializer lists don't have conversions as such.
2827 User.Before.setAsIdentityConversion();
2828 User.HadMultipleCandidates = HadMultipleCandidates;
2829 User.ConversionFunction = Constructor;
2830 User.FoundConversionFunction = Best->FoundDecl;
2831 User.After.setAsIdentityConversion();
2832 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2833 User.After.setAllToTypes(ToType);
2834 return OR_Success;
2835 }
2836
2837 case OR_No_Viable_Function:
2838 return OR_No_Viable_Function;
2839 case OR_Deleted:
2840 return OR_Deleted;
2841 case OR_Ambiguous:
2842 return OR_Ambiguous;
2843 }
2844
2845 llvm_unreachable("Invalid OverloadResult!");
2846}
2847
Douglas Gregor734d9862009-01-30 23:27:23 +00002848/// Determines whether there is a user-defined conversion sequence
2849/// (C++ [over.ics.user]) that converts expression From to the type
2850/// ToType. If such a conversion exists, User will contain the
2851/// user-defined conversion sequence that performs such a conversion
2852/// and this routine will return true. Otherwise, this routine returns
2853/// false and User is unspecified.
2854///
Douglas Gregor734d9862009-01-30 23:27:23 +00002855/// \param AllowExplicit true if the conversion should consider C++0x
2856/// "explicit" conversion functions as well as non-explicit conversion
2857/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002858static OverloadingResult
2859IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002860 UserDefinedConversionSequence &User,
2861 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002862 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002863 // Whether we will only visit constructors.
2864 bool ConstructorsOnly = false;
2865
2866 // If the type we are conversion to is a class type, enumerate its
2867 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002868 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002869 // C++ [over.match.ctor]p1:
2870 // When objects of class type are direct-initialized (8.5), or
2871 // copy-initialized from an expression of the same or a
2872 // derived class type (8.5), overload resolution selects the
2873 // constructor. [...] For copy-initialization, the candidate
2874 // functions are all the converting constructors (12.3.1) of
2875 // that class. The argument list is the expression-list within
2876 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002877 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002878 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002879 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002880 ConstructorsOnly = true;
2881
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002882 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2883 // RequireCompleteType may have returned true due to some invalid decl
2884 // during template instantiation, but ToType may be complete enough now
2885 // to try to recover.
2886 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002887 // We're not going to find any constructors.
2888 } else if (CXXRecordDecl *ToRecordDecl
2889 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002890
2891 Expr **Args = &From;
2892 unsigned NumArgs = 1;
2893 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002894 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002895 // But first, see if there is an init-list-contructor that will work.
2896 OverloadingResult Result = IsInitializerListConstructorConversion(
2897 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
2898 if (Result != OR_No_Viable_Function)
2899 return Result;
2900 // Never mind.
2901 CandidateSet.clear();
2902
2903 // If we're list-initializing, we pass the individual elements as
2904 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002905 Args = InitList->getInits();
2906 NumArgs = InitList->getNumInits();
2907 ListInitializing = true;
2908 }
2909
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002910 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002911 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002912 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002913 NamedDecl *D = *Con;
2914 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2915
Douglas Gregordec06662009-08-21 18:42:58 +00002916 // Find the constructor (which may be a template).
2917 CXXConstructorDecl *Constructor = 0;
2918 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002919 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002920 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002921 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002922 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2923 else
John McCall9aa472c2010-03-19 07:35:19 +00002924 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002925
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002926 bool Usable = !Constructor->isInvalidDecl();
2927 if (ListInitializing)
2928 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
2929 else
2930 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
2931 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002932 bool SuppressUserConversions = !ConstructorsOnly;
2933 if (SuppressUserConversions && ListInitializing) {
2934 SuppressUserConversions = false;
2935 if (NumArgs == 1) {
2936 // If the first argument is (a reference to) the target type,
2937 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002938 SuppressUserConversions = isFirstArgumentCompatibleWithType(
2939 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002940 }
2941 }
Douglas Gregordec06662009-08-21 18:42:58 +00002942 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002943 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2944 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002945 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002946 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00002947 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002948 // Allow one user-defined conversion when user specifies a
2949 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002950 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002951 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00002952 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00002953 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002954 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002955 }
2956 }
2957
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002958 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002959 if (ConstructorsOnly || isa<InitListExpr>(From)) {
John McCall120d63c2010-08-24 20:38:10 +00002960 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2961 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002962 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002963 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002964 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002965 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002966 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2967 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002968 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002969 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002970 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002971 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002972 DeclAccessPair FoundDecl = I.getPair();
2973 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002974 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2975 if (isa<UsingShadowDecl>(D))
2976 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2977
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002978 CXXConversionDecl *Conv;
2979 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002980 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2981 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002982 else
John McCall32daa422010-03-31 01:36:47 +00002983 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002984
2985 if (AllowExplicit || !Conv->isExplicit()) {
2986 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002987 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2988 ActingContext, From, ToType,
2989 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002990 else
John McCall120d63c2010-08-24 20:38:10 +00002991 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2992 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002993 }
2994 }
2995 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002996 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002997
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002998 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2999
Douglas Gregor60d62c22008-10-31 16:23:19 +00003000 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003001 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003002 case OR_Success:
3003 // Record the standard conversion we used and the conversion function.
3004 if (CXXConstructorDecl *Constructor
3005 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003006 S.MarkFunctionReferenced(From->getLocStart(), Constructor);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003007
John McCall120d63c2010-08-24 20:38:10 +00003008 // C++ [over.ics.user]p1:
3009 // If the user-defined conversion is specified by a
3010 // constructor (12.3.1), the initial standard conversion
3011 // sequence converts the source type to the type required by
3012 // the argument of the constructor.
3013 //
3014 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003015 if (isa<InitListExpr>(From)) {
3016 // Initializer lists don't have conversions as such.
3017 User.Before.setAsIdentityConversion();
3018 } else {
3019 if (Best->Conversions[0].isEllipsis())
3020 User.EllipsisConversion = true;
3021 else {
3022 User.Before = Best->Conversions[0].Standard;
3023 User.EllipsisConversion = false;
3024 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003025 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003026 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003027 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003028 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003029 User.After.setAsIdentityConversion();
3030 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3031 User.After.setAllToTypes(ToType);
3032 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003033 }
3034 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003035 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00003036 S.MarkFunctionReferenced(From->getLocStart(), Conversion);
Chandler Carruth25ca4212011-02-25 19:41:05 +00003037
John McCall120d63c2010-08-24 20:38:10 +00003038 // C++ [over.ics.user]p1:
3039 //
3040 // [...] If the user-defined conversion is specified by a
3041 // conversion function (12.3.2), the initial standard
3042 // conversion sequence converts the source type to the
3043 // implicit object parameter of the conversion function.
3044 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003045 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003046 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003047 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003048 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003049
John McCall120d63c2010-08-24 20:38:10 +00003050 // C++ [over.ics.user]p2:
3051 // The second standard conversion sequence converts the
3052 // result of the user-defined conversion to the target type
3053 // for the sequence. Since an implicit conversion sequence
3054 // is an initialization, the special rules for
3055 // initialization by user-defined conversion apply when
3056 // selecting the best user-defined conversion for a
3057 // user-defined conversion sequence (see 13.3.3 and
3058 // 13.3.3.1).
3059 User.After = Best->FinalConversion;
3060 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003061 }
David Blaikie7530c032012-01-17 06:56:22 +00003062 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003063
John McCall120d63c2010-08-24 20:38:10 +00003064 case OR_No_Viable_Function:
3065 return OR_No_Viable_Function;
3066 case OR_Deleted:
3067 // No conversion here! We're done.
3068 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003069
John McCall120d63c2010-08-24 20:38:10 +00003070 case OR_Ambiguous:
3071 return OR_Ambiguous;
3072 }
3073
David Blaikie7530c032012-01-17 06:56:22 +00003074 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003075}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003076
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003077bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003078Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003079 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003080 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003081 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003082 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003083 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003084 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003085 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003086 diag::err_typecheck_ambiguous_condition)
3087 << From->getType() << ToType << From->getSourceRange();
3088 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003089 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003090 diag::err_typecheck_nonviable_condition)
3091 << From->getType() << ToType << From->getSourceRange();
3092 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003093 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003094 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003095 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003096}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003097
Douglas Gregorb734e242012-02-22 17:32:19 +00003098/// \brief Compare the user-defined conversion functions or constructors
3099/// of two user-defined conversion sequences to determine whether any ordering
3100/// is possible.
3101static ImplicitConversionSequence::CompareKind
3102compareConversionFunctions(Sema &S,
3103 FunctionDecl *Function1,
3104 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003105 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003106 return ImplicitConversionSequence::Indistinguishable;
3107
3108 // Objective-C++:
3109 // If both conversion functions are implicitly-declared conversions from
3110 // a lambda closure type to a function pointer and a block pointer,
3111 // respectively, always prefer the conversion to a function pointer,
3112 // because the function pointer is more lightweight and is more likely
3113 // to keep code working.
3114 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3115 if (!Conv1)
3116 return ImplicitConversionSequence::Indistinguishable;
3117
3118 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3119 if (!Conv2)
3120 return ImplicitConversionSequence::Indistinguishable;
3121
3122 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3123 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3124 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3125 if (Block1 != Block2)
3126 return Block1? ImplicitConversionSequence::Worse
3127 : ImplicitConversionSequence::Better;
3128 }
3129
3130 return ImplicitConversionSequence::Indistinguishable;
3131}
3132
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003133/// CompareImplicitConversionSequences - Compare two implicit
3134/// conversion sequences to determine whether one is better than the
3135/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003136static ImplicitConversionSequence::CompareKind
3137CompareImplicitConversionSequences(Sema &S,
3138 const ImplicitConversionSequence& ICS1,
3139 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003140{
3141 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3142 // conversion sequences (as defined in 13.3.3.1)
3143 // -- a standard conversion sequence (13.3.3.1.1) is a better
3144 // conversion sequence than a user-defined conversion sequence or
3145 // an ellipsis conversion sequence, and
3146 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3147 // conversion sequence than an ellipsis conversion sequence
3148 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003149 //
John McCall1d318332010-01-12 00:44:57 +00003150 // C++0x [over.best.ics]p10:
3151 // For the purpose of ranking implicit conversion sequences as
3152 // described in 13.3.3.2, the ambiguous conversion sequence is
3153 // treated as a user-defined sequence that is indistinguishable
3154 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003155 if (ICS1.getKindRank() < ICS2.getKindRank())
3156 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003157 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003158 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003159
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003160 // The following checks require both conversion sequences to be of
3161 // the same kind.
3162 if (ICS1.getKind() != ICS2.getKind())
3163 return ImplicitConversionSequence::Indistinguishable;
3164
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003165 ImplicitConversionSequence::CompareKind Result =
3166 ImplicitConversionSequence::Indistinguishable;
3167
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003168 // Two implicit conversion sequences of the same form are
3169 // indistinguishable conversion sequences unless one of the
3170 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003171 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003172 Result = CompareStandardConversionSequences(S,
3173 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003174 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003175 // User-defined conversion sequence U1 is a better conversion
3176 // sequence than another user-defined conversion sequence U2 if
3177 // they contain the same user-defined conversion function or
3178 // constructor and if the second standard conversion sequence of
3179 // U1 is better than the second standard conversion sequence of
3180 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003181 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003182 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003183 Result = CompareStandardConversionSequences(S,
3184 ICS1.UserDefined.After,
3185 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003186 else
3187 Result = compareConversionFunctions(S,
3188 ICS1.UserDefined.ConversionFunction,
3189 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003190 }
3191
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003192 // List-initialization sequence L1 is a better conversion sequence than
3193 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3194 // for some X and L2 does not.
3195 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003196 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003197 ICS1.isListInitializationSequence() &&
3198 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003199 if (ICS1.isStdInitializerListElement() &&
3200 !ICS2.isStdInitializerListElement())
3201 return ImplicitConversionSequence::Better;
3202 if (!ICS1.isStdInitializerListElement() &&
3203 ICS2.isStdInitializerListElement())
3204 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003205 }
3206
3207 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003208}
3209
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003210static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3211 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3212 Qualifiers Quals;
3213 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003214 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003215 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003216
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003217 return Context.hasSameUnqualifiedType(T1, T2);
3218}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003219
Douglas Gregorad323a82010-01-27 03:51:04 +00003220// Per 13.3.3.2p3, compare the given standard conversion sequences to
3221// determine if one is a proper subset of the other.
3222static ImplicitConversionSequence::CompareKind
3223compareStandardConversionSubsets(ASTContext &Context,
3224 const StandardConversionSequence& SCS1,
3225 const StandardConversionSequence& SCS2) {
3226 ImplicitConversionSequence::CompareKind Result
3227 = ImplicitConversionSequence::Indistinguishable;
3228
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003229 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003230 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003231 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3232 return ImplicitConversionSequence::Better;
3233 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3234 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003235
Douglas Gregorad323a82010-01-27 03:51:04 +00003236 if (SCS1.Second != SCS2.Second) {
3237 if (SCS1.Second == ICK_Identity)
3238 Result = ImplicitConversionSequence::Better;
3239 else if (SCS2.Second == ICK_Identity)
3240 Result = ImplicitConversionSequence::Worse;
3241 else
3242 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003243 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003244 return ImplicitConversionSequence::Indistinguishable;
3245
3246 if (SCS1.Third == SCS2.Third) {
3247 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3248 : ImplicitConversionSequence::Indistinguishable;
3249 }
3250
3251 if (SCS1.Third == ICK_Identity)
3252 return Result == ImplicitConversionSequence::Worse
3253 ? ImplicitConversionSequence::Indistinguishable
3254 : ImplicitConversionSequence::Better;
3255
3256 if (SCS2.Third == ICK_Identity)
3257 return Result == ImplicitConversionSequence::Better
3258 ? ImplicitConversionSequence::Indistinguishable
3259 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003260
Douglas Gregorad323a82010-01-27 03:51:04 +00003261 return ImplicitConversionSequence::Indistinguishable;
3262}
3263
Douglas Gregor440a4832011-01-26 14:52:12 +00003264/// \brief Determine whether one of the given reference bindings is better
3265/// than the other based on what kind of bindings they are.
3266static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3267 const StandardConversionSequence &SCS2) {
3268 // C++0x [over.ics.rank]p3b4:
3269 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3270 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003271 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003272 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003273 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003274 // reference*.
3275 //
3276 // FIXME: Rvalue references. We're going rogue with the above edits,
3277 // because the semantics in the current C++0x working paper (N3225 at the
3278 // time of this writing) break the standard definition of std::forward
3279 // and std::reference_wrapper when dealing with references to functions.
3280 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003281 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3282 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3283 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003284
Douglas Gregor440a4832011-01-26 14:52:12 +00003285 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3286 SCS2.IsLvalueReference) ||
3287 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3288 !SCS2.IsLvalueReference);
3289}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003290
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003291/// CompareStandardConversionSequences - Compare two standard
3292/// conversion sequences to determine whether one is better than the
3293/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003294static ImplicitConversionSequence::CompareKind
3295CompareStandardConversionSequences(Sema &S,
3296 const StandardConversionSequence& SCS1,
3297 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003298{
3299 // Standard conversion sequence S1 is a better conversion sequence
3300 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3301
3302 // -- S1 is a proper subsequence of S2 (comparing the conversion
3303 // sequences in the canonical form defined by 13.3.3.1.1,
3304 // excluding any Lvalue Transformation; the identity conversion
3305 // sequence is considered to be a subsequence of any
3306 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003307 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003308 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003309 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003310
3311 // -- the rank of S1 is better than the rank of S2 (by the rules
3312 // defined below), or, if not that,
3313 ImplicitConversionRank Rank1 = SCS1.getRank();
3314 ImplicitConversionRank Rank2 = SCS2.getRank();
3315 if (Rank1 < Rank2)
3316 return ImplicitConversionSequence::Better;
3317 else if (Rank2 < Rank1)
3318 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003319
Douglas Gregor57373262008-10-22 14:17:15 +00003320 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3321 // are indistinguishable unless one of the following rules
3322 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003323
Douglas Gregor57373262008-10-22 14:17:15 +00003324 // A conversion that is not a conversion of a pointer, or
3325 // pointer to member, to bool is better than another conversion
3326 // that is such a conversion.
3327 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3328 return SCS2.isPointerConversionToBool()
3329 ? ImplicitConversionSequence::Better
3330 : ImplicitConversionSequence::Worse;
3331
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003332 // C++ [over.ics.rank]p4b2:
3333 //
3334 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003335 // conversion of B* to A* is better than conversion of B* to
3336 // void*, and conversion of A* to void* is better than conversion
3337 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003338 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003339 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003340 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003341 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003342 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3343 // Exactly one of the conversion sequences is a conversion to
3344 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003345 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3346 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003347 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3348 // Neither conversion sequence converts to a void pointer; compare
3349 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003350 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003351 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003352 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003353 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3354 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003355 // Both conversion sequences are conversions to void
3356 // pointers. Compare the source types to determine if there's an
3357 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003358 QualType FromType1 = SCS1.getFromType();
3359 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003360
3361 // Adjust the types we're converting from via the array-to-pointer
3362 // conversion, if we need to.
3363 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003364 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003365 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003366 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003367
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003368 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3369 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003370
John McCall120d63c2010-08-24 20:38:10 +00003371 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003372 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003373 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003374 return ImplicitConversionSequence::Worse;
3375
3376 // Objective-C++: If one interface is more specific than the
3377 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003378 const ObjCObjectPointerType* FromObjCPtr1
3379 = FromType1->getAs<ObjCObjectPointerType>();
3380 const ObjCObjectPointerType* FromObjCPtr2
3381 = FromType2->getAs<ObjCObjectPointerType>();
3382 if (FromObjCPtr1 && FromObjCPtr2) {
3383 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3384 FromObjCPtr2);
3385 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3386 FromObjCPtr1);
3387 if (AssignLeft != AssignRight) {
3388 return AssignLeft? ImplicitConversionSequence::Better
3389 : ImplicitConversionSequence::Worse;
3390 }
Douglas Gregor01919692009-12-13 21:37:05 +00003391 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003392 }
Douglas Gregor57373262008-10-22 14:17:15 +00003393
3394 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3395 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003396 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003397 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003398 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003399
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003400 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003401 // Check for a better reference binding based on the kind of bindings.
3402 if (isBetterReferenceBindingKind(SCS1, SCS2))
3403 return ImplicitConversionSequence::Better;
3404 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3405 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003406
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003407 // C++ [over.ics.rank]p3b4:
3408 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3409 // which the references refer are the same type except for
3410 // top-level cv-qualifiers, and the type to which the reference
3411 // initialized by S2 refers is more cv-qualified than the type
3412 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003413 QualType T1 = SCS1.getToType(2);
3414 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003415 T1 = S.Context.getCanonicalType(T1);
3416 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003417 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003418 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3419 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003420 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003421 // Objective-C++ ARC: If the references refer to objects with different
3422 // lifetimes, prefer bindings that don't change lifetime.
3423 if (SCS1.ObjCLifetimeConversionBinding !=
3424 SCS2.ObjCLifetimeConversionBinding) {
3425 return SCS1.ObjCLifetimeConversionBinding
3426 ? ImplicitConversionSequence::Worse
3427 : ImplicitConversionSequence::Better;
3428 }
3429
Chandler Carruth6df868e2010-12-12 08:17:55 +00003430 // If the type is an array type, promote the element qualifiers to the
3431 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003432 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003433 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003434 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003435 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003436 if (T2.isMoreQualifiedThan(T1))
3437 return ImplicitConversionSequence::Better;
3438 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003439 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003440 }
3441 }
Douglas Gregor57373262008-10-22 14:17:15 +00003442
Francois Pichet1c98d622011-09-18 21:37:37 +00003443 // In Microsoft mode, prefer an integral conversion to a
3444 // floating-to-integral conversion if the integral conversion
3445 // is between types of the same size.
3446 // For example:
3447 // void f(float);
3448 // void f(int);
3449 // int main {
3450 // long a;
3451 // f(a);
3452 // }
3453 // Here, MSVC will call f(int) instead of generating a compile error
3454 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003455 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003456 SCS1.Second == ICK_Integral_Conversion &&
3457 SCS2.Second == ICK_Floating_Integral &&
3458 S.Context.getTypeSize(SCS1.getFromType()) ==
3459 S.Context.getTypeSize(SCS1.getToType(2)))
3460 return ImplicitConversionSequence::Better;
3461
Douglas Gregor57373262008-10-22 14:17:15 +00003462 return ImplicitConversionSequence::Indistinguishable;
3463}
3464
3465/// CompareQualificationConversions - Compares two standard conversion
3466/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003467/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3468ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003469CompareQualificationConversions(Sema &S,
3470 const StandardConversionSequence& SCS1,
3471 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003472 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003473 // -- S1 and S2 differ only in their qualification conversion and
3474 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3475 // cv-qualification signature of type T1 is a proper subset of
3476 // the cv-qualification signature of type T2, and S1 is not the
3477 // deprecated string literal array-to-pointer conversion (4.2).
3478 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3479 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3480 return ImplicitConversionSequence::Indistinguishable;
3481
3482 // FIXME: the example in the standard doesn't use a qualification
3483 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003484 QualType T1 = SCS1.getToType(2);
3485 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003486 T1 = S.Context.getCanonicalType(T1);
3487 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003488 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003489 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3490 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003491
3492 // If the types are the same, we won't learn anything by unwrapped
3493 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003494 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003495 return ImplicitConversionSequence::Indistinguishable;
3496
Chandler Carruth28e318c2009-12-29 07:16:59 +00003497 // If the type is an array type, promote the element qualifiers to the type
3498 // for comparison.
3499 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003500 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003501 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003502 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003503
Mike Stump1eb44332009-09-09 15:08:12 +00003504 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003505 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003506
3507 // Objective-C++ ARC:
3508 // Prefer qualification conversions not involving a change in lifetime
3509 // to qualification conversions that do not change lifetime.
3510 if (SCS1.QualificationIncludesObjCLifetime !=
3511 SCS2.QualificationIncludesObjCLifetime) {
3512 Result = SCS1.QualificationIncludesObjCLifetime
3513 ? ImplicitConversionSequence::Worse
3514 : ImplicitConversionSequence::Better;
3515 }
3516
John McCall120d63c2010-08-24 20:38:10 +00003517 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003518 // Within each iteration of the loop, we check the qualifiers to
3519 // determine if this still looks like a qualification
3520 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003521 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003522 // until there are no more pointers or pointers-to-members left
3523 // to unwrap. This essentially mimics what
3524 // IsQualificationConversion does, but here we're checking for a
3525 // strict subset of qualifiers.
3526 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3527 // The qualifiers are the same, so this doesn't tell us anything
3528 // about how the sequences rank.
3529 ;
3530 else if (T2.isMoreQualifiedThan(T1)) {
3531 // T1 has fewer qualifiers, so it could be the better sequence.
3532 if (Result == ImplicitConversionSequence::Worse)
3533 // Neither has qualifiers that are a subset of the other's
3534 // qualifiers.
3535 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003536
Douglas Gregor57373262008-10-22 14:17:15 +00003537 Result = ImplicitConversionSequence::Better;
3538 } else if (T1.isMoreQualifiedThan(T2)) {
3539 // T2 has fewer qualifiers, so it could be the better sequence.
3540 if (Result == ImplicitConversionSequence::Better)
3541 // Neither has qualifiers that are a subset of the other's
3542 // qualifiers.
3543 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003544
Douglas Gregor57373262008-10-22 14:17:15 +00003545 Result = ImplicitConversionSequence::Worse;
3546 } else {
3547 // Qualifiers are disjoint.
3548 return ImplicitConversionSequence::Indistinguishable;
3549 }
3550
3551 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003552 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003553 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003554 }
3555
Douglas Gregor57373262008-10-22 14:17:15 +00003556 // Check that the winning standard conversion sequence isn't using
3557 // the deprecated string literal array to pointer conversion.
3558 switch (Result) {
3559 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003560 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003561 Result = ImplicitConversionSequence::Indistinguishable;
3562 break;
3563
3564 case ImplicitConversionSequence::Indistinguishable:
3565 break;
3566
3567 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003568 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003569 Result = ImplicitConversionSequence::Indistinguishable;
3570 break;
3571 }
3572
3573 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003574}
3575
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003576/// CompareDerivedToBaseConversions - Compares two standard conversion
3577/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003578/// various kinds of derived-to-base conversions (C++
3579/// [over.ics.rank]p4b3). As part of these checks, we also look at
3580/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003581ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003582CompareDerivedToBaseConversions(Sema &S,
3583 const StandardConversionSequence& SCS1,
3584 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003585 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003586 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003587 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003588 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003589
3590 // Adjust the types we're converting from via the array-to-pointer
3591 // conversion, if we need to.
3592 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003593 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003594 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003595 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003596
3597 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003598 FromType1 = S.Context.getCanonicalType(FromType1);
3599 ToType1 = S.Context.getCanonicalType(ToType1);
3600 FromType2 = S.Context.getCanonicalType(FromType2);
3601 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003602
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003603 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003604 //
3605 // If class B is derived directly or indirectly from class A and
3606 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003607 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003608 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003609 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003610 SCS2.Second == ICK_Pointer_Conversion &&
3611 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3612 FromType1->isPointerType() && FromType2->isPointerType() &&
3613 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003614 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003615 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003616 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003617 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003618 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003619 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003620 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003621 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003622
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003623 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003624 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003625 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003626 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003627 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003628 return ImplicitConversionSequence::Worse;
3629 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003630
3631 // -- conversion of B* to A* is better than conversion of C* to A*,
3632 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003633 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003634 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003635 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003636 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003637 }
3638 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3639 SCS2.Second == ICK_Pointer_Conversion) {
3640 const ObjCObjectPointerType *FromPtr1
3641 = FromType1->getAs<ObjCObjectPointerType>();
3642 const ObjCObjectPointerType *FromPtr2
3643 = FromType2->getAs<ObjCObjectPointerType>();
3644 const ObjCObjectPointerType *ToPtr1
3645 = ToType1->getAs<ObjCObjectPointerType>();
3646 const ObjCObjectPointerType *ToPtr2
3647 = ToType2->getAs<ObjCObjectPointerType>();
3648
3649 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3650 // Apply the same conversion ranking rules for Objective-C pointer types
3651 // that we do for C++ pointers to class types. However, we employ the
3652 // Objective-C pseudo-subtyping relationship used for assignment of
3653 // Objective-C pointer types.
3654 bool FromAssignLeft
3655 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3656 bool FromAssignRight
3657 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3658 bool ToAssignLeft
3659 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3660 bool ToAssignRight
3661 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3662
3663 // A conversion to an a non-id object pointer type or qualified 'id'
3664 // type is better than a conversion to 'id'.
3665 if (ToPtr1->isObjCIdType() &&
3666 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3667 return ImplicitConversionSequence::Worse;
3668 if (ToPtr2->isObjCIdType() &&
3669 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3670 return ImplicitConversionSequence::Better;
3671
3672 // A conversion to a non-id object pointer type is better than a
3673 // conversion to a qualified 'id' type
3674 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3675 return ImplicitConversionSequence::Worse;
3676 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3677 return ImplicitConversionSequence::Better;
3678
3679 // A conversion to an a non-Class object pointer type or qualified 'Class'
3680 // type is better than a conversion to 'Class'.
3681 if (ToPtr1->isObjCClassType() &&
3682 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3683 return ImplicitConversionSequence::Worse;
3684 if (ToPtr2->isObjCClassType() &&
3685 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3686 return ImplicitConversionSequence::Better;
3687
3688 // A conversion to a non-Class object pointer type is better than a
3689 // conversion to a qualified 'Class' type.
3690 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3691 return ImplicitConversionSequence::Worse;
3692 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3693 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003694
Douglas Gregor395cc372011-01-31 18:51:41 +00003695 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3696 if (S.Context.hasSameType(FromType1, FromType2) &&
3697 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3698 (ToAssignLeft != ToAssignRight))
3699 return ToAssignLeft? ImplicitConversionSequence::Worse
3700 : ImplicitConversionSequence::Better;
3701
3702 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3703 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3704 (FromAssignLeft != FromAssignRight))
3705 return FromAssignLeft? ImplicitConversionSequence::Better
3706 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003707 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003708 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003709
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003710 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003711 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3712 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3713 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003714 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003715 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003716 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003717 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003718 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003719 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003720 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003721 ToType2->getAs<MemberPointerType>();
3722 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3723 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3724 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3725 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3726 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3727 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3728 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3729 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003730 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003731 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003732 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003733 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003734 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003735 return ImplicitConversionSequence::Better;
3736 }
3737 // conversion of B::* to C::* is better than conversion of A::* to C::*
3738 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003739 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003740 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003741 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003742 return ImplicitConversionSequence::Worse;
3743 }
3744 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003745
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003746 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003747 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003748 // -- binding of an expression of type C to a reference of type
3749 // B& is better than binding an expression of type C to a
3750 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003751 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3752 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3753 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003754 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003755 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003756 return ImplicitConversionSequence::Worse;
3757 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003758
Douglas Gregor225c41e2008-11-03 19:09:14 +00003759 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003760 // -- binding of an expression of type B to a reference of type
3761 // A& is better than binding an expression of type C to a
3762 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003763 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3764 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3765 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003766 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003767 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003768 return ImplicitConversionSequence::Worse;
3769 }
3770 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003771
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003772 return ImplicitConversionSequence::Indistinguishable;
3773}
3774
Douglas Gregorabe183d2010-04-13 16:31:36 +00003775/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3776/// determine whether they are reference-related,
3777/// reference-compatible, reference-compatible with added
3778/// qualification, or incompatible, for use in C++ initialization by
3779/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3780/// type, and the first type (T1) is the pointee type of the reference
3781/// type being initialized.
3782Sema::ReferenceCompareResult
3783Sema::CompareReferenceRelationship(SourceLocation Loc,
3784 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003785 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003786 bool &ObjCConversion,
3787 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003788 assert(!OrigT1->isReferenceType() &&
3789 "T1 must be the pointee type of the reference type");
3790 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3791
3792 QualType T1 = Context.getCanonicalType(OrigT1);
3793 QualType T2 = Context.getCanonicalType(OrigT2);
3794 Qualifiers T1Quals, T2Quals;
3795 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3796 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3797
3798 // C++ [dcl.init.ref]p4:
3799 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3800 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3801 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003802 DerivedToBase = false;
3803 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003804 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003805 if (UnqualT1 == UnqualT2) {
3806 // Nothing to do.
3807 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003808 IsDerivedFrom(UnqualT2, UnqualT1))
3809 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003810 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3811 UnqualT2->isObjCObjectOrInterfaceType() &&
3812 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3813 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003814 else
3815 return Ref_Incompatible;
3816
3817 // At this point, we know that T1 and T2 are reference-related (at
3818 // least).
3819
3820 // If the type is an array type, promote the element qualifiers to the type
3821 // for comparison.
3822 if (isa<ArrayType>(T1) && T1Quals)
3823 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3824 if (isa<ArrayType>(T2) && T2Quals)
3825 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3826
3827 // C++ [dcl.init.ref]p4:
3828 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3829 // reference-related to T2 and cv1 is the same cv-qualification
3830 // as, or greater cv-qualification than, cv2. For purposes of
3831 // overload resolution, cases for which cv1 is greater
3832 // cv-qualification than cv2 are identified as
3833 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003834 //
3835 // Note that we also require equivalence of Objective-C GC and address-space
3836 // qualifiers when performing these computations, so that e.g., an int in
3837 // address space 1 is not reference-compatible with an int in address
3838 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003839 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3840 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3841 T1Quals.removeObjCLifetime();
3842 T2Quals.removeObjCLifetime();
3843 ObjCLifetimeConversion = true;
3844 }
3845
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003846 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003847 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003848 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003849 return Ref_Compatible_With_Added_Qualification;
3850 else
3851 return Ref_Related;
3852}
3853
Douglas Gregor604eb652010-08-11 02:15:33 +00003854/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003855/// with DeclType. Return true if something definite is found.
3856static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003857FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3858 QualType DeclType, SourceLocation DeclLoc,
3859 Expr *Init, QualType T2, bool AllowRvalues,
3860 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003861 assert(T2->isRecordType() && "Can only find conversions of record types.");
3862 CXXRecordDecl *T2RecordDecl
3863 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3864
3865 OverloadCandidateSet CandidateSet(DeclLoc);
3866 const UnresolvedSetImpl *Conversions
3867 = T2RecordDecl->getVisibleConversionFunctions();
3868 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3869 E = Conversions->end(); I != E; ++I) {
3870 NamedDecl *D = *I;
3871 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3872 if (isa<UsingShadowDecl>(D))
3873 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3874
3875 FunctionTemplateDecl *ConvTemplate
3876 = dyn_cast<FunctionTemplateDecl>(D);
3877 CXXConversionDecl *Conv;
3878 if (ConvTemplate)
3879 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3880 else
3881 Conv = cast<CXXConversionDecl>(D);
3882
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003883 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003884 // explicit conversions, skip it.
3885 if (!AllowExplicit && Conv->isExplicit())
3886 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887
Douglas Gregor604eb652010-08-11 02:15:33 +00003888 if (AllowRvalues) {
3889 bool DerivedToBase = false;
3890 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003891 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003892
3893 // If we are initializing an rvalue reference, don't permit conversion
3894 // functions that return lvalues.
3895 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3896 const ReferenceType *RefType
3897 = Conv->getConversionType()->getAs<LValueReferenceType>();
3898 if (RefType && !RefType->getPointeeType()->isFunctionType())
3899 continue;
3900 }
3901
Douglas Gregor604eb652010-08-11 02:15:33 +00003902 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003903 S.CompareReferenceRelationship(
3904 DeclLoc,
3905 Conv->getConversionType().getNonReferenceType()
3906 .getUnqualifiedType(),
3907 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003908 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003909 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003910 continue;
3911 } else {
3912 // If the conversion function doesn't return a reference type,
3913 // it can't be considered for this conversion. An rvalue reference
3914 // is only acceptable if its referencee is a function type.
3915
3916 const ReferenceType *RefType =
3917 Conv->getConversionType()->getAs<ReferenceType>();
3918 if (!RefType ||
3919 (!RefType->isLValueReferenceType() &&
3920 !RefType->getPointeeType()->isFunctionType()))
3921 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003922 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003923
Douglas Gregor604eb652010-08-11 02:15:33 +00003924 if (ConvTemplate)
3925 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003926 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003927 else
3928 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003929 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003930 }
3931
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003932 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3933
Sebastian Redl4680bf22010-06-30 18:13:39 +00003934 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003935 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003936 case OR_Success:
3937 // C++ [over.ics.ref]p1:
3938 //
3939 // [...] If the parameter binds directly to the result of
3940 // applying a conversion function to the argument
3941 // expression, the implicit conversion sequence is a
3942 // user-defined conversion sequence (13.3.3.1.2), with the
3943 // second standard conversion sequence either an identity
3944 // conversion or, if the conversion function returns an
3945 // entity of a type that is a derived class of the parameter
3946 // type, a derived-to-base Conversion.
3947 if (!Best->FinalConversion.DirectBinding)
3948 return false;
3949
Chandler Carruth25ca4212011-02-25 19:41:05 +00003950 if (Best->Function)
Eli Friedman5f2987c2012-02-02 03:46:19 +00003951 S.MarkFunctionReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003952 ICS.setUserDefined();
3953 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3954 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003955 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003956 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003957 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003958 ICS.UserDefined.EllipsisConversion = false;
3959 assert(ICS.UserDefined.After.ReferenceBinding &&
3960 ICS.UserDefined.After.DirectBinding &&
3961 "Expected a direct reference binding!");
3962 return true;
3963
3964 case OR_Ambiguous:
3965 ICS.setAmbiguous();
3966 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3967 Cand != CandidateSet.end(); ++Cand)
3968 if (Cand->Viable)
3969 ICS.Ambiguous.addConversion(Cand->Function);
3970 return true;
3971
3972 case OR_No_Viable_Function:
3973 case OR_Deleted:
3974 // There was no suitable conversion, or we found a deleted
3975 // conversion; continue with other checks.
3976 return false;
3977 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003978
David Blaikie7530c032012-01-17 06:56:22 +00003979 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00003980}
3981
Douglas Gregorabe183d2010-04-13 16:31:36 +00003982/// \brief Compute an implicit conversion sequence for reference
3983/// initialization.
3984static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00003985TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003986 SourceLocation DeclLoc,
3987 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003988 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003989 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3990
3991 // Most paths end in a failed conversion.
3992 ImplicitConversionSequence ICS;
3993 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3994
3995 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3996 QualType T2 = Init->getType();
3997
3998 // If the initializer is the address of an overloaded function, try
3999 // to resolve the overloaded function. If all goes well, T2 is the
4000 // type of the resulting function.
4001 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4002 DeclAccessPair Found;
4003 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4004 false, Found))
4005 T2 = Fn->getType();
4006 }
4007
4008 // Compute some basic properties of the types and the initializer.
4009 bool isRValRef = DeclType->isRValueReferenceType();
4010 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004011 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004012 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004013 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004014 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004015 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004016 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004017
Douglas Gregorabe183d2010-04-13 16:31:36 +00004018
Sebastian Redl4680bf22010-06-30 18:13:39 +00004019 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004020 // A reference to type "cv1 T1" is initialized by an expression
4021 // of type "cv2 T2" as follows:
4022
Sebastian Redl4680bf22010-06-30 18:13:39 +00004023 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004024 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004025 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4026 // reference-compatible with "cv2 T2," or
4027 //
4028 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4029 if (InitCategory.isLValue() &&
4030 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004031 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004032 // When a parameter of reference type binds directly (8.5.3)
4033 // to an argument expression, the implicit conversion sequence
4034 // is the identity conversion, unless the argument expression
4035 // has a type that is a derived class of the parameter type,
4036 // in which case the implicit conversion sequence is a
4037 // derived-to-base Conversion (13.3.3.1).
4038 ICS.setStandard();
4039 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004040 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4041 : ObjCConversion? ICK_Compatible_Conversion
4042 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004043 ICS.Standard.Third = ICK_Identity;
4044 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4045 ICS.Standard.setToType(0, T2);
4046 ICS.Standard.setToType(1, T1);
4047 ICS.Standard.setToType(2, T1);
4048 ICS.Standard.ReferenceBinding = true;
4049 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004050 ICS.Standard.IsLvalueReference = !isRValRef;
4051 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4052 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004053 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004054 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004055 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004056
Sebastian Redl4680bf22010-06-30 18:13:39 +00004057 // Nothing more to do: the inaccessibility/ambiguity check for
4058 // derived-to-base conversions is suppressed when we're
4059 // computing the implicit conversion sequence (C++
4060 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004061 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004062 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004063
Sebastian Redl4680bf22010-06-30 18:13:39 +00004064 // -- has a class type (i.e., T2 is a class type), where T1 is
4065 // not reference-related to T2, and can be implicitly
4066 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4067 // is reference-compatible with "cv3 T3" 92) (this
4068 // conversion is selected by enumerating the applicable
4069 // conversion functions (13.3.1.6) and choosing the best
4070 // one through overload resolution (13.3)),
4071 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004072 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004073 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004074 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4075 Init, T2, /*AllowRvalues=*/false,
4076 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004077 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004078 }
4079 }
4080
Sebastian Redl4680bf22010-06-30 18:13:39 +00004081 // -- Otherwise, the reference shall be an lvalue reference to a
4082 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004083 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004084 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004085 // We actually handle one oddity of C++ [over.ics.ref] at this
4086 // point, which is that, due to p2 (which short-circuits reference
4087 // binding by only attempting a simple conversion for non-direct
4088 // bindings) and p3's strange wording, we allow a const volatile
4089 // reference to bind to an rvalue. Hence the check for the presence
4090 // of "const" rather than checking for "const" being the only
4091 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004092 // This is also the point where rvalue references and lvalue inits no longer
4093 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004094 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00004095 return ICS;
4096
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004097 // -- If the initializer expression
4098 //
4099 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004100 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004101 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4102 (InitCategory.isXValue() ||
4103 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4104 (InitCategory.isLValue() && T2->isFunctionType()))) {
4105 ICS.setStandard();
4106 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004107 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004108 : ObjCConversion? ICK_Compatible_Conversion
4109 : ICK_Identity;
4110 ICS.Standard.Third = ICK_Identity;
4111 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4112 ICS.Standard.setToType(0, T2);
4113 ICS.Standard.setToType(1, T1);
4114 ICS.Standard.setToType(2, T1);
4115 ICS.Standard.ReferenceBinding = true;
4116 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4117 // binding unless we're binding to a class prvalue.
4118 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4119 // allow the use of rvalue references in C++98/03 for the benefit of
4120 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004121 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004122 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004123 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004124 ICS.Standard.IsLvalueReference = !isRValRef;
4125 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004126 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004127 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004128 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004129 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004130 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004132
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004133 // -- has a class type (i.e., T2 is a class type), where T1 is not
4134 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004135 // an xvalue, class prvalue, or function lvalue of type
4136 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004137 // "cv3 T3",
4138 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004139 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004140 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004141 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004142 // class subobject).
4143 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004144 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004145 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4146 Init, T2, /*AllowRvalues=*/true,
4147 AllowExplicit)) {
4148 // In the second case, if the reference is an rvalue reference
4149 // and the second standard conversion sequence of the
4150 // user-defined conversion sequence includes an lvalue-to-rvalue
4151 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004152 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004153 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4154 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4155
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004156 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004157 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004158
Douglas Gregorabe183d2010-04-13 16:31:36 +00004159 // -- Otherwise, a temporary of type "cv1 T1" is created and
4160 // initialized from the initializer expression using the
4161 // rules for a non-reference copy initialization (8.5). The
4162 // reference is then bound to the temporary. If T1 is
4163 // reference-related to T2, cv1 must be the same
4164 // cv-qualification as, or greater cv-qualification than,
4165 // cv2; otherwise, the program is ill-formed.
4166 if (RefRelationship == Sema::Ref_Related) {
4167 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4168 // we would be reference-compatible or reference-compatible with
4169 // added qualification. But that wasn't the case, so the reference
4170 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004171 //
4172 // Note that we only want to check address spaces and cvr-qualifiers here.
4173 // ObjC GC and lifetime qualifiers aren't important.
4174 Qualifiers T1Quals = T1.getQualifiers();
4175 Qualifiers T2Quals = T2.getQualifiers();
4176 T1Quals.removeObjCGCAttr();
4177 T1Quals.removeObjCLifetime();
4178 T2Quals.removeObjCGCAttr();
4179 T2Quals.removeObjCLifetime();
4180 if (!T1Quals.compatiblyIncludes(T2Quals))
4181 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004182 }
4183
4184 // If at least one of the types is a class type, the types are not
4185 // related, and we aren't allowed any user conversions, the
4186 // reference binding fails. This case is important for breaking
4187 // recursion, since TryImplicitConversion below will attempt to
4188 // create a temporary through the use of a copy constructor.
4189 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4190 (T1->isRecordType() || T2->isRecordType()))
4191 return ICS;
4192
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004193 // If T1 is reference-related to T2 and the reference is an rvalue
4194 // reference, the initializer expression shall not be an lvalue.
4195 if (RefRelationship >= Sema::Ref_Related &&
4196 isRValRef && Init->Classify(S.Context).isLValue())
4197 return ICS;
4198
Douglas Gregorabe183d2010-04-13 16:31:36 +00004199 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004200 // When a parameter of reference type is not bound directly to
4201 // an argument expression, the conversion sequence is the one
4202 // required to convert the argument expression to the
4203 // underlying type of the reference according to
4204 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4205 // to copy-initializing a temporary of the underlying type with
4206 // the argument expression. Any difference in top-level
4207 // cv-qualification is subsumed by the initialization itself
4208 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004209 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4210 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004211 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004212 /*CStyle=*/false,
4213 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004214
4215 // Of course, that's still a reference binding.
4216 if (ICS.isStandard()) {
4217 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004218 ICS.Standard.IsLvalueReference = !isRValRef;
4219 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4220 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004221 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004222 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004223 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004224 // Don't allow rvalue references to bind to lvalues.
4225 if (DeclType->isRValueReferenceType()) {
4226 if (const ReferenceType *RefType
4227 = ICS.UserDefined.ConversionFunction->getResultType()
4228 ->getAs<LValueReferenceType>()) {
4229 if (!RefType->getPointeeType()->isFunctionType()) {
4230 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4231 DeclType);
4232 return ICS;
4233 }
4234 }
4235 }
4236
Douglas Gregorabe183d2010-04-13 16:31:36 +00004237 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004238 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4239 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4240 ICS.UserDefined.After.BindsToRvalue = true;
4241 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4242 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004243 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004244
Douglas Gregorabe183d2010-04-13 16:31:36 +00004245 return ICS;
4246}
4247
Sebastian Redl5405b812011-10-16 18:19:34 +00004248static ImplicitConversionSequence
4249TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4250 bool SuppressUserConversions,
4251 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004252 bool AllowObjCWritebackConversion,
4253 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004254
4255/// TryListConversion - Try to copy-initialize a value of type ToType from the
4256/// initializer list From.
4257static ImplicitConversionSequence
4258TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4259 bool SuppressUserConversions,
4260 bool InOverloadResolution,
4261 bool AllowObjCWritebackConversion) {
4262 // C++11 [over.ics.list]p1:
4263 // When an argument is an initializer list, it is not an expression and
4264 // special rules apply for converting it to a parameter type.
4265
4266 ImplicitConversionSequence Result;
4267 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004268 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004269
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004270 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004271 // initialized from init lists.
4272 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag()))
4273 return Result;
4274
Sebastian Redl5405b812011-10-16 18:19:34 +00004275 // C++11 [over.ics.list]p2:
4276 // If the parameter type is std::initializer_list<X> or "array of X" and
4277 // all the elements can be implicitly converted to X, the implicit
4278 // conversion sequence is the worst conversion necessary to convert an
4279 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004280 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004281 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004282 if (ToType->isArrayType())
Sebastian Redlfe592282012-01-17 22:49:48 +00004283 X = S.Context.getBaseElementType(ToType);
4284 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004285 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004286 if (!X.isNull()) {
4287 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4288 Expr *Init = From->getInit(i);
4289 ImplicitConversionSequence ICS =
4290 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4291 InOverloadResolution,
4292 AllowObjCWritebackConversion);
4293 // If a single element isn't convertible, fail.
4294 if (ICS.isBad()) {
4295 Result = ICS;
4296 break;
4297 }
4298 // Otherwise, look for the worst conversion.
4299 if (Result.isBad() ||
4300 CompareImplicitConversionSequences(S, ICS, Result) ==
4301 ImplicitConversionSequence::Worse)
4302 Result = ICS;
4303 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004304
4305 // For an empty list, we won't have computed any conversion sequence.
4306 // Introduce the identity conversion sequence.
4307 if (From->getNumInits() == 0) {
4308 Result.setStandard();
4309 Result.Standard.setAsIdentityConversion();
4310 Result.Standard.setFromType(ToType);
4311 Result.Standard.setAllToTypes(ToType);
4312 }
4313
Sebastian Redlfe592282012-01-17 22:49:48 +00004314 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004315 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004316 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004317 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004318
4319 // C++11 [over.ics.list]p3:
4320 // Otherwise, if the parameter is a non-aggregate class X and overload
4321 // resolution chooses a single best constructor [...] the implicit
4322 // conversion sequence is a user-defined conversion sequence. If multiple
4323 // constructors are viable but none is better than the others, the
4324 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004325 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4326 // This function can deal with initializer lists.
4327 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4328 /*AllowExplicit=*/false,
4329 InOverloadResolution, /*CStyle=*/false,
4330 AllowObjCWritebackConversion);
4331 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004332 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004333 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004334
4335 // C++11 [over.ics.list]p4:
4336 // Otherwise, if the parameter has an aggregate type which can be
4337 // initialized from the initializer list [...] the implicit conversion
4338 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004339 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004340 // Type is an aggregate, argument is an init list. At this point it comes
4341 // down to checking whether the initialization works.
4342 // FIXME: Find out whether this parameter is consumed or not.
4343 InitializedEntity Entity =
4344 InitializedEntity::InitializeParameter(S.Context, ToType,
4345 /*Consumed=*/false);
4346 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4347 Result.setUserDefined();
4348 Result.UserDefined.Before.setAsIdentityConversion();
4349 // Initializer lists don't have a type.
4350 Result.UserDefined.Before.setFromType(QualType());
4351 Result.UserDefined.Before.setAllToTypes(QualType());
4352
4353 Result.UserDefined.After.setAsIdentityConversion();
4354 Result.UserDefined.After.setFromType(ToType);
4355 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004356 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004357 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004358 return Result;
4359 }
4360
4361 // C++11 [over.ics.list]p5:
4362 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004363 if (ToType->isReferenceType()) {
4364 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4365 // mention initializer lists in any way. So we go by what list-
4366 // initialization would do and try to extrapolate from that.
4367
4368 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4369
4370 // If the initializer list has a single element that is reference-related
4371 // to the parameter type, we initialize the reference from that.
4372 if (From->getNumInits() == 1) {
4373 Expr *Init = From->getInit(0);
4374
4375 QualType T2 = Init->getType();
4376
4377 // If the initializer is the address of an overloaded function, try
4378 // to resolve the overloaded function. If all goes well, T2 is the
4379 // type of the resulting function.
4380 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4381 DeclAccessPair Found;
4382 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4383 Init, ToType, false, Found))
4384 T2 = Fn->getType();
4385 }
4386
4387 // Compute some basic properties of the types and the initializer.
4388 bool dummy1 = false;
4389 bool dummy2 = false;
4390 bool dummy3 = false;
4391 Sema::ReferenceCompareResult RefRelationship
4392 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4393 dummy2, dummy3);
4394
4395 if (RefRelationship >= Sema::Ref_Related)
4396 return TryReferenceInit(S, Init, ToType,
4397 /*FIXME:*/From->getLocStart(),
4398 SuppressUserConversions,
4399 /*AllowExplicit=*/false);
4400 }
4401
4402 // Otherwise, we bind the reference to a temporary created from the
4403 // initializer list.
4404 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4405 InOverloadResolution,
4406 AllowObjCWritebackConversion);
4407 if (Result.isFailure())
4408 return Result;
4409 assert(!Result.isEllipsis() &&
4410 "Sub-initialization cannot result in ellipsis conversion.");
4411
4412 // Can we even bind to a temporary?
4413 if (ToType->isRValueReferenceType() ||
4414 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4415 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4416 Result.UserDefined.After;
4417 SCS.ReferenceBinding = true;
4418 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4419 SCS.BindsToRvalue = true;
4420 SCS.BindsToFunctionLvalue = false;
4421 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4422 SCS.ObjCLifetimeConversionBinding = false;
4423 } else
4424 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4425 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004426 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004427 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004428
4429 // C++11 [over.ics.list]p6:
4430 // Otherwise, if the parameter type is not a class:
4431 if (!ToType->isRecordType()) {
4432 // - if the initializer list has one element, the implicit conversion
4433 // sequence is the one required to convert the element to the
4434 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004435 unsigned NumInits = From->getNumInits();
4436 if (NumInits == 1)
4437 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4438 SuppressUserConversions,
4439 InOverloadResolution,
4440 AllowObjCWritebackConversion);
4441 // - if the initializer list has no elements, the implicit conversion
4442 // sequence is the identity conversion.
4443 else if (NumInits == 0) {
4444 Result.setStandard();
4445 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004446 Result.Standard.setFromType(ToType);
4447 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004448 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004449 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004450 return Result;
4451 }
4452
4453 // C++11 [over.ics.list]p7:
4454 // In all cases other than those enumerated above, no conversion is possible
4455 return Result;
4456}
4457
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004458/// TryCopyInitialization - Try to copy-initialize a value of type
4459/// ToType from the expression From. Return the implicit conversion
4460/// sequence required to pass this argument, which may be a bad
4461/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004462/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004463/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004464static ImplicitConversionSequence
4465TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004466 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004467 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004468 bool AllowObjCWritebackConversion,
4469 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004470 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4471 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4472 InOverloadResolution,AllowObjCWritebackConversion);
4473
Douglas Gregorabe183d2010-04-13 16:31:36 +00004474 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004475 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004476 /*FIXME:*/From->getLocStart(),
4477 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004478 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004479
John McCall120d63c2010-08-24 20:38:10 +00004480 return TryImplicitConversion(S, From, ToType,
4481 SuppressUserConversions,
4482 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004483 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004484 /*CStyle=*/false,
4485 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004486}
4487
Anna Zaksf3546ee2011-07-28 19:46:48 +00004488static bool TryCopyInitialization(const CanQualType FromQTy,
4489 const CanQualType ToQTy,
4490 Sema &S,
4491 SourceLocation Loc,
4492 ExprValueKind FromVK) {
4493 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4494 ImplicitConversionSequence ICS =
4495 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4496
4497 return !ICS.isBad();
4498}
4499
Douglas Gregor96176b32008-11-18 23:14:02 +00004500/// TryObjectArgumentInitialization - Try to initialize the object
4501/// parameter of the given member function (@c Method) from the
4502/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004503static ImplicitConversionSequence
4504TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004505 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004506 CXXMethodDecl *Method,
4507 CXXRecordDecl *ActingContext) {
4508 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004509 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4510 // const volatile object.
4511 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4512 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004513 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004514
4515 // Set up the conversion sequence as a "bad" conversion, to allow us
4516 // to exit early.
4517 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004518
4519 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004520 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004521 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004522 FromType = PT->getPointeeType();
4523
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004524 // When we had a pointer, it's implicitly dereferenced, so we
4525 // better have an lvalue.
4526 assert(FromClassification.isLValue());
4527 }
4528
Anders Carlssona552f7c2009-05-01 18:34:30 +00004529 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004530
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004531 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004532 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004533 // parameter is
4534 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004535 // - "lvalue reference to cv X" for functions declared without a
4536 // ref-qualifier or with the & ref-qualifier
4537 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004538 // ref-qualifier
4539 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004540 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004541 // cv-qualification on the member function declaration.
4542 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004543 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004544 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004545 // (C++ [over.match.funcs]p5). We perform a simplified version of
4546 // reference binding here, that allows class rvalues to bind to
4547 // non-constant references.
4548
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004549 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004550 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004551 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004552 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004553 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004554 ICS.setBad(BadConversionSequence::bad_qualifiers,
4555 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004556 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004557 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004558
4559 // Check that we have either the same type or a derived type. It
4560 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004561 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004562 ImplicitConversionKind SecondKind;
4563 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4564 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004565 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004566 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004567 else {
John McCallb1bdc622010-02-25 01:37:24 +00004568 ICS.setBad(BadConversionSequence::unrelated_class,
4569 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004570 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004571 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004572
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004573 // Check the ref-qualifier.
4574 switch (Method->getRefQualifier()) {
4575 case RQ_None:
4576 // Do nothing; we don't care about lvalueness or rvalueness.
4577 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004578
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004579 case RQ_LValue:
4580 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4581 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004582 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004583 ImplicitParamType);
4584 return ICS;
4585 }
4586 break;
4587
4588 case RQ_RValue:
4589 if (!FromClassification.isRValue()) {
4590 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004591 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004592 ImplicitParamType);
4593 return ICS;
4594 }
4595 break;
4596 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004597
Douglas Gregor96176b32008-11-18 23:14:02 +00004598 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004599 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004600 ICS.Standard.setAsIdentityConversion();
4601 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004602 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004603 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004604 ICS.Standard.ReferenceBinding = true;
4605 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004606 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004607 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004608 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4609 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4610 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004611 return ICS;
4612}
4613
4614/// PerformObjectArgumentInitialization - Perform initialization of
4615/// the implicit object parameter for the given Method with the given
4616/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004617ExprResult
4618Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004619 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004620 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004621 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004622 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004623 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004624 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004625
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004626 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004627 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004628 FromRecordType = PT->getPointeeType();
4629 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004630 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004631 } else {
4632 FromRecordType = From->getType();
4633 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004634 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004635 }
4636
John McCall701c89e2009-12-03 04:06:58 +00004637 // Note that we always use the true parent context when performing
4638 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004639 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004640 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4641 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004642 if (ICS.isBad()) {
4643 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4644 Qualifiers FromQs = FromRecordType.getQualifiers();
4645 Qualifiers ToQs = DestType.getQualifiers();
4646 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4647 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004648 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004649 diag::err_member_function_call_bad_cvr)
4650 << Method->getDeclName() << FromRecordType << (CVR - 1)
4651 << From->getSourceRange();
4652 Diag(Method->getLocation(), diag::note_previous_decl)
4653 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004654 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004655 }
4656 }
4657
Daniel Dunbar96a00142012-03-09 18:35:03 +00004658 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004659 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004660 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004661 }
Mike Stump1eb44332009-09-09 15:08:12 +00004662
John Wiegley429bb272011-04-08 18:41:53 +00004663 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4664 ExprResult FromRes =
4665 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4666 if (FromRes.isInvalid())
4667 return ExprError();
4668 From = FromRes.take();
4669 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004670
Douglas Gregor5fccd362010-03-03 23:55:11 +00004671 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004672 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004673 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004674 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004675}
4676
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004677/// TryContextuallyConvertToBool - Attempt to contextually convert the
4678/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004679static ImplicitConversionSequence
4680TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004681 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004682 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004683 // FIXME: Are these flags correct?
4684 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004685 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004686 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004687 /*CStyle=*/false,
4688 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004689}
4690
4691/// PerformContextuallyConvertToBool - Perform a contextual conversion
4692/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004693ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004694 if (checkPlaceholderForOverload(*this, From))
4695 return ExprError();
4696
John McCall120d63c2010-08-24 20:38:10 +00004697 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004698 if (!ICS.isBad())
4699 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004700
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004701 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004702 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004703 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004704 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004705 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004706}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004707
Richard Smith8ef7b202012-01-18 23:55:52 +00004708/// Check that the specified conversion is permitted in a converted constant
4709/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4710/// is acceptable.
4711static bool CheckConvertedConstantConversions(Sema &S,
4712 StandardConversionSequence &SCS) {
4713 // Since we know that the target type is an integral or unscoped enumeration
4714 // type, most conversion kinds are impossible. All possible First and Third
4715 // conversions are fine.
4716 switch (SCS.Second) {
4717 case ICK_Identity:
4718 case ICK_Integral_Promotion:
4719 case ICK_Integral_Conversion:
4720 return true;
4721
4722 case ICK_Boolean_Conversion:
4723 // Conversion from an integral or unscoped enumeration type to bool is
4724 // classified as ICK_Boolean_Conversion, but it's also an integral
4725 // conversion, so it's permitted in a converted constant expression.
4726 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4727 SCS.getToType(2)->isBooleanType();
4728
4729 case ICK_Floating_Integral:
4730 case ICK_Complex_Real:
4731 return false;
4732
4733 case ICK_Lvalue_To_Rvalue:
4734 case ICK_Array_To_Pointer:
4735 case ICK_Function_To_Pointer:
4736 case ICK_NoReturn_Adjustment:
4737 case ICK_Qualification:
4738 case ICK_Compatible_Conversion:
4739 case ICK_Vector_Conversion:
4740 case ICK_Vector_Splat:
4741 case ICK_Derived_To_Base:
4742 case ICK_Pointer_Conversion:
4743 case ICK_Pointer_Member:
4744 case ICK_Block_Pointer_Conversion:
4745 case ICK_Writeback_Conversion:
4746 case ICK_Floating_Promotion:
4747 case ICK_Complex_Promotion:
4748 case ICK_Complex_Conversion:
4749 case ICK_Floating_Conversion:
4750 case ICK_TransparentUnionConversion:
4751 llvm_unreachable("unexpected second conversion kind");
4752
4753 case ICK_Num_Conversion_Kinds:
4754 break;
4755 }
4756
4757 llvm_unreachable("unknown conversion kind");
4758}
4759
4760/// CheckConvertedConstantExpression - Check that the expression From is a
4761/// converted constant expression of type T, perform the conversion and produce
4762/// the converted expression, per C++11 [expr.const]p3.
4763ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4764 llvm::APSInt &Value,
4765 CCEKind CCE) {
4766 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4767 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4768
4769 if (checkPlaceholderForOverload(*this, From))
4770 return ExprError();
4771
4772 // C++11 [expr.const]p3 with proposed wording fixes:
4773 // A converted constant expression of type T is a core constant expression,
4774 // implicitly converted to a prvalue of type T, where the converted
4775 // expression is a literal constant expression and the implicit conversion
4776 // sequence contains only user-defined conversions, lvalue-to-rvalue
4777 // conversions, integral promotions, and integral conversions other than
4778 // narrowing conversions.
4779 ImplicitConversionSequence ICS =
4780 TryImplicitConversion(From, T,
4781 /*SuppressUserConversions=*/false,
4782 /*AllowExplicit=*/false,
4783 /*InOverloadResolution=*/false,
4784 /*CStyle=*/false,
4785 /*AllowObjcWritebackConversion=*/false);
4786 StandardConversionSequence *SCS = 0;
4787 switch (ICS.getKind()) {
4788 case ImplicitConversionSequence::StandardConversion:
4789 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004790 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004791 diag::err_typecheck_converted_constant_expression_disallowed)
4792 << From->getType() << From->getSourceRange() << T;
4793 SCS = &ICS.Standard;
4794 break;
4795 case ImplicitConversionSequence::UserDefinedConversion:
4796 // We are converting from class type to an integral or enumeration type, so
4797 // the Before sequence must be trivial.
4798 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004799 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004800 diag::err_typecheck_converted_constant_expression_disallowed)
4801 << From->getType() << From->getSourceRange() << T;
4802 SCS = &ICS.UserDefined.After;
4803 break;
4804 case ImplicitConversionSequence::AmbiguousConversion:
4805 case ImplicitConversionSequence::BadConversion:
4806 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004807 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004808 diag::err_typecheck_converted_constant_expression)
4809 << From->getType() << From->getSourceRange() << T;
4810 return ExprError();
4811
4812 case ImplicitConversionSequence::EllipsisConversion:
4813 llvm_unreachable("ellipsis conversion in converted constant expression");
4814 }
4815
4816 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4817 if (Result.isInvalid())
4818 return Result;
4819
4820 // Check for a narrowing implicit conversion.
4821 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004822 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004823 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4824 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004825 case NK_Variable_Narrowing:
4826 // Implicit conversion to a narrower type, and the value is not a constant
4827 // expression. We'll diagnose this in a moment.
4828 case NK_Not_Narrowing:
4829 break;
4830
4831 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004832 Diag(From->getLocStart(),
4833 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4834 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004835 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004836 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004837 break;
4838
4839 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004840 Diag(From->getLocStart(),
4841 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4842 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004843 << CCE << /*Constant*/0 << From->getType() << T;
4844 break;
4845 }
4846
4847 // Check the expression is a constant expression.
4848 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4849 Expr::EvalResult Eval;
4850 Eval.Diag = &Notes;
4851
4852 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4853 // The expression can't be folded, so we can't keep it at this position in
4854 // the AST.
4855 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004856 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004857 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004858
4859 if (Notes.empty()) {
4860 // It's a constant expression.
4861 return Result;
4862 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004863 }
4864
4865 // It's not a constant expression. Produce an appropriate diagnostic.
4866 if (Notes.size() == 1 &&
4867 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4868 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4869 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004870 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004871 << CCE << From->getSourceRange();
4872 for (unsigned I = 0; I < Notes.size(); ++I)
4873 Diag(Notes[I].first, Notes[I].second);
4874 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004875 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004876}
4877
John McCall0bcc9bc2011-09-09 06:11:02 +00004878/// dropPointerConversions - If the given standard conversion sequence
4879/// involves any pointer conversions, remove them. This may change
4880/// the result type of the conversion sequence.
4881static void dropPointerConversion(StandardConversionSequence &SCS) {
4882 if (SCS.Second == ICK_Pointer_Conversion) {
4883 SCS.Second = ICK_Identity;
4884 SCS.Third = ICK_Identity;
4885 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4886 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004887}
John McCall120d63c2010-08-24 20:38:10 +00004888
John McCall0bcc9bc2011-09-09 06:11:02 +00004889/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4890/// convert the expression From to an Objective-C pointer type.
4891static ImplicitConversionSequence
4892TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4893 // Do an implicit conversion to 'id'.
4894 QualType Ty = S.Context.getObjCIdType();
4895 ImplicitConversionSequence ICS
4896 = TryImplicitConversion(S, From, Ty,
4897 // FIXME: Are these flags correct?
4898 /*SuppressUserConversions=*/false,
4899 /*AllowExplicit=*/true,
4900 /*InOverloadResolution=*/false,
4901 /*CStyle=*/false,
4902 /*AllowObjCWritebackConversion=*/false);
4903
4904 // Strip off any final conversions to 'id'.
4905 switch (ICS.getKind()) {
4906 case ImplicitConversionSequence::BadConversion:
4907 case ImplicitConversionSequence::AmbiguousConversion:
4908 case ImplicitConversionSequence::EllipsisConversion:
4909 break;
4910
4911 case ImplicitConversionSequence::UserDefinedConversion:
4912 dropPointerConversion(ICS.UserDefined.After);
4913 break;
4914
4915 case ImplicitConversionSequence::StandardConversion:
4916 dropPointerConversion(ICS.Standard);
4917 break;
4918 }
4919
4920 return ICS;
4921}
4922
4923/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4924/// conversion of the expression From to an Objective-C pointer type.
4925ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004926 if (checkPlaceholderForOverload(*this, From))
4927 return ExprError();
4928
John McCallc12c5bb2010-05-15 11:32:37 +00004929 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004930 ImplicitConversionSequence ICS =
4931 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004932 if (!ICS.isBad())
4933 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004934 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004935}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004936
Richard Smithf39aec12012-02-04 07:07:42 +00004937/// Determine whether the provided type is an integral type, or an enumeration
4938/// type of a permitted flavor.
4939static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
4940 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
4941 : T->isIntegralOrUnscopedEnumerationType();
4942}
4943
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004944/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004945/// enumeration type.
4946///
4947/// This routine will attempt to convert an expression of class type to an
4948/// integral or enumeration type, if that class type only has a single
4949/// conversion to an integral or enumeration type.
4950///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004951/// \param Loc The source location of the construct that requires the
4952/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004953///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004954/// \param FromE The expression we're converting from.
4955///
4956/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4957/// have integral or enumeration type.
4958///
4959/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4960/// incomplete class type.
4961///
4962/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4963/// explicit conversion function (because no implicit conversion functions
4964/// were available). This is a recovery mode.
4965///
4966/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4967/// showing which conversion was picked.
4968///
4969/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4970/// conversion function that could convert to integral or enumeration type.
4971///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004972/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004973/// usable conversion function.
4974///
4975/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4976/// function, which may be an extension in this case.
4977///
Richard Smithf39aec12012-02-04 07:07:42 +00004978/// \param AllowScopedEnumerations Specifies whether conversions to scoped
4979/// enumerations should be considered.
4980///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004981/// \returns The expression, converted to an integral or enumeration type if
4982/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004983ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004984Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004985 const PartialDiagnostic &NotIntDiag,
4986 const PartialDiagnostic &IncompleteDiag,
4987 const PartialDiagnostic &ExplicitConvDiag,
4988 const PartialDiagnostic &ExplicitConvNote,
4989 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004990 const PartialDiagnostic &AmbigNote,
Richard Smithf39aec12012-02-04 07:07:42 +00004991 const PartialDiagnostic &ConvDiag,
4992 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004993 // We can't perform any more checking for type-dependent expressions.
4994 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004995 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004996
Eli Friedmanceccab92012-01-26 00:26:18 +00004997 // Process placeholders immediately.
4998 if (From->hasPlaceholderType()) {
4999 ExprResult result = CheckPlaceholderExpr(From);
5000 if (result.isInvalid()) return result;
5001 From = result.take();
5002 }
5003
Douglas Gregorc30614b2010-06-29 23:17:37 +00005004 // If the expression already has integral or enumeration type, we're golden.
5005 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005006 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005007 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005008
5009 // FIXME: Check for missing '()' if T is a function type?
5010
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005011 // 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 +00005012 // expression of integral or enumeration type.
5013 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005014 if (!RecordTy || !getLangOpts().CPlusPlus) {
Richard Smith282e7e62012-02-04 09:53:13 +00005015 if (NotIntDiag.getDiagID())
5016 Diag(Loc, NotIntDiag) << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005017 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005018 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005019
Douglas Gregorc30614b2010-06-29 23:17:37 +00005020 // We must have a complete class type.
5021 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00005022 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005023
Douglas Gregorc30614b2010-06-29 23:17:37 +00005024 // Look for a conversion to an integral or enumeration type.
5025 UnresolvedSet<4> ViableConversions;
5026 UnresolvedSet<4> ExplicitConversions;
5027 const UnresolvedSetImpl *Conversions
5028 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005029
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005030 bool HadMultipleCandidates = (Conversions->size() > 1);
5031
Douglas Gregorc30614b2010-06-29 23:17:37 +00005032 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005033 E = Conversions->end();
5034 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00005035 ++I) {
5036 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005037 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5038 if (isIntegralOrEnumerationType(
5039 Conversion->getConversionType().getNonReferenceType(),
5040 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005041 if (Conversion->isExplicit())
5042 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5043 else
5044 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5045 }
Richard Smithf39aec12012-02-04 07:07:42 +00005046 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005047 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005048
Douglas Gregorc30614b2010-06-29 23:17:37 +00005049 switch (ViableConversions.size()) {
5050 case 0:
Richard Smith282e7e62012-02-04 09:53:13 +00005051 if (ExplicitConversions.size() == 1 && ExplicitConvDiag.getDiagID()) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005052 DeclAccessPair Found = ExplicitConversions[0];
5053 CXXConversionDecl *Conversion
5054 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005055
Douglas Gregorc30614b2010-06-29 23:17:37 +00005056 // The user probably meant to invoke the given explicit
5057 // conversion; use it.
5058 QualType ConvTy
5059 = Conversion->getConversionType().getNonReferenceType();
5060 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005061 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005062
Douglas Gregorc30614b2010-06-29 23:17:37 +00005063 Diag(Loc, ExplicitConvDiag)
5064 << T << ConvTy
5065 << FixItHint::CreateInsertion(From->getLocStart(),
5066 "static_cast<" + TypeStr + ">(")
5067 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5068 ")");
5069 Diag(Conversion->getLocation(), ExplicitConvNote)
5070 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005071
5072 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005073 // explicit conversion function.
5074 if (isSFINAEContext())
5075 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005076
Douglas Gregorc30614b2010-06-29 23:17:37 +00005077 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005078 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5079 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005080 if (Result.isInvalid())
5081 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005082 // Record usage of conversion in an implicit cast.
5083 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5084 CK_UserDefinedConversion,
5085 Result.get(), 0,
5086 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005087 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005088
Douglas Gregorc30614b2010-06-29 23:17:37 +00005089 // We'll complain below about a non-integral condition type.
5090 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005091
Douglas Gregorc30614b2010-06-29 23:17:37 +00005092 case 1: {
5093 // Apply this conversion.
5094 DeclAccessPair Found = ViableConversions[0];
5095 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005096
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005097 CXXConversionDecl *Conversion
5098 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5099 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005100 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005101 if (ConvDiag.getDiagID()) {
5102 if (isSFINAEContext())
5103 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005104
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005105 Diag(Loc, ConvDiag)
5106 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
5107 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005108
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005109 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5110 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005111 if (Result.isInvalid())
5112 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005113 // Record usage of conversion in an implicit cast.
5114 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5115 CK_UserDefinedConversion,
5116 Result.get(), 0,
5117 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005118 break;
5119 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005120
Douglas Gregorc30614b2010-06-29 23:17:37 +00005121 default:
Richard Smith282e7e62012-02-04 09:53:13 +00005122 if (!AmbigDiag.getDiagID())
5123 return Owned(From);
5124
Douglas Gregorc30614b2010-06-29 23:17:37 +00005125 Diag(Loc, AmbigDiag)
5126 << T << From->getSourceRange();
5127 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5128 CXXConversionDecl *Conv
5129 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5130 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
5131 Diag(Conv->getLocation(), AmbigNote)
5132 << ConvTy->isEnumeralType() << ConvTy;
5133 }
John McCall9ae2f072010-08-23 23:25:46 +00005134 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005135 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005136
Richard Smith282e7e62012-02-04 09:53:13 +00005137 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
5138 NotIntDiag.getDiagID())
5139 Diag(Loc, NotIntDiag) << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005140
Eli Friedmanceccab92012-01-26 00:26:18 +00005141 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005142}
5143
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005144/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005145/// candidate functions, using the given function call arguments. If
5146/// @p SuppressUserConversions, then don't allow user-defined
5147/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005148///
5149/// \para PartialOverloading true if we are performing "partial" overloading
5150/// based on an incomplete set of function arguments. This feature is used by
5151/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005152void
5153Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005154 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005155 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005156 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005157 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005158 bool PartialOverloading,
5159 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005160 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005161 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005162 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005163 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005164 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005165
Douglas Gregor88a35142008-12-22 05:46:06 +00005166 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005167 if (!isa<CXXConstructorDecl>(Method)) {
5168 // If we get here, it's because we're calling a member function
5169 // that is named without a member access expression (e.g.,
5170 // "this->f") that was either written explicitly or created
5171 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005172 // function, e.g., X::f(). We use an empty type for the implied
5173 // object argument (C++ [over.call.func]p3), and the acting context
5174 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005175 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005176 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005177 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005178 return;
5179 }
5180 // We treat a constructor like a non-member function, since its object
5181 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005182 }
5183
Douglas Gregorfd476482009-11-13 23:59:09 +00005184 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005185 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005186
Douglas Gregor7edfb692009-11-23 12:27:39 +00005187 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005188 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005189
Douglas Gregor66724ea2009-11-14 01:20:54 +00005190 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5191 // C++ [class.copy]p3:
5192 // A member function template is never instantiated to perform the copy
5193 // of a class object to an object of its class type.
5194 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005195 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005196 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005197 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5198 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005199 return;
5200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005201
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005202 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005203 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005204 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005205 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005206 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005207 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005208 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005209 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005210
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005211 unsigned NumArgsInProto = Proto->getNumArgs();
5212
5213 // (C++ 13.3.2p2): A candidate function having fewer than m
5214 // parameters is viable only if it has an ellipsis in its parameter
5215 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005216 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005217 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005218 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005219 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005220 return;
5221 }
5222
5223 // (C++ 13.3.2p2): A candidate function having more than m parameters
5224 // is viable only if the (m+1)st parameter has a default argument
5225 // (8.3.6). For the purposes of overload resolution, the
5226 // parameter list is truncated on the right, so that there are
5227 // exactly m parameters.
5228 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005229 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005230 // Not enough arguments.
5231 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005232 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005233 return;
5234 }
5235
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005236 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005237 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005238 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5239 if (CheckCUDATarget(Caller, Function)) {
5240 Candidate.Viable = false;
5241 Candidate.FailureKind = ovl_fail_bad_target;
5242 return;
5243 }
5244
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005245 // Determine the implicit conversion sequences for each of the
5246 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005247 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005248 if (ArgIdx < NumArgsInProto) {
5249 // (C++ 13.3.2p3): for F to be a viable function, there shall
5250 // exist for each argument an implicit conversion sequence
5251 // (13.3.3.1) that converts that argument to the corresponding
5252 // parameter of F.
5253 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005254 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005255 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005256 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005257 /*InOverloadResolution=*/true,
5258 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005259 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005260 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005261 if (Candidate.Conversions[ArgIdx].isBad()) {
5262 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005263 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005264 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005265 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005266 } else {
5267 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5268 // argument for which there is no corresponding parameter is
5269 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005270 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005271 }
5272 }
5273}
5274
Douglas Gregor063daf62009-03-13 18:40:31 +00005275/// \brief Add all of the function declarations in the given function set to
5276/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005277void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005278 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005279 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005280 bool SuppressUserConversions,
5281 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005282 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005283 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5284 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005285 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005286 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005287 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005288 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005289 Args.slice(1), CandidateSet,
5290 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005291 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005292 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005293 SuppressUserConversions);
5294 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005295 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005296 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5297 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005298 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005299 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005300 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005301 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005302 Args[0]->Classify(Context), Args.slice(1),
5303 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005304 else
John McCall9aa472c2010-03-19 07:35:19 +00005305 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005306 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005307 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005308 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005309 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005310}
5311
John McCall314be4e2009-11-17 07:50:12 +00005312/// AddMethodCandidate - Adds a named decl (which is some kind of
5313/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005314void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005315 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005316 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005317 Expr **Args, unsigned NumArgs,
5318 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005319 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005320 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005321 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005322
5323 if (isa<UsingShadowDecl>(Decl))
5324 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005325
John McCall314be4e2009-11-17 07:50:12 +00005326 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5327 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5328 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005329 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5330 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005331 ObjectType, ObjectClassification,
5332 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005333 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005334 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005335 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005336 ObjectType, ObjectClassification,
5337 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005338 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005339 }
5340}
5341
Douglas Gregor96176b32008-11-18 23:14:02 +00005342/// AddMethodCandidate - Adds the given C++ member function to the set
5343/// of candidate functions, using the given function call arguments
5344/// and the object argument (@c Object). For example, in a call
5345/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5346/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5347/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005348/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005349void
John McCall9aa472c2010-03-19 07:35:19 +00005350Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005351 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005352 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005353 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005354 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005355 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005356 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005357 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005358 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005359 assert(!isa<CXXConstructorDecl>(Method) &&
5360 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005361
Douglas Gregor3f396022009-09-28 04:47:19 +00005362 if (!CandidateSet.isNewCandidate(Method))
5363 return;
5364
Douglas Gregor7edfb692009-11-23 12:27:39 +00005365 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005366 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005367
Douglas Gregor96176b32008-11-18 23:14:02 +00005368 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005369 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005370 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005371 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005372 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005373 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005374 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005375
5376 unsigned NumArgsInProto = Proto->getNumArgs();
5377
5378 // (C++ 13.3.2p2): A candidate function having fewer than m
5379 // parameters is viable only if it has an ellipsis in its parameter
5380 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005381 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005382 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005383 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005384 return;
5385 }
5386
5387 // (C++ 13.3.2p2): A candidate function having more than m parameters
5388 // is viable only if the (m+1)st parameter has a default argument
5389 // (8.3.6). For the purposes of overload resolution, the
5390 // parameter list is truncated on the right, so that there are
5391 // exactly m parameters.
5392 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005393 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005394 // Not enough arguments.
5395 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005396 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005397 return;
5398 }
5399
5400 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005401
John McCall701c89e2009-12-03 04:06:58 +00005402 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005403 // The implicit object argument is ignored.
5404 Candidate.IgnoreObjectArgument = true;
5405 else {
5406 // Determine the implicit conversion sequence for the object
5407 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005408 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005409 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5410 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005411 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005412 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005413 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005414 return;
5415 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005416 }
5417
5418 // Determine the implicit conversion sequences for each of the
5419 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005420 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005421 if (ArgIdx < NumArgsInProto) {
5422 // (C++ 13.3.2p3): for F to be a viable function, there shall
5423 // exist for each argument an implicit conversion sequence
5424 // (13.3.3.1) that converts that argument to the corresponding
5425 // parameter of F.
5426 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005427 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005428 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005429 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005430 /*InOverloadResolution=*/true,
5431 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005432 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005433 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005434 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005435 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005436 break;
5437 }
5438 } else {
5439 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5440 // argument for which there is no corresponding parameter is
5441 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005442 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005443 }
5444 }
5445}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005446
Douglas Gregor6b906862009-08-21 00:16:32 +00005447/// \brief Add a C++ member function template as a candidate to the candidate
5448/// set, using template argument deduction to produce an appropriate member
5449/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005450void
Douglas Gregor6b906862009-08-21 00:16:32 +00005451Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005452 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005453 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005454 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005455 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005456 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005457 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005458 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005459 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005460 if (!CandidateSet.isNewCandidate(MethodTmpl))
5461 return;
5462
Douglas Gregor6b906862009-08-21 00:16:32 +00005463 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005464 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005465 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005466 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005467 // candidate functions in the usual way.113) A given name can refer to one
5468 // or more function templates and also to a set of overloaded non-template
5469 // functions. In such a case, the candidate functions generated from each
5470 // function template are combined with the set of non-template candidate
5471 // functions.
John McCall5769d612010-02-08 23:07:23 +00005472 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005473 FunctionDecl *Specialization = 0;
5474 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005475 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5476 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005477 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005478 Candidate.FoundDecl = FoundDecl;
5479 Candidate.Function = MethodTmpl->getTemplatedDecl();
5480 Candidate.Viable = false;
5481 Candidate.FailureKind = ovl_fail_bad_deduction;
5482 Candidate.IsSurrogate = false;
5483 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005484 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005485 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005486 Info);
5487 return;
5488 }
Mike Stump1eb44332009-09-09 15:08:12 +00005489
Douglas Gregor6b906862009-08-21 00:16:32 +00005490 // Add the function template specialization produced by template argument
5491 // deduction as a candidate.
5492 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005493 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005494 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005495 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005496 ActingContext, ObjectType, ObjectClassification, Args,
5497 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005498}
5499
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005500/// \brief Add a C++ function template specialization as a candidate
5501/// in the candidate set, using template argument deduction to produce
5502/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005503void
Douglas Gregore53060f2009-06-25 22:08:12 +00005504Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005505 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005506 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005507 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005508 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005509 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005510 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5511 return;
5512
Douglas Gregore53060f2009-06-25 22:08:12 +00005513 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005514 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005515 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005516 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005517 // candidate functions in the usual way.113) A given name can refer to one
5518 // or more function templates and also to a set of overloaded non-template
5519 // functions. In such a case, the candidate functions generated from each
5520 // function template are combined with the set of non-template candidate
5521 // functions.
John McCall5769d612010-02-08 23:07:23 +00005522 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005523 FunctionDecl *Specialization = 0;
5524 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005525 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5526 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005527 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005528 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005529 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5530 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005531 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005532 Candidate.IsSurrogate = false;
5533 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005534 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005535 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005536 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005537 return;
5538 }
Mike Stump1eb44332009-09-09 15:08:12 +00005539
Douglas Gregore53060f2009-06-25 22:08:12 +00005540 // Add the function template specialization produced by template argument
5541 // deduction as a candidate.
5542 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005543 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005544 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005545}
Mike Stump1eb44332009-09-09 15:08:12 +00005546
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005547/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005548/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005549/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005550/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005551/// (which may or may not be the same type as the type that the
5552/// conversion function produces).
5553void
5554Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005555 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005556 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005557 Expr *From, QualType ToType,
5558 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005559 assert(!Conversion->getDescribedFunctionTemplate() &&
5560 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005561 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005562 if (!CandidateSet.isNewCandidate(Conversion))
5563 return;
5564
Douglas Gregor7edfb692009-11-23 12:27:39 +00005565 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005566 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005567
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005568 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005569 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005570 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005571 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005572 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005573 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005574 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005575 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005576 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005577 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005578 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005579
Douglas Gregorbca39322010-08-19 15:37:02 +00005580 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005581 // For conversion functions, the function is considered to be a member of
5582 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005583 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005584 //
5585 // Determine the implicit conversion sequence for the implicit
5586 // object parameter.
5587 QualType ImplicitParamType = From->getType();
5588 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5589 ImplicitParamType = FromPtrType->getPointeeType();
5590 CXXRecordDecl *ConversionContext
5591 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005592
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005593 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005594 = TryObjectArgumentInitialization(*this, From->getType(),
5595 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005596 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005597
John McCall1d318332010-01-12 00:44:57 +00005598 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005599 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005600 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005601 return;
5602 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005603
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005604 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005605 // derived to base as such conversions are given Conversion Rank. They only
5606 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5607 QualType FromCanon
5608 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5609 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5610 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5611 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005612 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005613 return;
5614 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005615
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005616 // To determine what the conversion from the result of calling the
5617 // conversion function to the type we're eventually trying to
5618 // convert to (ToType), we need to synthesize a call to the
5619 // conversion function and attempt copy initialization from it. This
5620 // makes sure that we get the right semantics with respect to
5621 // lvalues/rvalues and the type. Fortunately, we can allocate this
5622 // call on the stack and we don't need its arguments to be
5623 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005624 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005625 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005626 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5627 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005628 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005629 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005630
Richard Smith87c1f1f2011-07-13 22:53:21 +00005631 QualType ConversionType = Conversion->getConversionType();
5632 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005633 Candidate.Viable = false;
5634 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5635 return;
5636 }
5637
Richard Smith87c1f1f2011-07-13 22:53:21 +00005638 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005639
Mike Stump1eb44332009-09-09 15:08:12 +00005640 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005641 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5642 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005643 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005644 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005645 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005646 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005647 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005648 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005649 /*InOverloadResolution=*/false,
5650 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005651
John McCall1d318332010-01-12 00:44:57 +00005652 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005653 case ImplicitConversionSequence::StandardConversion:
5654 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005655
Douglas Gregorc520c842010-04-12 23:42:09 +00005656 // C++ [over.ics.user]p3:
5657 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005658 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005659 // shall have exact match rank.
5660 if (Conversion->getPrimaryTemplate() &&
5661 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5662 Candidate.Viable = false;
5663 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5664 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005665
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005666 // C++0x [dcl.init.ref]p5:
5667 // In the second case, if the reference is an rvalue reference and
5668 // the second standard conversion sequence of the user-defined
5669 // conversion sequence includes an lvalue-to-rvalue conversion, the
5670 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005671 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005672 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5673 Candidate.Viable = false;
5674 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5675 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005676 break;
5677
5678 case ImplicitConversionSequence::BadConversion:
5679 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005680 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005681 break;
5682
5683 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005684 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005685 "Can only end up with a standard conversion sequence or failure");
5686 }
5687}
5688
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005689/// \brief Adds a conversion function template specialization
5690/// candidate to the overload set, using template argument deduction
5691/// to deduce the template arguments of the conversion function
5692/// template from the type that we are converting to (C++
5693/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005694void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005695Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005696 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005697 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005698 Expr *From, QualType ToType,
5699 OverloadCandidateSet &CandidateSet) {
5700 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5701 "Only conversion function templates permitted here");
5702
Douglas Gregor3f396022009-09-28 04:47:19 +00005703 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5704 return;
5705
John McCall5769d612010-02-08 23:07:23 +00005706 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005707 CXXConversionDecl *Specialization = 0;
5708 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005709 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005710 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005711 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005712 Candidate.FoundDecl = FoundDecl;
5713 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5714 Candidate.Viable = false;
5715 Candidate.FailureKind = ovl_fail_bad_deduction;
5716 Candidate.IsSurrogate = false;
5717 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005718 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005719 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005720 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005721 return;
5722 }
Mike Stump1eb44332009-09-09 15:08:12 +00005723
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005724 // Add the conversion function template specialization produced by
5725 // template argument deduction as a candidate.
5726 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005727 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005728 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005729}
5730
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005731/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5732/// converts the given @c Object to a function pointer via the
5733/// conversion function @c Conversion, and then attempts to call it
5734/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5735/// the type of function that we'll eventually be calling.
5736void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005737 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005738 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005739 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005740 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005741 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005742 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005743 if (!CandidateSet.isNewCandidate(Conversion))
5744 return;
5745
Douglas Gregor7edfb692009-11-23 12:27:39 +00005746 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005747 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005748
Ahmed Charles13a140c2012-02-25 11:00:22 +00005749 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005750 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005751 Candidate.Function = 0;
5752 Candidate.Surrogate = Conversion;
5753 Candidate.Viable = true;
5754 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005755 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005756 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005757
5758 // Determine the implicit conversion sequence for the implicit
5759 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005760 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005761 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005762 Object->Classify(Context),
5763 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005764 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005765 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005766 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005767 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005768 return;
5769 }
5770
5771 // The first conversion is actually a user-defined conversion whose
5772 // first conversion is ObjectInit's standard conversion (which is
5773 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005774 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005775 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005776 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005777 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005778 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005779 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005780 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005781 = Candidate.Conversions[0].UserDefined.Before;
5782 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5783
Mike Stump1eb44332009-09-09 15:08:12 +00005784 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005785 unsigned NumArgsInProto = Proto->getNumArgs();
5786
5787 // (C++ 13.3.2p2): A candidate function having fewer than m
5788 // parameters is viable only if it has an ellipsis in its parameter
5789 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005790 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005791 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005792 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005793 return;
5794 }
5795
5796 // Function types don't have any default arguments, so just check if
5797 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005798 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005799 // Not enough arguments.
5800 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005801 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005802 return;
5803 }
5804
5805 // Determine the implicit conversion sequences for each of the
5806 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005807 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005808 if (ArgIdx < NumArgsInProto) {
5809 // (C++ 13.3.2p3): for F to be a viable function, there shall
5810 // exist for each argument an implicit conversion sequence
5811 // (13.3.3.1) that converts that argument to the corresponding
5812 // parameter of F.
5813 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005814 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005815 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005816 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005817 /*InOverloadResolution=*/false,
5818 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005819 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005820 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005821 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005822 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005823 break;
5824 }
5825 } else {
5826 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5827 // argument for which there is no corresponding parameter is
5828 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005829 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005830 }
5831 }
5832}
5833
Douglas Gregor063daf62009-03-13 18:40:31 +00005834/// \brief Add overload candidates for overloaded operators that are
5835/// member functions.
5836///
5837/// Add the overloaded operator candidates that are member functions
5838/// for the operator Op that was used in an operator expression such
5839/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5840/// CandidateSet will store the added overload candidates. (C++
5841/// [over.match.oper]).
5842void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5843 SourceLocation OpLoc,
5844 Expr **Args, unsigned NumArgs,
5845 OverloadCandidateSet& CandidateSet,
5846 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005847 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5848
5849 // C++ [over.match.oper]p3:
5850 // For a unary operator @ with an operand of a type whose
5851 // cv-unqualified version is T1, and for a binary operator @ with
5852 // a left operand of a type whose cv-unqualified version is T1 and
5853 // a right operand of a type whose cv-unqualified version is T2,
5854 // three sets of candidate functions, designated member
5855 // candidates, non-member candidates and built-in candidates, are
5856 // constructed as follows:
5857 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005858
5859 // -- If T1 is a class type, the set of member candidates is the
5860 // result of the qualified lookup of T1::operator@
5861 // (13.3.1.1.1); otherwise, the set of member candidates is
5862 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005863 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005864 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005865 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005866 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005867
John McCalla24dc2e2009-11-17 02:14:36 +00005868 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5869 LookupQualifiedName(Operators, T1Rec->getDecl());
5870 Operators.suppressDiagnostics();
5871
Mike Stump1eb44332009-09-09 15:08:12 +00005872 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005873 OperEnd = Operators.end();
5874 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005875 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005876 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005877 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005878 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005879 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005880 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005881}
5882
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005883/// AddBuiltinCandidate - Add a candidate for a built-in
5884/// operator. ResultTy and ParamTys are the result and parameter types
5885/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005886/// arguments being passed to the candidate. IsAssignmentOperator
5887/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005888/// operator. NumContextualBoolArguments is the number of arguments
5889/// (at the beginning of the argument list) that will be contextually
5890/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005891void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005892 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005893 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005894 bool IsAssignmentOperator,
5895 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005896 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005897 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005898
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005899 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005900 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005901 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005902 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005903 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005904 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005905 Candidate.BuiltinTypes.ResultTy = ResultTy;
5906 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5907 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5908
5909 // Determine the implicit conversion sequences for each of the
5910 // arguments.
5911 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005912 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005913 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005914 // C++ [over.match.oper]p4:
5915 // For the built-in assignment operators, conversions of the
5916 // left operand are restricted as follows:
5917 // -- no temporaries are introduced to hold the left operand, and
5918 // -- no user-defined conversions are applied to the left
5919 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005920 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005921 //
5922 // We block these conversions by turning off user-defined
5923 // conversions, since that is the only way that initialization of
5924 // a reference to a non-class type can occur from something that
5925 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005926 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005927 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005928 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005929 Candidate.Conversions[ArgIdx]
5930 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005931 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005932 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005933 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005934 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005935 /*InOverloadResolution=*/false,
5936 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005937 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005938 }
John McCall1d318332010-01-12 00:44:57 +00005939 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005940 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005941 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005942 break;
5943 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005944 }
5945}
5946
5947/// BuiltinCandidateTypeSet - A set of types that will be used for the
5948/// candidate operator functions for built-in operators (C++
5949/// [over.built]). The types are separated into pointer types and
5950/// enumeration types.
5951class BuiltinCandidateTypeSet {
5952 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005953 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005954
5955 /// PointerTypes - The set of pointer types that will be used in the
5956 /// built-in candidates.
5957 TypeSet PointerTypes;
5958
Sebastian Redl78eb8742009-04-19 21:53:20 +00005959 /// MemberPointerTypes - The set of member pointer types that will be
5960 /// used in the built-in candidates.
5961 TypeSet MemberPointerTypes;
5962
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005963 /// EnumerationTypes - The set of enumeration types that will be
5964 /// used in the built-in candidates.
5965 TypeSet EnumerationTypes;
5966
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005967 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005968 /// candidates.
5969 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005970
5971 /// \brief A flag indicating non-record types are viable candidates
5972 bool HasNonRecordTypes;
5973
5974 /// \brief A flag indicating whether either arithmetic or enumeration types
5975 /// were present in the candidate set.
5976 bool HasArithmeticOrEnumeralTypes;
5977
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005978 /// \brief A flag indicating whether the nullptr type was present in the
5979 /// candidate set.
5980 bool HasNullPtrType;
5981
Douglas Gregor5842ba92009-08-24 15:23:48 +00005982 /// Sema - The semantic analysis instance where we are building the
5983 /// candidate type set.
5984 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005985
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005986 /// Context - The AST context in which we will build the type sets.
5987 ASTContext &Context;
5988
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005989 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5990 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005991 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005992
5993public:
5994 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005995 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005996
Mike Stump1eb44332009-09-09 15:08:12 +00005997 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005998 : HasNonRecordTypes(false),
5999 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006000 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006001 SemaRef(SemaRef),
6002 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006003
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006004 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006005 SourceLocation Loc,
6006 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006007 bool AllowExplicitConversions,
6008 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006009
6010 /// pointer_begin - First pointer type found;
6011 iterator pointer_begin() { return PointerTypes.begin(); }
6012
Sebastian Redl78eb8742009-04-19 21:53:20 +00006013 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006014 iterator pointer_end() { return PointerTypes.end(); }
6015
Sebastian Redl78eb8742009-04-19 21:53:20 +00006016 /// member_pointer_begin - First member pointer type found;
6017 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6018
6019 /// member_pointer_end - Past the last member pointer type found;
6020 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6021
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006022 /// enumeration_begin - First enumeration type found;
6023 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6024
Sebastian Redl78eb8742009-04-19 21:53:20 +00006025 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006026 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006027
Douglas Gregor26bcf672010-05-19 03:21:00 +00006028 iterator vector_begin() { return VectorTypes.begin(); }
6029 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006030
6031 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6032 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006033 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006034};
6035
Sebastian Redl78eb8742009-04-19 21:53:20 +00006036/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006037/// the set of pointer types along with any more-qualified variants of
6038/// that type. For example, if @p Ty is "int const *", this routine
6039/// will add "int const *", "int const volatile *", "int const
6040/// restrict *", and "int const volatile restrict *" to the set of
6041/// pointer types. Returns true if the add of @p Ty itself succeeded,
6042/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006043///
6044/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006045bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006046BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6047 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006048
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006049 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006050 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006051 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006052
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006053 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006054 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006055 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006056 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006057 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006058 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006059 buildObjCPtr = true;
6060 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006061 else
David Blaikieb219cfc2011-09-23 05:06:16 +00006062 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006063 }
6064 else
6065 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006066
Sebastian Redla9efada2009-11-18 20:39:26 +00006067 // Don't add qualified variants of arrays. For one, they're not allowed
6068 // (the qualifier would sink to the element type), and for another, the
6069 // only overload situation where it matters is subscript or pointer +- int,
6070 // and those shouldn't have qualifier variants anyway.
6071 if (PointeeTy->isArrayType())
6072 return true;
John McCall0953e762009-09-24 19:53:00 +00006073 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00006074 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00006075 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006076 bool hasVolatile = VisibleQuals.hasVolatile();
6077 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006078
John McCall0953e762009-09-24 19:53:00 +00006079 // Iterate through all strict supersets of BaseCVR.
6080 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6081 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006082 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
6083 // in the types.
6084 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
6085 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00006086 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006087 if (!buildObjCPtr)
6088 PointerTypes.insert(Context.getPointerType(QPointeeTy));
6089 else
6090 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006091 }
6092
6093 return true;
6094}
6095
Sebastian Redl78eb8742009-04-19 21:53:20 +00006096/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6097/// to the set of pointer types along with any more-qualified variants of
6098/// that type. For example, if @p Ty is "int const *", this routine
6099/// will add "int const *", "int const volatile *", "int const
6100/// restrict *", and "int const volatile restrict *" to the set of
6101/// pointer types. Returns true if the add of @p Ty itself succeeded,
6102/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006103///
6104/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006105bool
6106BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6107 QualType Ty) {
6108 // Insert this type.
6109 if (!MemberPointerTypes.insert(Ty))
6110 return false;
6111
John McCall0953e762009-09-24 19:53:00 +00006112 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6113 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006114
John McCall0953e762009-09-24 19:53:00 +00006115 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006116 // Don't add qualified variants of arrays. For one, they're not allowed
6117 // (the qualifier would sink to the element type), and for another, the
6118 // only overload situation where it matters is subscript or pointer +- int,
6119 // and those shouldn't have qualifier variants anyway.
6120 if (PointeeTy->isArrayType())
6121 return true;
John McCall0953e762009-09-24 19:53:00 +00006122 const Type *ClassTy = PointerTy->getClass();
6123
6124 // Iterate through all strict supersets of the pointee type's CVR
6125 // qualifiers.
6126 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6127 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6128 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006129
John McCall0953e762009-09-24 19:53:00 +00006130 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006131 MemberPointerTypes.insert(
6132 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006133 }
6134
6135 return true;
6136}
6137
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006138/// AddTypesConvertedFrom - Add each of the types to which the type @p
6139/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006140/// primarily interested in pointer types and enumeration types. We also
6141/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006142/// AllowUserConversions is true if we should look at the conversion
6143/// functions of a class type, and AllowExplicitConversions if we
6144/// should also include the explicit conversion functions of a class
6145/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006146void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006147BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006148 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006149 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006150 bool AllowExplicitConversions,
6151 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006152 // Only deal with canonical types.
6153 Ty = Context.getCanonicalType(Ty);
6154
6155 // Look through reference types; they aren't part of the type of an
6156 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006157 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006158 Ty = RefTy->getPointeeType();
6159
John McCall3b657512011-01-19 10:06:00 +00006160 // If we're dealing with an array type, decay to the pointer.
6161 if (Ty->isArrayType())
6162 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6163
6164 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006165 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006166
Chandler Carruth6a577462010-12-13 01:44:01 +00006167 // Flag if we ever add a non-record type.
6168 const RecordType *TyRec = Ty->getAs<RecordType>();
6169 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6170
Chandler Carruth6a577462010-12-13 01:44:01 +00006171 // Flag if we encounter an arithmetic type.
6172 HasArithmeticOrEnumeralTypes =
6173 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6174
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006175 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6176 PointerTypes.insert(Ty);
6177 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006178 // Insert our type, and its more-qualified variants, into the set
6179 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006180 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006181 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006182 } else if (Ty->isMemberPointerType()) {
6183 // Member pointers are far easier, since the pointee can't be converted.
6184 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6185 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006186 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006187 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006188 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006189 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006190 // We treat vector types as arithmetic types in many contexts as an
6191 // extension.
6192 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006193 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006194 } else if (Ty->isNullPtrType()) {
6195 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006196 } else if (AllowUserConversions && TyRec) {
6197 // No conversion functions in incomplete types.
6198 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6199 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006200
Chandler Carruth6a577462010-12-13 01:44:01 +00006201 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
6202 const UnresolvedSetImpl *Conversions
6203 = ClassDecl->getVisibleConversionFunctions();
6204 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
6205 E = Conversions->end(); I != E; ++I) {
6206 NamedDecl *D = I.getDecl();
6207 if (isa<UsingShadowDecl>(D))
6208 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006209
Chandler Carruth6a577462010-12-13 01:44:01 +00006210 // Skip conversion function templates; they don't tell us anything
6211 // about which builtin types we can convert to.
6212 if (isa<FunctionTemplateDecl>(D))
6213 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006214
Chandler Carruth6a577462010-12-13 01:44:01 +00006215 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6216 if (AllowExplicitConversions || !Conv->isExplicit()) {
6217 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6218 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006219 }
6220 }
6221 }
6222}
6223
Douglas Gregor19b7b152009-08-24 13:43:27 +00006224/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6225/// the volatile- and non-volatile-qualified assignment operators for the
6226/// given type to the candidate set.
6227static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6228 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006229 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006230 unsigned NumArgs,
6231 OverloadCandidateSet &CandidateSet) {
6232 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006233
Douglas Gregor19b7b152009-08-24 13:43:27 +00006234 // T& operator=(T&, T)
6235 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6236 ParamTypes[1] = T;
6237 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6238 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006239
Douglas Gregor19b7b152009-08-24 13:43:27 +00006240 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6241 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006242 ParamTypes[0]
6243 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006244 ParamTypes[1] = T;
6245 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006246 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006247 }
6248}
Mike Stump1eb44332009-09-09 15:08:12 +00006249
Sebastian Redl9994a342009-10-25 17:03:50 +00006250/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6251/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006252static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6253 Qualifiers VRQuals;
6254 const RecordType *TyRec;
6255 if (const MemberPointerType *RHSMPType =
6256 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006257 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006258 else
6259 TyRec = ArgExpr->getType()->getAs<RecordType>();
6260 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006261 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006262 VRQuals.addVolatile();
6263 VRQuals.addRestrict();
6264 return VRQuals;
6265 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006266
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006267 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006268 if (!ClassDecl->hasDefinition())
6269 return VRQuals;
6270
John McCalleec51cf2010-01-20 00:46:10 +00006271 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00006272 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006273
John McCalleec51cf2010-01-20 00:46:10 +00006274 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006275 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006276 NamedDecl *D = I.getDecl();
6277 if (isa<UsingShadowDecl>(D))
6278 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6279 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006280 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6281 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6282 CanTy = ResTypeRef->getPointeeType();
6283 // Need to go down the pointer/mempointer chain and add qualifiers
6284 // as see them.
6285 bool done = false;
6286 while (!done) {
6287 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6288 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006289 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006290 CanTy->getAs<MemberPointerType>())
6291 CanTy = ResTypeMPtr->getPointeeType();
6292 else
6293 done = true;
6294 if (CanTy.isVolatileQualified())
6295 VRQuals.addVolatile();
6296 if (CanTy.isRestrictQualified())
6297 VRQuals.addRestrict();
6298 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6299 return VRQuals;
6300 }
6301 }
6302 }
6303 return VRQuals;
6304}
John McCall00071ec2010-11-13 05:51:15 +00006305
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006306namespace {
John McCall00071ec2010-11-13 05:51:15 +00006307
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006308/// \brief Helper class to manage the addition of builtin operator overload
6309/// candidates. It provides shared state and utility methods used throughout
6310/// the process, as well as a helper method to add each group of builtin
6311/// operator overloads from the standard to a candidate set.
6312class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006313 // Common instance state available to all overload candidate addition methods.
6314 Sema &S;
6315 Expr **Args;
6316 unsigned NumArgs;
6317 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006318 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006319 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006320 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006321
Chandler Carruth6d695582010-12-12 10:35:00 +00006322 // Define some constants used to index and iterate over the arithemetic types
6323 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006324 // The "promoted arithmetic types" are the arithmetic
6325 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006326 static const unsigned FirstIntegralType = 3;
6327 static const unsigned LastIntegralType = 18;
6328 static const unsigned FirstPromotedIntegralType = 3,
6329 LastPromotedIntegralType = 9;
6330 static const unsigned FirstPromotedArithmeticType = 0,
6331 LastPromotedArithmeticType = 9;
6332 static const unsigned NumArithmeticTypes = 18;
6333
Chandler Carruth6d695582010-12-12 10:35:00 +00006334 /// \brief Get the canonical type for a given arithmetic type index.
6335 CanQualType getArithmeticType(unsigned index) {
6336 assert(index < NumArithmeticTypes);
6337 static CanQualType ASTContext::* const
6338 ArithmeticTypes[NumArithmeticTypes] = {
6339 // Start of promoted types.
6340 &ASTContext::FloatTy,
6341 &ASTContext::DoubleTy,
6342 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006343
Chandler Carruth6d695582010-12-12 10:35:00 +00006344 // Start of integral types.
6345 &ASTContext::IntTy,
6346 &ASTContext::LongTy,
6347 &ASTContext::LongLongTy,
6348 &ASTContext::UnsignedIntTy,
6349 &ASTContext::UnsignedLongTy,
6350 &ASTContext::UnsignedLongLongTy,
6351 // End of promoted types.
6352
6353 &ASTContext::BoolTy,
6354 &ASTContext::CharTy,
6355 &ASTContext::WCharTy,
6356 &ASTContext::Char16Ty,
6357 &ASTContext::Char32Ty,
6358 &ASTContext::SignedCharTy,
6359 &ASTContext::ShortTy,
6360 &ASTContext::UnsignedCharTy,
6361 &ASTContext::UnsignedShortTy,
6362 // End of integral types.
6363 // FIXME: What about complex?
6364 };
6365 return S.Context.*ArithmeticTypes[index];
6366 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006367
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006368 /// \brief Gets the canonical type resulting from the usual arithemetic
6369 /// converions for the given arithmetic types.
6370 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6371 // Accelerator table for performing the usual arithmetic conversions.
6372 // The rules are basically:
6373 // - if either is floating-point, use the wider floating-point
6374 // - if same signedness, use the higher rank
6375 // - if same size, use unsigned of the higher rank
6376 // - use the larger type
6377 // These rules, together with the axiom that higher ranks are
6378 // never smaller, are sufficient to precompute all of these results
6379 // *except* when dealing with signed types of higher rank.
6380 // (we could precompute SLL x UI for all known platforms, but it's
6381 // better not to make any assumptions).
6382 enum PromotedType {
6383 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
6384 };
6385 static PromotedType ConversionsTable[LastPromotedArithmeticType]
6386 [LastPromotedArithmeticType] = {
6387 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
6388 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6389 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6390 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
6391 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
6392 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
6393 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
6394 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
6395 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
6396 };
6397
6398 assert(L < LastPromotedArithmeticType);
6399 assert(R < LastPromotedArithmeticType);
6400 int Idx = ConversionsTable[L][R];
6401
6402 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006403 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006404
6405 // Slow path: we need to compare widths.
6406 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006407 CanQualType LT = getArithmeticType(L),
6408 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006409 unsigned LW = S.Context.getIntWidth(LT),
6410 RW = S.Context.getIntWidth(RT);
6411
6412 // If they're different widths, use the signed type.
6413 if (LW > RW) return LT;
6414 else if (LW < RW) return RT;
6415
6416 // Otherwise, use the unsigned type of the signed type's rank.
6417 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6418 assert(L == SLL || R == SLL);
6419 return S.Context.UnsignedLongLongTy;
6420 }
6421
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006422 /// \brief Helper method to factor out the common pattern of adding overloads
6423 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006424 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
6425 bool HasVolatile) {
6426 QualType ParamTypes[2] = {
6427 S.Context.getLValueReferenceType(CandidateTy),
6428 S.Context.IntTy
6429 };
6430
6431 // Non-volatile version.
6432 if (NumArgs == 1)
6433 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6434 else
6435 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6436
6437 // Use a heuristic to reduce number of builtin candidates in the set:
6438 // add volatile version only if there are conversions to a volatile type.
6439 if (HasVolatile) {
6440 ParamTypes[0] =
6441 S.Context.getLValueReferenceType(
6442 S.Context.getVolatileType(CandidateTy));
6443 if (NumArgs == 1)
6444 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6445 else
6446 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6447 }
6448 }
6449
6450public:
6451 BuiltinOperatorOverloadBuilder(
6452 Sema &S, Expr **Args, unsigned NumArgs,
6453 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006454 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006455 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006456 OverloadCandidateSet &CandidateSet)
6457 : S(S), Args(Args), NumArgs(NumArgs),
6458 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006459 HasArithmeticOrEnumeralCandidateType(
6460 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006461 CandidateTypes(CandidateTypes),
6462 CandidateSet(CandidateSet) {
6463 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006464 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006465 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006466 assert(getArithmeticType(LastPromotedIntegralType - 1)
6467 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006468 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006469 assert(getArithmeticType(FirstPromotedArithmeticType)
6470 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006471 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006472 assert(getArithmeticType(LastPromotedArithmeticType - 1)
6473 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006474 "Invalid last promoted arithmetic type");
6475 }
6476
6477 // C++ [over.built]p3:
6478 //
6479 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6480 // is either volatile or empty, there exist candidate operator
6481 // functions of the form
6482 //
6483 // VQ T& operator++(VQ T&);
6484 // T operator++(VQ T&, int);
6485 //
6486 // C++ [over.built]p4:
6487 //
6488 // For every pair (T, VQ), where T is an arithmetic type other
6489 // than bool, and VQ is either volatile or empty, there exist
6490 // candidate operator functions of the form
6491 //
6492 // VQ T& operator--(VQ T&);
6493 // T operator--(VQ T&, int);
6494 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006495 if (!HasArithmeticOrEnumeralCandidateType)
6496 return;
6497
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006498 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6499 Arith < NumArithmeticTypes; ++Arith) {
6500 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006501 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006502 VisibleTypeConversionsQuals.hasVolatile());
6503 }
6504 }
6505
6506 // C++ [over.built]p5:
6507 //
6508 // For every pair (T, VQ), where T is a cv-qualified or
6509 // cv-unqualified object type, and VQ is either volatile or
6510 // empty, there exist candidate operator functions of the form
6511 //
6512 // T*VQ& operator++(T*VQ&);
6513 // T*VQ& operator--(T*VQ&);
6514 // T* operator++(T*VQ&, int);
6515 // T* operator--(T*VQ&, int);
6516 void addPlusPlusMinusMinusPointerOverloads() {
6517 for (BuiltinCandidateTypeSet::iterator
6518 Ptr = CandidateTypes[0].pointer_begin(),
6519 PtrEnd = CandidateTypes[0].pointer_end();
6520 Ptr != PtrEnd; ++Ptr) {
6521 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006522 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006523 continue;
6524
6525 addPlusPlusMinusMinusStyleOverloads(*Ptr,
6526 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6527 VisibleTypeConversionsQuals.hasVolatile()));
6528 }
6529 }
6530
6531 // C++ [over.built]p6:
6532 // For every cv-qualified or cv-unqualified object type T, there
6533 // exist candidate operator functions of the form
6534 //
6535 // T& operator*(T*);
6536 //
6537 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006538 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006539 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006540 // T& operator*(T*);
6541 void addUnaryStarPointerOverloads() {
6542 for (BuiltinCandidateTypeSet::iterator
6543 Ptr = CandidateTypes[0].pointer_begin(),
6544 PtrEnd = CandidateTypes[0].pointer_end();
6545 Ptr != PtrEnd; ++Ptr) {
6546 QualType ParamTy = *Ptr;
6547 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006548 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6549 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006550
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006551 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6552 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6553 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006554
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006555 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6556 &ParamTy, Args, 1, CandidateSet);
6557 }
6558 }
6559
6560 // C++ [over.built]p9:
6561 // For every promoted arithmetic type T, there exist candidate
6562 // operator functions of the form
6563 //
6564 // T operator+(T);
6565 // T operator-(T);
6566 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006567 if (!HasArithmeticOrEnumeralCandidateType)
6568 return;
6569
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006570 for (unsigned Arith = FirstPromotedArithmeticType;
6571 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006572 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006573 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6574 }
6575
6576 // Extension: We also add these operators for vector types.
6577 for (BuiltinCandidateTypeSet::iterator
6578 Vec = CandidateTypes[0].vector_begin(),
6579 VecEnd = CandidateTypes[0].vector_end();
6580 Vec != VecEnd; ++Vec) {
6581 QualType VecTy = *Vec;
6582 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6583 }
6584 }
6585
6586 // C++ [over.built]p8:
6587 // For every type T, there exist candidate operator functions of
6588 // the form
6589 //
6590 // T* operator+(T*);
6591 void addUnaryPlusPointerOverloads() {
6592 for (BuiltinCandidateTypeSet::iterator
6593 Ptr = CandidateTypes[0].pointer_begin(),
6594 PtrEnd = CandidateTypes[0].pointer_end();
6595 Ptr != PtrEnd; ++Ptr) {
6596 QualType ParamTy = *Ptr;
6597 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6598 }
6599 }
6600
6601 // C++ [over.built]p10:
6602 // For every promoted integral type T, there exist candidate
6603 // operator functions of the form
6604 //
6605 // T operator~(T);
6606 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006607 if (!HasArithmeticOrEnumeralCandidateType)
6608 return;
6609
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006610 for (unsigned Int = FirstPromotedIntegralType;
6611 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006612 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006613 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6614 }
6615
6616 // Extension: We also add this operator for vector types.
6617 for (BuiltinCandidateTypeSet::iterator
6618 Vec = CandidateTypes[0].vector_begin(),
6619 VecEnd = CandidateTypes[0].vector_end();
6620 Vec != VecEnd; ++Vec) {
6621 QualType VecTy = *Vec;
6622 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6623 }
6624 }
6625
6626 // C++ [over.match.oper]p16:
6627 // For every pointer to member type T, there exist candidate operator
6628 // functions of the form
6629 //
6630 // bool operator==(T,T);
6631 // bool operator!=(T,T);
6632 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6633 /// Set of (canonical) types that we've already handled.
6634 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6635
6636 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6637 for (BuiltinCandidateTypeSet::iterator
6638 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6639 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6640 MemPtr != MemPtrEnd;
6641 ++MemPtr) {
6642 // Don't add the same builtin candidate twice.
6643 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6644 continue;
6645
6646 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6647 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6648 CandidateSet);
6649 }
6650 }
6651 }
6652
6653 // C++ [over.built]p15:
6654 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006655 // For every T, where T is an enumeration type, a pointer type, or
6656 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006657 //
6658 // bool operator<(T, T);
6659 // bool operator>(T, T);
6660 // bool operator<=(T, T);
6661 // bool operator>=(T, T);
6662 // bool operator==(T, T);
6663 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006664 void addRelationalPointerOrEnumeralOverloads() {
6665 // C++ [over.built]p1:
6666 // If there is a user-written candidate with the same name and parameter
6667 // types as a built-in candidate operator function, the built-in operator
6668 // function is hidden and is not included in the set of candidate
6669 // functions.
6670 //
6671 // The text is actually in a note, but if we don't implement it then we end
6672 // up with ambiguities when the user provides an overloaded operator for
6673 // an enumeration type. Note that only enumeration types have this problem,
6674 // so we track which enumeration types we've seen operators for. Also, the
6675 // only other overloaded operator with enumeration argumenst, operator=,
6676 // cannot be overloaded for enumeration types, so this is the only place
6677 // where we must suppress candidates like this.
6678 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6679 UserDefinedBinaryOperators;
6680
6681 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6682 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6683 CandidateTypes[ArgIdx].enumeration_end()) {
6684 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6685 CEnd = CandidateSet.end();
6686 C != CEnd; ++C) {
6687 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6688 continue;
6689
6690 QualType FirstParamType =
6691 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6692 QualType SecondParamType =
6693 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6694
6695 // Skip if either parameter isn't of enumeral type.
6696 if (!FirstParamType->isEnumeralType() ||
6697 !SecondParamType->isEnumeralType())
6698 continue;
6699
6700 // Add this operator to the set of known user-defined operators.
6701 UserDefinedBinaryOperators.insert(
6702 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6703 S.Context.getCanonicalType(SecondParamType)));
6704 }
6705 }
6706 }
6707
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006708 /// Set of (canonical) types that we've already handled.
6709 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6710
6711 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6712 for (BuiltinCandidateTypeSet::iterator
6713 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6714 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6715 Ptr != PtrEnd; ++Ptr) {
6716 // Don't add the same builtin candidate twice.
6717 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6718 continue;
6719
6720 QualType ParamTypes[2] = { *Ptr, *Ptr };
6721 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6722 CandidateSet);
6723 }
6724 for (BuiltinCandidateTypeSet::iterator
6725 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6726 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6727 Enum != EnumEnd; ++Enum) {
6728 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6729
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006730 // Don't add the same builtin candidate twice, or if a user defined
6731 // candidate exists.
6732 if (!AddedTypes.insert(CanonType) ||
6733 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6734 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006735 continue;
6736
6737 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006738 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6739 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006740 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006741
6742 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6743 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6744 if (AddedTypes.insert(NullPtrTy) &&
6745 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6746 NullPtrTy))) {
6747 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6748 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6749 CandidateSet);
6750 }
6751 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006752 }
6753 }
6754
6755 // C++ [over.built]p13:
6756 //
6757 // For every cv-qualified or cv-unqualified object type T
6758 // there exist candidate operator functions of the form
6759 //
6760 // T* operator+(T*, ptrdiff_t);
6761 // T& operator[](T*, ptrdiff_t); [BELOW]
6762 // T* operator-(T*, ptrdiff_t);
6763 // T* operator+(ptrdiff_t, T*);
6764 // T& operator[](ptrdiff_t, T*); [BELOW]
6765 //
6766 // C++ [over.built]p14:
6767 //
6768 // For every T, where T is a pointer to object type, there
6769 // exist candidate operator functions of the form
6770 //
6771 // ptrdiff_t operator-(T, T);
6772 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6773 /// Set of (canonical) types that we've already handled.
6774 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6775
6776 for (int Arg = 0; Arg < 2; ++Arg) {
6777 QualType AsymetricParamTypes[2] = {
6778 S.Context.getPointerDiffType(),
6779 S.Context.getPointerDiffType(),
6780 };
6781 for (BuiltinCandidateTypeSet::iterator
6782 Ptr = CandidateTypes[Arg].pointer_begin(),
6783 PtrEnd = CandidateTypes[Arg].pointer_end();
6784 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006785 QualType PointeeTy = (*Ptr)->getPointeeType();
6786 if (!PointeeTy->isObjectType())
6787 continue;
6788
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006789 AsymetricParamTypes[Arg] = *Ptr;
6790 if (Arg == 0 || Op == OO_Plus) {
6791 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6792 // T* operator+(ptrdiff_t, T*);
6793 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6794 CandidateSet);
6795 }
6796 if (Op == OO_Minus) {
6797 // ptrdiff_t operator-(T, T);
6798 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6799 continue;
6800
6801 QualType ParamTypes[2] = { *Ptr, *Ptr };
6802 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6803 Args, 2, CandidateSet);
6804 }
6805 }
6806 }
6807 }
6808
6809 // C++ [over.built]p12:
6810 //
6811 // For every pair of promoted arithmetic types L and R, there
6812 // exist candidate operator functions of the form
6813 //
6814 // LR operator*(L, R);
6815 // LR operator/(L, R);
6816 // LR operator+(L, R);
6817 // LR operator-(L, R);
6818 // bool operator<(L, R);
6819 // bool operator>(L, R);
6820 // bool operator<=(L, R);
6821 // bool operator>=(L, R);
6822 // bool operator==(L, R);
6823 // bool operator!=(L, R);
6824 //
6825 // where LR is the result of the usual arithmetic conversions
6826 // between types L and R.
6827 //
6828 // C++ [over.built]p24:
6829 //
6830 // For every pair of promoted arithmetic types L and R, there exist
6831 // candidate operator functions of the form
6832 //
6833 // LR operator?(bool, L, R);
6834 //
6835 // where LR is the result of the usual arithmetic conversions
6836 // between types L and R.
6837 // Our candidates ignore the first parameter.
6838 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006839 if (!HasArithmeticOrEnumeralCandidateType)
6840 return;
6841
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006842 for (unsigned Left = FirstPromotedArithmeticType;
6843 Left < LastPromotedArithmeticType; ++Left) {
6844 for (unsigned Right = FirstPromotedArithmeticType;
6845 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006846 QualType LandR[2] = { getArithmeticType(Left),
6847 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006848 QualType Result =
6849 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006850 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006851 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6852 }
6853 }
6854
6855 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6856 // conditional operator for vector types.
6857 for (BuiltinCandidateTypeSet::iterator
6858 Vec1 = CandidateTypes[0].vector_begin(),
6859 Vec1End = CandidateTypes[0].vector_end();
6860 Vec1 != Vec1End; ++Vec1) {
6861 for (BuiltinCandidateTypeSet::iterator
6862 Vec2 = CandidateTypes[1].vector_begin(),
6863 Vec2End = CandidateTypes[1].vector_end();
6864 Vec2 != Vec2End; ++Vec2) {
6865 QualType LandR[2] = { *Vec1, *Vec2 };
6866 QualType Result = S.Context.BoolTy;
6867 if (!isComparison) {
6868 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6869 Result = *Vec1;
6870 else
6871 Result = *Vec2;
6872 }
6873
6874 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6875 }
6876 }
6877 }
6878
6879 // C++ [over.built]p17:
6880 //
6881 // For every pair of promoted integral types L and R, there
6882 // exist candidate operator functions of the form
6883 //
6884 // LR operator%(L, R);
6885 // LR operator&(L, R);
6886 // LR operator^(L, R);
6887 // LR operator|(L, R);
6888 // L operator<<(L, R);
6889 // L operator>>(L, R);
6890 //
6891 // where LR is the result of the usual arithmetic conversions
6892 // between types L and R.
6893 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006894 if (!HasArithmeticOrEnumeralCandidateType)
6895 return;
6896
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006897 for (unsigned Left = FirstPromotedIntegralType;
6898 Left < LastPromotedIntegralType; ++Left) {
6899 for (unsigned Right = FirstPromotedIntegralType;
6900 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006901 QualType LandR[2] = { getArithmeticType(Left),
6902 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006903 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6904 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006905 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006906 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6907 }
6908 }
6909 }
6910
6911 // C++ [over.built]p20:
6912 //
6913 // For every pair (T, VQ), where T is an enumeration or
6914 // pointer to member type and VQ is either volatile or
6915 // empty, there exist candidate operator functions of the form
6916 //
6917 // VQ T& operator=(VQ T&, T);
6918 void addAssignmentMemberPointerOrEnumeralOverloads() {
6919 /// Set of (canonical) types that we've already handled.
6920 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6921
6922 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6923 for (BuiltinCandidateTypeSet::iterator
6924 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6925 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6926 Enum != EnumEnd; ++Enum) {
6927 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6928 continue;
6929
6930 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6931 CandidateSet);
6932 }
6933
6934 for (BuiltinCandidateTypeSet::iterator
6935 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6936 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6937 MemPtr != MemPtrEnd; ++MemPtr) {
6938 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6939 continue;
6940
6941 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6942 CandidateSet);
6943 }
6944 }
6945 }
6946
6947 // C++ [over.built]p19:
6948 //
6949 // For every pair (T, VQ), where T is any type and VQ is either
6950 // volatile or empty, there exist candidate operator functions
6951 // of the form
6952 //
6953 // T*VQ& operator=(T*VQ&, T*);
6954 //
6955 // C++ [over.built]p21:
6956 //
6957 // For every pair (T, VQ), where T is a cv-qualified or
6958 // cv-unqualified object type and VQ is either volatile or
6959 // empty, there exist candidate operator functions of the form
6960 //
6961 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6962 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6963 void addAssignmentPointerOverloads(bool isEqualOp) {
6964 /// Set of (canonical) types that we've already handled.
6965 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6966
6967 for (BuiltinCandidateTypeSet::iterator
6968 Ptr = CandidateTypes[0].pointer_begin(),
6969 PtrEnd = CandidateTypes[0].pointer_end();
6970 Ptr != PtrEnd; ++Ptr) {
6971 // If this is operator=, keep track of the builtin candidates we added.
6972 if (isEqualOp)
6973 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006974 else if (!(*Ptr)->getPointeeType()->isObjectType())
6975 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006976
6977 // non-volatile version
6978 QualType ParamTypes[2] = {
6979 S.Context.getLValueReferenceType(*Ptr),
6980 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6981 };
6982 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6983 /*IsAssigmentOperator=*/ isEqualOp);
6984
6985 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6986 VisibleTypeConversionsQuals.hasVolatile()) {
6987 // volatile version
6988 ParamTypes[0] =
6989 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6990 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6991 /*IsAssigmentOperator=*/isEqualOp);
6992 }
6993 }
6994
6995 if (isEqualOp) {
6996 for (BuiltinCandidateTypeSet::iterator
6997 Ptr = CandidateTypes[1].pointer_begin(),
6998 PtrEnd = CandidateTypes[1].pointer_end();
6999 Ptr != PtrEnd; ++Ptr) {
7000 // Make sure we don't add the same candidate twice.
7001 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7002 continue;
7003
Chandler Carruth6df868e2010-12-12 08:17:55 +00007004 QualType ParamTypes[2] = {
7005 S.Context.getLValueReferenceType(*Ptr),
7006 *Ptr,
7007 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007008
7009 // non-volatile version
7010 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7011 /*IsAssigmentOperator=*/true);
7012
7013 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
7014 VisibleTypeConversionsQuals.hasVolatile()) {
7015 // volatile version
7016 ParamTypes[0] =
7017 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007018 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7019 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007020 }
7021 }
7022 }
7023 }
7024
7025 // C++ [over.built]p18:
7026 //
7027 // For every triple (L, VQ, R), where L is an arithmetic type,
7028 // VQ is either volatile or empty, and R is a promoted
7029 // arithmetic type, there exist candidate operator functions of
7030 // the form
7031 //
7032 // VQ L& operator=(VQ L&, R);
7033 // VQ L& operator*=(VQ L&, R);
7034 // VQ L& operator/=(VQ L&, R);
7035 // VQ L& operator+=(VQ L&, R);
7036 // VQ L& operator-=(VQ L&, R);
7037 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007038 if (!HasArithmeticOrEnumeralCandidateType)
7039 return;
7040
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007041 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7042 for (unsigned Right = FirstPromotedArithmeticType;
7043 Right < LastPromotedArithmeticType; ++Right) {
7044 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007045 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007046
7047 // Add this built-in operator as a candidate (VQ is empty).
7048 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007049 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007050 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7051 /*IsAssigmentOperator=*/isEqualOp);
7052
7053 // Add this built-in operator as a candidate (VQ is 'volatile').
7054 if (VisibleTypeConversionsQuals.hasVolatile()) {
7055 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007056 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007057 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007058 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7059 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007060 /*IsAssigmentOperator=*/isEqualOp);
7061 }
7062 }
7063 }
7064
7065 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7066 for (BuiltinCandidateTypeSet::iterator
7067 Vec1 = CandidateTypes[0].vector_begin(),
7068 Vec1End = CandidateTypes[0].vector_end();
7069 Vec1 != Vec1End; ++Vec1) {
7070 for (BuiltinCandidateTypeSet::iterator
7071 Vec2 = CandidateTypes[1].vector_begin(),
7072 Vec2End = CandidateTypes[1].vector_end();
7073 Vec2 != Vec2End; ++Vec2) {
7074 QualType ParamTypes[2];
7075 ParamTypes[1] = *Vec2;
7076 // Add this built-in operator as a candidate (VQ is empty).
7077 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7078 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7079 /*IsAssigmentOperator=*/isEqualOp);
7080
7081 // Add this built-in operator as a candidate (VQ is 'volatile').
7082 if (VisibleTypeConversionsQuals.hasVolatile()) {
7083 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7084 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007085 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7086 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007087 /*IsAssigmentOperator=*/isEqualOp);
7088 }
7089 }
7090 }
7091 }
7092
7093 // C++ [over.built]p22:
7094 //
7095 // For every triple (L, VQ, R), where L is an integral type, VQ
7096 // is either volatile or empty, and R is a promoted integral
7097 // type, there exist candidate operator functions of the form
7098 //
7099 // VQ L& operator%=(VQ L&, R);
7100 // VQ L& operator<<=(VQ L&, R);
7101 // VQ L& operator>>=(VQ L&, R);
7102 // VQ L& operator&=(VQ L&, R);
7103 // VQ L& operator^=(VQ L&, R);
7104 // VQ L& operator|=(VQ L&, R);
7105 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007106 if (!HasArithmeticOrEnumeralCandidateType)
7107 return;
7108
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007109 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7110 for (unsigned Right = FirstPromotedIntegralType;
7111 Right < LastPromotedIntegralType; ++Right) {
7112 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007113 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007114
7115 // Add this built-in operator as a candidate (VQ is empty).
7116 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007117 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7119 if (VisibleTypeConversionsQuals.hasVolatile()) {
7120 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007121 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007122 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7123 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7124 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7125 CandidateSet);
7126 }
7127 }
7128 }
7129 }
7130
7131 // C++ [over.operator]p23:
7132 //
7133 // There also exist candidate operator functions of the form
7134 //
7135 // bool operator!(bool);
7136 // bool operator&&(bool, bool);
7137 // bool operator||(bool, bool);
7138 void addExclaimOverload() {
7139 QualType ParamTy = S.Context.BoolTy;
7140 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7141 /*IsAssignmentOperator=*/false,
7142 /*NumContextualBoolArguments=*/1);
7143 }
7144 void addAmpAmpOrPipePipeOverload() {
7145 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7146 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7147 /*IsAssignmentOperator=*/false,
7148 /*NumContextualBoolArguments=*/2);
7149 }
7150
7151 // C++ [over.built]p13:
7152 //
7153 // For every cv-qualified or cv-unqualified object type T there
7154 // exist candidate operator functions of the form
7155 //
7156 // T* operator+(T*, ptrdiff_t); [ABOVE]
7157 // T& operator[](T*, ptrdiff_t);
7158 // T* operator-(T*, ptrdiff_t); [ABOVE]
7159 // T* operator+(ptrdiff_t, T*); [ABOVE]
7160 // T& operator[](ptrdiff_t, T*);
7161 void addSubscriptOverloads() {
7162 for (BuiltinCandidateTypeSet::iterator
7163 Ptr = CandidateTypes[0].pointer_begin(),
7164 PtrEnd = CandidateTypes[0].pointer_end();
7165 Ptr != PtrEnd; ++Ptr) {
7166 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7167 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007168 if (!PointeeType->isObjectType())
7169 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007170
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007171 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7172
7173 // T& operator[](T*, ptrdiff_t)
7174 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7175 }
7176
7177 for (BuiltinCandidateTypeSet::iterator
7178 Ptr = CandidateTypes[1].pointer_begin(),
7179 PtrEnd = CandidateTypes[1].pointer_end();
7180 Ptr != PtrEnd; ++Ptr) {
7181 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7182 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007183 if (!PointeeType->isObjectType())
7184 continue;
7185
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007186 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7187
7188 // T& operator[](ptrdiff_t, T*)
7189 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7190 }
7191 }
7192
7193 // C++ [over.built]p11:
7194 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7195 // C1 is the same type as C2 or is a derived class of C2, T is an object
7196 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7197 // there exist candidate operator functions of the form
7198 //
7199 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7200 //
7201 // where CV12 is the union of CV1 and CV2.
7202 void addArrowStarOverloads() {
7203 for (BuiltinCandidateTypeSet::iterator
7204 Ptr = CandidateTypes[0].pointer_begin(),
7205 PtrEnd = CandidateTypes[0].pointer_end();
7206 Ptr != PtrEnd; ++Ptr) {
7207 QualType C1Ty = (*Ptr);
7208 QualType C1;
7209 QualifierCollector Q1;
7210 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7211 if (!isa<RecordType>(C1))
7212 continue;
7213 // heuristic to reduce number of builtin candidates in the set.
7214 // Add volatile/restrict version only if there are conversions to a
7215 // volatile/restrict type.
7216 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7217 continue;
7218 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7219 continue;
7220 for (BuiltinCandidateTypeSet::iterator
7221 MemPtr = CandidateTypes[1].member_pointer_begin(),
7222 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7223 MemPtr != MemPtrEnd; ++MemPtr) {
7224 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7225 QualType C2 = QualType(mptr->getClass(), 0);
7226 C2 = C2.getUnqualifiedType();
7227 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7228 break;
7229 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7230 // build CV12 T&
7231 QualType T = mptr->getPointeeType();
7232 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7233 T.isVolatileQualified())
7234 continue;
7235 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7236 T.isRestrictQualified())
7237 continue;
7238 T = Q1.apply(S.Context, T);
7239 QualType ResultTy = S.Context.getLValueReferenceType(T);
7240 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7241 }
7242 }
7243 }
7244
7245 // Note that we don't consider the first argument, since it has been
7246 // contextually converted to bool long ago. The candidates below are
7247 // therefore added as binary.
7248 //
7249 // C++ [over.built]p25:
7250 // For every type T, where T is a pointer, pointer-to-member, or scoped
7251 // enumeration type, there exist candidate operator functions of the form
7252 //
7253 // T operator?(bool, T, T);
7254 //
7255 void addConditionalOperatorOverloads() {
7256 /// Set of (canonical) types that we've already handled.
7257 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7258
7259 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7260 for (BuiltinCandidateTypeSet::iterator
7261 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7262 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7263 Ptr != PtrEnd; ++Ptr) {
7264 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7265 continue;
7266
7267 QualType ParamTypes[2] = { *Ptr, *Ptr };
7268 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7269 }
7270
7271 for (BuiltinCandidateTypeSet::iterator
7272 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7273 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7274 MemPtr != MemPtrEnd; ++MemPtr) {
7275 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7276 continue;
7277
7278 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7279 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7280 }
7281
David Blaikie4e4d0842012-03-11 07:00:24 +00007282 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007283 for (BuiltinCandidateTypeSet::iterator
7284 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7285 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7286 Enum != EnumEnd; ++Enum) {
7287 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7288 continue;
7289
7290 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7291 continue;
7292
7293 QualType ParamTypes[2] = { *Enum, *Enum };
7294 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7295 }
7296 }
7297 }
7298 }
7299};
7300
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007301} // end anonymous namespace
7302
7303/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7304/// operator overloads to the candidate set (C++ [over.built]), based
7305/// on the operator @p Op and the arguments given. For example, if the
7306/// operator is a binary '+', this routine might add "int
7307/// operator+(int, int)" to cover integer addition.
7308void
7309Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7310 SourceLocation OpLoc,
7311 Expr **Args, unsigned NumArgs,
7312 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007313 // Find all of the types that the arguments can convert to, but only
7314 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007315 // that make use of these types. Also record whether we encounter non-record
7316 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007317 Qualifiers VisibleTypeConversionsQuals;
7318 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007319 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7320 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007321
7322 bool HasNonRecordCandidateType = false;
7323 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007324 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007325 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7326 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7327 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7328 OpLoc,
7329 true,
7330 (Op == OO_Exclaim ||
7331 Op == OO_AmpAmp ||
7332 Op == OO_PipePipe),
7333 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007334 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7335 CandidateTypes[ArgIdx].hasNonRecordTypes();
7336 HasArithmeticOrEnumeralCandidateType =
7337 HasArithmeticOrEnumeralCandidateType ||
7338 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007339 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007340
Chandler Carruth6a577462010-12-13 01:44:01 +00007341 // Exit early when no non-record types have been added to the candidate set
7342 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007343 //
7344 // We can't exit early for !, ||, or &&, since there we have always have
7345 // 'bool' overloads.
7346 if (!HasNonRecordCandidateType &&
7347 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007348 return;
7349
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007350 // Setup an object to manage the common state for building overloads.
7351 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7352 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007353 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007354 CandidateTypes, CandidateSet);
7355
7356 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007357 switch (Op) {
7358 case OO_None:
7359 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007360 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007361
Chandler Carruthabb71842010-12-12 08:51:33 +00007362 case OO_New:
7363 case OO_Delete:
7364 case OO_Array_New:
7365 case OO_Array_Delete:
7366 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007367 llvm_unreachable(
7368 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007369
7370 case OO_Comma:
7371 case OO_Arrow:
7372 // C++ [over.match.oper]p3:
7373 // -- For the operator ',', the unary operator '&', or the
7374 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007375 break;
7376
7377 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007378 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007379 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007380 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007381
7382 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007383 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007384 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007385 } else {
7386 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7387 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7388 }
Douglas Gregor74253732008-11-19 15:42:04 +00007389 break;
7390
Chandler Carruthabb71842010-12-12 08:51:33 +00007391 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007392 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007393 OpBuilder.addUnaryStarPointerOverloads();
7394 else
7395 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7396 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007397
Chandler Carruthabb71842010-12-12 08:51:33 +00007398 case OO_Slash:
7399 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007400 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007401
7402 case OO_PlusPlus:
7403 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007404 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7405 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007406 break;
7407
Douglas Gregor19b7b152009-08-24 13:43:27 +00007408 case OO_EqualEqual:
7409 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007410 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007411 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007412
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007413 case OO_Less:
7414 case OO_Greater:
7415 case OO_LessEqual:
7416 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007417 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007418 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7419 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007420
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007421 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007422 case OO_Caret:
7423 case OO_Pipe:
7424 case OO_LessLess:
7425 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007426 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007427 break;
7428
Chandler Carruthabb71842010-12-12 08:51:33 +00007429 case OO_Amp: // '&' is either unary or binary
7430 if (NumArgs == 1)
7431 // C++ [over.match.oper]p3:
7432 // -- For the operator ',', the unary operator '&', or the
7433 // operator '->', the built-in candidates set is empty.
7434 break;
7435
7436 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7437 break;
7438
7439 case OO_Tilde:
7440 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7441 break;
7442
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007443 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007444 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007445 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007446
7447 case OO_PlusEqual:
7448 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007449 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007450 // Fall through.
7451
7452 case OO_StarEqual:
7453 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007454 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007455 break;
7456
7457 case OO_PercentEqual:
7458 case OO_LessLessEqual:
7459 case OO_GreaterGreaterEqual:
7460 case OO_AmpEqual:
7461 case OO_CaretEqual:
7462 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007463 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007464 break;
7465
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007466 case OO_Exclaim:
7467 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007468 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007469
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007470 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007471 case OO_PipePipe:
7472 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007473 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007474
7475 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007476 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007477 break;
7478
7479 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007480 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007481 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007482
7483 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007484 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007485 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7486 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007487 }
7488}
7489
Douglas Gregorfa047642009-02-04 00:32:51 +00007490/// \brief Add function candidates found via argument-dependent lookup
7491/// to the set of overloading candidates.
7492///
7493/// This routine performs argument-dependent name lookup based on the
7494/// given function name (which may also be an operator name) and adds
7495/// all of the overload candidates found by ADL to the overload
7496/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007497void
Douglas Gregorfa047642009-02-04 00:32:51 +00007498Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007499 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007500 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007501 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007502 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00007503 bool PartialOverloading,
7504 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00007505 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007506
John McCalla113e722010-01-26 06:04:06 +00007507 // FIXME: This approach for uniquing ADL results (and removing
7508 // redundant candidates from the set) relies on pointer-equality,
7509 // which means we need to key off the canonical decl. However,
7510 // always going back to the canonical decl might not get us the
7511 // right set of default arguments. What default arguments are
7512 // we supposed to consider on ADL candidates, anyway?
7513
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007514 // FIXME: Pass in the explicit template arguments?
Ahmed Charles13a140c2012-02-25 11:00:22 +00007515 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns,
Richard Smithad762fc2011-04-14 22:09:26 +00007516 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00007517
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007518 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007519 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7520 CandEnd = CandidateSet.end();
7521 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007522 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007523 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007524 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007525 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007526 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007527
7528 // For each of the ADL candidates we found, add it to the overload
7529 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007530 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007531 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007532 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007533 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007534 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007535
Ahmed Charles13a140c2012-02-25 11:00:22 +00007536 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7537 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007538 } else
John McCall6e266892010-01-26 03:27:55 +00007539 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007540 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007541 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007542 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007543}
7544
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007545/// isBetterOverloadCandidate - Determines whether the first overload
7546/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007547bool
John McCall120d63c2010-08-24 20:38:10 +00007548isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007549 const OverloadCandidate &Cand1,
7550 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007551 SourceLocation Loc,
7552 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007553 // Define viable functions to be better candidates than non-viable
7554 // functions.
7555 if (!Cand2.Viable)
7556 return Cand1.Viable;
7557 else if (!Cand1.Viable)
7558 return false;
7559
Douglas Gregor88a35142008-12-22 05:46:06 +00007560 // C++ [over.match.best]p1:
7561 //
7562 // -- if F is a static member function, ICS1(F) is defined such
7563 // that ICS1(F) is neither better nor worse than ICS1(G) for
7564 // any function G, and, symmetrically, ICS1(G) is neither
7565 // better nor worse than ICS1(F).
7566 unsigned StartArg = 0;
7567 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7568 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007569
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007570 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007571 // A viable function F1 is defined to be a better function than another
7572 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007573 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007574 unsigned NumArgs = Cand1.NumConversions;
7575 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007576 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007577 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007578 switch (CompareImplicitConversionSequences(S,
7579 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007580 Cand2.Conversions[ArgIdx])) {
7581 case ImplicitConversionSequence::Better:
7582 // Cand1 has a better conversion sequence.
7583 HasBetterConversion = true;
7584 break;
7585
7586 case ImplicitConversionSequence::Worse:
7587 // Cand1 can't be better than Cand2.
7588 return false;
7589
7590 case ImplicitConversionSequence::Indistinguishable:
7591 // Do nothing.
7592 break;
7593 }
7594 }
7595
Mike Stump1eb44332009-09-09 15:08:12 +00007596 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007597 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007598 if (HasBetterConversion)
7599 return true;
7600
Mike Stump1eb44332009-09-09 15:08:12 +00007601 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007602 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007603 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007604 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7605 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007606
7607 // -- F1 and F2 are function template specializations, and the function
7608 // template for F1 is more specialized than the template for F2
7609 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007610 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007611 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007612 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007613 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007614 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7615 Cand2.Function->getPrimaryTemplate(),
7616 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007617 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007618 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007619 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007620 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007621 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007622
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007623 // -- the context is an initialization by user-defined conversion
7624 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7625 // from the return type of F1 to the destination type (i.e.,
7626 // the type of the entity being initialized) is a better
7627 // conversion sequence than the standard conversion sequence
7628 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007629 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007630 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007631 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007632 // First check whether we prefer one of the conversion functions over the
7633 // other. This only distinguishes the results in non-standard, extension
7634 // cases such as the conversion from a lambda closure type to a function
7635 // pointer or block.
7636 ImplicitConversionSequence::CompareKind FuncResult
7637 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7638 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7639 return FuncResult;
7640
John McCall120d63c2010-08-24 20:38:10 +00007641 switch (CompareStandardConversionSequences(S,
7642 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007643 Cand2.FinalConversion)) {
7644 case ImplicitConversionSequence::Better:
7645 // Cand1 has a better conversion sequence.
7646 return true;
7647
7648 case ImplicitConversionSequence::Worse:
7649 // Cand1 can't be better than Cand2.
7650 return false;
7651
7652 case ImplicitConversionSequence::Indistinguishable:
7653 // Do nothing
7654 break;
7655 }
7656 }
7657
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007658 return false;
7659}
7660
Mike Stump1eb44332009-09-09 15:08:12 +00007661/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007662/// within an overload candidate set.
7663///
7664/// \param CandidateSet the set of candidate functions.
7665///
7666/// \param Loc the location of the function name (or operator symbol) for
7667/// which overload resolution occurs.
7668///
Mike Stump1eb44332009-09-09 15:08:12 +00007669/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007670/// function, Best points to the candidate function found.
7671///
7672/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007673OverloadingResult
7674OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007675 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007676 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007677 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007678 Best = end();
7679 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7680 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007681 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007682 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007683 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007684 }
7685
7686 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007687 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007688 return OR_No_Viable_Function;
7689
7690 // Make sure that this function is better than every other viable
7691 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007692 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007693 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007694 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007695 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007696 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007697 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007698 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007699 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007700 }
Mike Stump1eb44332009-09-09 15:08:12 +00007701
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007702 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007703 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007704 (Best->Function->isDeleted() ||
7705 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007706 return OR_Deleted;
7707
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007708 return OR_Success;
7709}
7710
John McCall3c80f572010-01-12 02:15:36 +00007711namespace {
7712
7713enum OverloadCandidateKind {
7714 oc_function,
7715 oc_method,
7716 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007717 oc_function_template,
7718 oc_method_template,
7719 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007720 oc_implicit_default_constructor,
7721 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007722 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007723 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007724 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007725 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007726};
7727
John McCall220ccbf2010-01-13 00:25:19 +00007728OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7729 FunctionDecl *Fn,
7730 std::string &Description) {
7731 bool isTemplate = false;
7732
7733 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7734 isTemplate = true;
7735 Description = S.getTemplateArgumentBindingsText(
7736 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7737 }
John McCallb1622a12010-01-06 09:43:14 +00007738
7739 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007740 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007741 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007742
Sebastian Redlf677ea32011-02-05 19:23:19 +00007743 if (Ctor->getInheritedConstructor())
7744 return oc_implicit_inherited_constructor;
7745
Sean Hunt82713172011-05-25 23:16:36 +00007746 if (Ctor->isDefaultConstructor())
7747 return oc_implicit_default_constructor;
7748
7749 if (Ctor->isMoveConstructor())
7750 return oc_implicit_move_constructor;
7751
7752 assert(Ctor->isCopyConstructor() &&
7753 "unexpected sort of implicit constructor");
7754 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007755 }
7756
7757 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7758 // This actually gets spelled 'candidate function' for now, but
7759 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007760 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007761 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007762
Sean Hunt82713172011-05-25 23:16:36 +00007763 if (Meth->isMoveAssignmentOperator())
7764 return oc_implicit_move_assignment;
7765
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007766 if (Meth->isCopyAssignmentOperator())
7767 return oc_implicit_copy_assignment;
7768
7769 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7770 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007771 }
7772
John McCall220ccbf2010-01-13 00:25:19 +00007773 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007774}
7775
Sebastian Redlf677ea32011-02-05 19:23:19 +00007776void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7777 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7778 if (!Ctor) return;
7779
7780 Ctor = Ctor->getInheritedConstructor();
7781 if (!Ctor) return;
7782
7783 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7784}
7785
John McCall3c80f572010-01-12 02:15:36 +00007786} // end anonymous namespace
7787
7788// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007789void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007790 std::string FnDesc;
7791 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007792 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7793 << (unsigned) K << FnDesc;
7794 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7795 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007796 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007797}
7798
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007799//Notes the location of all overload candidates designated through
7800// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007801void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007802 assert(OverloadedExpr->getType() == Context.OverloadTy);
7803
7804 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7805 OverloadExpr *OvlExpr = Ovl.Expression;
7806
7807 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7808 IEnd = OvlExpr->decls_end();
7809 I != IEnd; ++I) {
7810 if (FunctionTemplateDecl *FunTmpl =
7811 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007812 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007813 } else if (FunctionDecl *Fun
7814 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007815 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007816 }
7817 }
7818}
7819
John McCall1d318332010-01-12 00:44:57 +00007820/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7821/// "lead" diagnostic; it will be given two arguments, the source and
7822/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007823void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7824 Sema &S,
7825 SourceLocation CaretLoc,
7826 const PartialDiagnostic &PDiag) const {
7827 S.Diag(CaretLoc, PDiag)
7828 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007829 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007830 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7831 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007832 }
John McCall81201622010-01-08 04:41:39 +00007833}
7834
John McCall1d318332010-01-12 00:44:57 +00007835namespace {
7836
John McCalladbb8f82010-01-13 09:16:55 +00007837void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7838 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7839 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007840 assert(Cand->Function && "for now, candidate must be a function");
7841 FunctionDecl *Fn = Cand->Function;
7842
7843 // There's a conversion slot for the object argument if this is a
7844 // non-constructor method. Note that 'I' corresponds the
7845 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007846 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007847 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007848 if (I == 0)
7849 isObjectArgument = true;
7850 else
7851 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007852 }
7853
John McCall220ccbf2010-01-13 00:25:19 +00007854 std::string FnDesc;
7855 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7856
John McCalladbb8f82010-01-13 09:16:55 +00007857 Expr *FromExpr = Conv.Bad.FromExpr;
7858 QualType FromTy = Conv.Bad.getFromType();
7859 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007860
John McCall5920dbb2010-02-02 02:42:52 +00007861 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007862 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007863 Expr *E = FromExpr->IgnoreParens();
7864 if (isa<UnaryOperator>(E))
7865 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007866 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007867
7868 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7869 << (unsigned) FnKind << FnDesc
7870 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7871 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007872 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007873 return;
7874 }
7875
John McCall258b2032010-01-23 08:10:49 +00007876 // Do some hand-waving analysis to see if the non-viability is due
7877 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007878 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7879 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7880 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7881 CToTy = RT->getPointeeType();
7882 else {
7883 // TODO: detect and diagnose the full richness of const mismatches.
7884 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7885 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7886 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7887 }
7888
7889 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7890 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00007891 Qualifiers FromQs = CFromTy.getQualifiers();
7892 Qualifiers ToQs = CToTy.getQualifiers();
7893
7894 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7895 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7896 << (unsigned) FnKind << FnDesc
7897 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7898 << FromTy
7899 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7900 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007901 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007902 return;
7903 }
7904
John McCallf85e1932011-06-15 23:02:42 +00007905 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007906 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007907 << (unsigned) FnKind << FnDesc
7908 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7909 << FromTy
7910 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7911 << (unsigned) isObjectArgument << I+1;
7912 MaybeEmitInheritedConstructorNote(S, Fn);
7913 return;
7914 }
7915
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007916 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7918 << (unsigned) FnKind << FnDesc
7919 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7920 << FromTy
7921 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7922 << (unsigned) isObjectArgument << I+1;
7923 MaybeEmitInheritedConstructorNote(S, Fn);
7924 return;
7925 }
7926
John McCall651f3ee2010-01-14 03:28:57 +00007927 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7928 assert(CVR && "unexpected qualifiers mismatch");
7929
7930 if (isObjectArgument) {
7931 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7932 << (unsigned) FnKind << FnDesc
7933 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7934 << FromTy << (CVR - 1);
7935 } else {
7936 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7937 << (unsigned) FnKind << FnDesc
7938 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7939 << FromTy << (CVR - 1) << I+1;
7940 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007941 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007942 return;
7943 }
7944
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007945 // Special diagnostic for failure to convert an initializer list, since
7946 // telling the user that it has type void is not useful.
7947 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7948 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7949 << (unsigned) FnKind << FnDesc
7950 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7951 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7952 MaybeEmitInheritedConstructorNote(S, Fn);
7953 return;
7954 }
7955
John McCall258b2032010-01-23 08:10:49 +00007956 // Diagnose references or pointers to incomplete types differently,
7957 // since it's far from impossible that the incompleteness triggered
7958 // the failure.
7959 QualType TempFromTy = FromTy.getNonReferenceType();
7960 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7961 TempFromTy = PTy->getPointeeType();
7962 if (TempFromTy->isIncompleteType()) {
7963 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7964 << (unsigned) FnKind << FnDesc
7965 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7966 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007967 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00007968 return;
7969 }
7970
Douglas Gregor85789812010-06-30 23:01:39 +00007971 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007972 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007973 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7974 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7975 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7976 FromPtrTy->getPointeeType()) &&
7977 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7978 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007979 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007980 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007981 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007982 }
7983 } else if (const ObjCObjectPointerType *FromPtrTy
7984 = FromTy->getAs<ObjCObjectPointerType>()) {
7985 if (const ObjCObjectPointerType *ToPtrTy
7986 = ToTy->getAs<ObjCObjectPointerType>())
7987 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7988 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7989 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7990 FromPtrTy->getPointeeType()) &&
7991 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007992 BaseToDerivedConversion = 2;
7993 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7994 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7995 !FromTy->isIncompleteType() &&
7996 !ToRefTy->getPointeeType()->isIncompleteType() &&
7997 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7998 BaseToDerivedConversion = 3;
7999 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008000
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008001 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008002 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008003 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008004 << (unsigned) FnKind << FnDesc
8005 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008006 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008007 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008008 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008009 return;
8010 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008011
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008012 if (isa<ObjCObjectPointerType>(CFromTy) &&
8013 isa<PointerType>(CToTy)) {
8014 Qualifiers FromQs = CFromTy.getQualifiers();
8015 Qualifiers ToQs = CToTy.getQualifiers();
8016 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8017 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8018 << (unsigned) FnKind << FnDesc
8019 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8020 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8021 MaybeEmitInheritedConstructorNote(S, Fn);
8022 return;
8023 }
8024 }
8025
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008026 // Emit the generic diagnostic and, optionally, add the hints to it.
8027 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8028 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008029 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008030 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8031 << (unsigned) (Cand->Fix.Kind);
8032
8033 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008034 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8035 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008036 FDiag << *HI;
8037 S.Diag(Fn->getLocation(), FDiag);
8038
Sebastian Redlf677ea32011-02-05 19:23:19 +00008039 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008040}
8041
8042void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8043 unsigned NumFormalArgs) {
8044 // TODO: treat calls to a missing default constructor as a special case
8045
8046 FunctionDecl *Fn = Cand->Function;
8047 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8048
8049 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008050
Douglas Gregor439d3c32011-05-05 00:13:13 +00008051 // With invalid overloaded operators, it's possible that we think we
8052 // have an arity mismatch when it fact it looks like we have the
8053 // right number of arguments, because only overloaded operators have
8054 // the weird behavior of overloading member and non-member functions.
8055 // Just don't report anything.
8056 if (Fn->isInvalidDecl() &&
8057 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8058 return;
8059
John McCalladbb8f82010-01-13 09:16:55 +00008060 // at least / at most / exactly
8061 unsigned mode, modeCount;
8062 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008063 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8064 (Cand->FailureKind == ovl_fail_bad_deduction &&
8065 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008066 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008067 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008068 mode = 0; // "at least"
8069 else
8070 mode = 2; // "exactly"
8071 modeCount = MinParams;
8072 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008073 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8074 (Cand->FailureKind == ovl_fail_bad_deduction &&
8075 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008076 if (MinParams != FnTy->getNumArgs())
8077 mode = 1; // "at most"
8078 else
8079 mode = 2; // "exactly"
8080 modeCount = FnTy->getNumArgs();
8081 }
8082
8083 std::string Description;
8084 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8085
8086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008087 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00008088 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008089 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008090}
8091
John McCall342fec42010-02-01 18:53:26 +00008092/// Diagnose a failed template-argument deduction.
8093void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008094 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008095 FunctionDecl *Fn = Cand->Function; // pattern
8096
Douglas Gregora9333192010-05-08 17:41:32 +00008097 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008098 NamedDecl *ParamD;
8099 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8100 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8101 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008102 switch (Cand->DeductionFailure.Result) {
8103 case Sema::TDK_Success:
8104 llvm_unreachable("TDK_success while diagnosing bad deduction");
8105
8106 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008107 assert(ParamD && "no parameter found for incomplete deduction result");
8108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8109 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008110 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008111 return;
8112 }
8113
John McCall57e97782010-08-05 09:05:08 +00008114 case Sema::TDK_Underqualified: {
8115 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8116 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8117
8118 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8119
8120 // Param will have been canonicalized, but it should just be a
8121 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008122 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008123 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008124 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008125 assert(S.Context.hasSameType(Param, NonCanonParam));
8126
8127 // Arg has also been canonicalized, but there's nothing we can do
8128 // about that. It also doesn't matter as much, because it won't
8129 // have any template parameters in it (because deduction isn't
8130 // done on dependent types).
8131 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8132
8133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8134 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008135 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008136 return;
8137 }
8138
8139 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008140 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008141 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008142 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008143 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008144 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008145 which = 1;
8146 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008147 which = 2;
8148 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008149
Douglas Gregora9333192010-05-08 17:41:32 +00008150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008151 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008152 << *Cand->DeductionFailure.getFirstArg()
8153 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008154 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008155 return;
8156 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008157
Douglas Gregorf1a84452010-05-08 19:15:54 +00008158 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008159 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008160 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008161 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008162 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8163 << ParamD->getDeclName();
8164 else {
8165 int index = 0;
8166 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8167 index = TTP->getIndex();
8168 else if (NonTypeTemplateParmDecl *NTTP
8169 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8170 index = NTTP->getIndex();
8171 else
8172 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008173 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008174 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8175 << (index + 1);
8176 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008177 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008178 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008179
Douglas Gregora18592e2010-05-08 18:13:28 +00008180 case Sema::TDK_TooManyArguments:
8181 case Sema::TDK_TooFewArguments:
8182 DiagnoseArityMismatch(S, Cand, NumArgs);
8183 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008184
8185 case Sema::TDK_InstantiationDepth:
8186 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008187 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008188 return;
8189
8190 case Sema::TDK_SubstitutionFailure: {
8191 std::string ArgString;
8192 if (TemplateArgumentList *Args
8193 = Cand->DeductionFailure.getTemplateArgumentList())
8194 ArgString = S.getTemplateArgumentBindingsText(
8195 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
8196 *Args);
8197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
8198 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008199 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008200 return;
8201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008202
John McCall342fec42010-02-01 18:53:26 +00008203 // TODO: diagnose these individually, then kill off
8204 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008205 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008206 case Sema::TDK_FailedOverloadResolution:
8207 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008208 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008209 return;
8210 }
8211}
8212
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008213/// CUDA: diagnose an invalid call across targets.
8214void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8215 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8216 FunctionDecl *Callee = Cand->Function;
8217
8218 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8219 CalleeTarget = S.IdentifyCUDATarget(Callee);
8220
8221 std::string FnDesc;
8222 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8223
8224 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8225 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8226}
8227
John McCall342fec42010-02-01 18:53:26 +00008228/// Generates a 'note' diagnostic for an overload candidate. We've
8229/// already generated a primary error at the call site.
8230///
8231/// It really does need to be a single diagnostic with its caret
8232/// pointed at the candidate declaration. Yes, this creates some
8233/// major challenges of technical writing. Yes, this makes pointing
8234/// out problems with specific arguments quite awkward. It's still
8235/// better than generating twenty screens of text for every failed
8236/// overload.
8237///
8238/// It would be great to be able to express per-candidate problems
8239/// more richly for those diagnostic clients that cared, but we'd
8240/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008241void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008242 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008243 FunctionDecl *Fn = Cand->Function;
8244
John McCall81201622010-01-08 04:41:39 +00008245 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008246 if (Cand->Viable && (Fn->isDeleted() ||
8247 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008248 std::string FnDesc;
8249 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008250
8251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008252 << FnKind << FnDesc
8253 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008254 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008255 return;
John McCall81201622010-01-08 04:41:39 +00008256 }
8257
John McCall220ccbf2010-01-13 00:25:19 +00008258 // We don't really have anything else to say about viable candidates.
8259 if (Cand->Viable) {
8260 S.NoteOverloadCandidate(Fn);
8261 return;
8262 }
John McCall1d318332010-01-12 00:44:57 +00008263
John McCalladbb8f82010-01-13 09:16:55 +00008264 switch (Cand->FailureKind) {
8265 case ovl_fail_too_many_arguments:
8266 case ovl_fail_too_few_arguments:
8267 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008268
John McCalladbb8f82010-01-13 09:16:55 +00008269 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008270 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008271
John McCall717e8912010-01-23 05:17:32 +00008272 case ovl_fail_trivial_conversion:
8273 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008274 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008275 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008276
John McCallb1bdc622010-02-25 01:37:24 +00008277 case ovl_fail_bad_conversion: {
8278 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008279 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008280 if (Cand->Conversions[I].isBad())
8281 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008282
John McCalladbb8f82010-01-13 09:16:55 +00008283 // FIXME: this currently happens when we're called from SemaInit
8284 // when user-conversion overload fails. Figure out how to handle
8285 // those conditions and diagnose them well.
8286 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008287 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008288
8289 case ovl_fail_bad_target:
8290 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008291 }
John McCalla1d7d622010-01-08 00:58:21 +00008292}
8293
8294void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8295 // Desugar the type of the surrogate down to a function type,
8296 // retaining as many typedefs as possible while still showing
8297 // the function type (and, therefore, its parameter types).
8298 QualType FnType = Cand->Surrogate->getConversionType();
8299 bool isLValueReference = false;
8300 bool isRValueReference = false;
8301 bool isPointer = false;
8302 if (const LValueReferenceType *FnTypeRef =
8303 FnType->getAs<LValueReferenceType>()) {
8304 FnType = FnTypeRef->getPointeeType();
8305 isLValueReference = true;
8306 } else if (const RValueReferenceType *FnTypeRef =
8307 FnType->getAs<RValueReferenceType>()) {
8308 FnType = FnTypeRef->getPointeeType();
8309 isRValueReference = true;
8310 }
8311 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8312 FnType = FnTypePtr->getPointeeType();
8313 isPointer = true;
8314 }
8315 // Desugar down to a function type.
8316 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8317 // Reconstruct the pointer/reference as appropriate.
8318 if (isPointer) FnType = S.Context.getPointerType(FnType);
8319 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8320 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8321
8322 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8323 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008324 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008325}
8326
8327void NoteBuiltinOperatorCandidate(Sema &S,
8328 const char *Opc,
8329 SourceLocation OpLoc,
8330 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008331 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008332 std::string TypeStr("operator");
8333 TypeStr += Opc;
8334 TypeStr += "(";
8335 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008336 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008337 TypeStr += ")";
8338 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8339 } else {
8340 TypeStr += ", ";
8341 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8342 TypeStr += ")";
8343 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8344 }
8345}
8346
8347void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8348 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008349 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008350 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8351 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008352 if (ICS.isBad()) break; // all meaningless after first invalid
8353 if (!ICS.isAmbiguous()) continue;
8354
John McCall120d63c2010-08-24 20:38:10 +00008355 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008356 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008357 }
8358}
8359
John McCall1b77e732010-01-15 23:32:50 +00008360SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8361 if (Cand->Function)
8362 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008363 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008364 return Cand->Surrogate->getLocation();
8365 return SourceLocation();
8366}
8367
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008368static unsigned
8369RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008370 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008371 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008372 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008373
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008374 case Sema::TDK_Incomplete:
8375 return 1;
8376
8377 case Sema::TDK_Underqualified:
8378 case Sema::TDK_Inconsistent:
8379 return 2;
8380
8381 case Sema::TDK_SubstitutionFailure:
8382 case Sema::TDK_NonDeducedMismatch:
8383 return 3;
8384
8385 case Sema::TDK_InstantiationDepth:
8386 case Sema::TDK_FailedOverloadResolution:
8387 return 4;
8388
8389 case Sema::TDK_InvalidExplicitArguments:
8390 return 5;
8391
8392 case Sema::TDK_TooManyArguments:
8393 case Sema::TDK_TooFewArguments:
8394 return 6;
8395 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008396 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008397}
8398
John McCallbf65c0b2010-01-12 00:48:53 +00008399struct CompareOverloadCandidatesForDisplay {
8400 Sema &S;
8401 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008402
8403 bool operator()(const OverloadCandidate *L,
8404 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008405 // Fast-path this check.
8406 if (L == R) return false;
8407
John McCall81201622010-01-08 04:41:39 +00008408 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008409 if (L->Viable) {
8410 if (!R->Viable) return true;
8411
8412 // TODO: introduce a tri-valued comparison for overload
8413 // candidates. Would be more worthwhile if we had a sort
8414 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008415 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8416 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008417 } else if (R->Viable)
8418 return false;
John McCall81201622010-01-08 04:41:39 +00008419
John McCall1b77e732010-01-15 23:32:50 +00008420 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008421
John McCall1b77e732010-01-15 23:32:50 +00008422 // Criteria by which we can sort non-viable candidates:
8423 if (!L->Viable) {
8424 // 1. Arity mismatches come after other candidates.
8425 if (L->FailureKind == ovl_fail_too_many_arguments ||
8426 L->FailureKind == ovl_fail_too_few_arguments)
8427 return false;
8428 if (R->FailureKind == ovl_fail_too_many_arguments ||
8429 R->FailureKind == ovl_fail_too_few_arguments)
8430 return true;
John McCall81201622010-01-08 04:41:39 +00008431
John McCall717e8912010-01-23 05:17:32 +00008432 // 2. Bad conversions come first and are ordered by the number
8433 // of bad conversions and quality of good conversions.
8434 if (L->FailureKind == ovl_fail_bad_conversion) {
8435 if (R->FailureKind != ovl_fail_bad_conversion)
8436 return true;
8437
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008438 // The conversion that can be fixed with a smaller number of changes,
8439 // comes first.
8440 unsigned numLFixes = L->Fix.NumConversionsFixed;
8441 unsigned numRFixes = R->Fix.NumConversionsFixed;
8442 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8443 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008444 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008445 if (numLFixes < numRFixes)
8446 return true;
8447 else
8448 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008449 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008450
John McCall717e8912010-01-23 05:17:32 +00008451 // If there's any ordering between the defined conversions...
8452 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008453 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008454
8455 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008456 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008457 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008458 switch (CompareImplicitConversionSequences(S,
8459 L->Conversions[I],
8460 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008461 case ImplicitConversionSequence::Better:
8462 leftBetter++;
8463 break;
8464
8465 case ImplicitConversionSequence::Worse:
8466 leftBetter--;
8467 break;
8468
8469 case ImplicitConversionSequence::Indistinguishable:
8470 break;
8471 }
8472 }
8473 if (leftBetter > 0) return true;
8474 if (leftBetter < 0) return false;
8475
8476 } else if (R->FailureKind == ovl_fail_bad_conversion)
8477 return false;
8478
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008479 if (L->FailureKind == ovl_fail_bad_deduction) {
8480 if (R->FailureKind != ovl_fail_bad_deduction)
8481 return true;
8482
8483 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8484 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008485 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008486 } else if (R->FailureKind == ovl_fail_bad_deduction)
8487 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008488
John McCall1b77e732010-01-15 23:32:50 +00008489 // TODO: others?
8490 }
8491
8492 // Sort everything else by location.
8493 SourceLocation LLoc = GetLocationForCandidate(L);
8494 SourceLocation RLoc = GetLocationForCandidate(R);
8495
8496 // Put candidates without locations (e.g. builtins) at the end.
8497 if (LLoc.isInvalid()) return false;
8498 if (RLoc.isInvalid()) return true;
8499
8500 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008501 }
8502};
8503
John McCall717e8912010-01-23 05:17:32 +00008504/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008505/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008506void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008507 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008508 assert(!Cand->Viable);
8509
8510 // Don't do anything on failures other than bad conversion.
8511 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8512
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008513 // We only want the FixIts if all the arguments can be corrected.
8514 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008515 // Use a implicit copy initialization to check conversion fixes.
8516 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008517
John McCall717e8912010-01-23 05:17:32 +00008518 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008519 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008520 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008521 while (true) {
8522 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8523 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008524 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008525 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008526 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008527 }
John McCall717e8912010-01-23 05:17:32 +00008528 }
8529
8530 if (ConvIdx == ConvCount)
8531 return;
8532
John McCallb1bdc622010-02-25 01:37:24 +00008533 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8534 "remaining conversion is initialized?");
8535
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008536 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008537 // operation somehow.
8538 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008539
8540 const FunctionProtoType* Proto;
8541 unsigned ArgIdx = ConvIdx;
8542
8543 if (Cand->IsSurrogate) {
8544 QualType ConvType
8545 = Cand->Surrogate->getConversionType().getNonReferenceType();
8546 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8547 ConvType = ConvPtrType->getPointeeType();
8548 Proto = ConvType->getAs<FunctionProtoType>();
8549 ArgIdx--;
8550 } else if (Cand->Function) {
8551 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8552 if (isa<CXXMethodDecl>(Cand->Function) &&
8553 !isa<CXXConstructorDecl>(Cand->Function))
8554 ArgIdx--;
8555 } else {
8556 // Builtin binary operator with a bad first conversion.
8557 assert(ConvCount <= 3);
8558 for (; ConvIdx != ConvCount; ++ConvIdx)
8559 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008560 = TryCopyInitialization(S, Args[ConvIdx],
8561 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008562 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008563 /*InOverloadResolution*/ true,
8564 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008565 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008566 return;
8567 }
8568
8569 // Fill in the rest of the conversions.
8570 unsigned NumArgsInProto = Proto->getNumArgs();
8571 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008572 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008573 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008574 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008575 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008576 /*InOverloadResolution=*/true,
8577 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008578 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008579 // Store the FixIt in the candidate if it exists.
8580 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008581 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008582 }
John McCall717e8912010-01-23 05:17:32 +00008583 else
8584 Cand->Conversions[ConvIdx].setEllipsis();
8585 }
8586}
8587
John McCalla1d7d622010-01-08 00:58:21 +00008588} // end anonymous namespace
8589
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008590/// PrintOverloadCandidates - When overload resolution fails, prints
8591/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008592/// set.
John McCall120d63c2010-08-24 20:38:10 +00008593void OverloadCandidateSet::NoteCandidates(Sema &S,
8594 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008595 llvm::ArrayRef<Expr *> Args,
John McCall120d63c2010-08-24 20:38:10 +00008596 const char *Opc,
8597 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008598 // Sort the candidates by viability and position. Sorting directly would
8599 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008600 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008601 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8602 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008603 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008604 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008605 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008606 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008607 if (Cand->Function || Cand->IsSurrogate)
8608 Cands.push_back(Cand);
8609 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8610 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008611 }
8612 }
8613
John McCallbf65c0b2010-01-12 00:48:53 +00008614 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008615 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008616
John McCall1d318332010-01-12 00:44:57 +00008617 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008618
Chris Lattner5f9e2722011-07-23 10:55:15 +00008619 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008620 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8621 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008622 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008623 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8624 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008625
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008626 // Set an arbitrary limit on the number of candidate functions we'll spam
8627 // the user with. FIXME: This limit should depend on details of the
8628 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008629 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008630 break;
8631 }
8632 ++CandsShown;
8633
John McCalla1d7d622010-01-08 00:58:21 +00008634 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008635 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008636 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008637 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008638 else {
8639 assert(Cand->Viable &&
8640 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008641 // Generally we only see ambiguities including viable builtin
8642 // operators if overload resolution got screwed up by an
8643 // ambiguous user-defined conversion.
8644 //
8645 // FIXME: It's quite possible for different conversions to see
8646 // different ambiguities, though.
8647 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008648 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008649 ReportedAmbiguousConversions = true;
8650 }
John McCalla1d7d622010-01-08 00:58:21 +00008651
John McCall1d318332010-01-12 00:44:57 +00008652 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008653 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008654 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008655 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008656
8657 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008658 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008659}
8660
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008661// [PossiblyAFunctionType] --> [Return]
8662// NonFunctionType --> NonFunctionType
8663// R (A) --> R(A)
8664// R (*)(A) --> R (A)
8665// R (&)(A) --> R (A)
8666// R (S::*)(A) --> R (A)
8667QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8668 QualType Ret = PossiblyAFunctionType;
8669 if (const PointerType *ToTypePtr =
8670 PossiblyAFunctionType->getAs<PointerType>())
8671 Ret = ToTypePtr->getPointeeType();
8672 else if (const ReferenceType *ToTypeRef =
8673 PossiblyAFunctionType->getAs<ReferenceType>())
8674 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008675 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008676 PossiblyAFunctionType->getAs<MemberPointerType>())
8677 Ret = MemTypePtr->getPointeeType();
8678 Ret =
8679 Context.getCanonicalType(Ret).getUnqualifiedType();
8680 return Ret;
8681}
Douglas Gregor904eed32008-11-10 20:40:00 +00008682
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008683// A helper class to help with address of function resolution
8684// - allows us to avoid passing around all those ugly parameters
8685class AddressOfFunctionResolver
8686{
8687 Sema& S;
8688 Expr* SourceExpr;
8689 const QualType& TargetType;
8690 QualType TargetFunctionType; // Extracted function type from target type
8691
8692 bool Complain;
8693 //DeclAccessPair& ResultFunctionAccessPair;
8694 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008695
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008696 bool TargetTypeIsNonStaticMemberFunction;
8697 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008698
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008699 OverloadExpr::FindResult OvlExprInfo;
8700 OverloadExpr *OvlExpr;
8701 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008702 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008703
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008704public:
8705 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8706 const QualType& TargetType, bool Complain)
8707 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8708 Complain(Complain), Context(S.getASTContext()),
8709 TargetTypeIsNonStaticMemberFunction(
8710 !!TargetType->getAs<MemberPointerType>()),
8711 FoundNonTemplateFunction(false),
8712 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8713 OvlExpr(OvlExprInfo.Expression)
8714 {
8715 ExtractUnqualifiedFunctionTypeFromTargetType();
8716
8717 if (!TargetFunctionType->isFunctionType()) {
8718 if (OvlExpr->hasExplicitTemplateArgs()) {
8719 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008720 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008721 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008722
8723 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8724 if (!Method->isStatic()) {
8725 // If the target type is a non-function type and the function
8726 // found is a non-static member function, pretend as if that was
8727 // the target, it's the only possible type to end up with.
8728 TargetTypeIsNonStaticMemberFunction = true;
8729
8730 // And skip adding the function if its not in the proper form.
8731 // We'll diagnose this due to an empty set of functions.
8732 if (!OvlExprInfo.HasFormOfMemberPointer)
8733 return;
8734 }
8735 }
8736
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008737 Matches.push_back(std::make_pair(dap,Fn));
8738 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008739 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008740 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008741 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008742
8743 if (OvlExpr->hasExplicitTemplateArgs())
8744 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008745
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008746 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8747 // C++ [over.over]p4:
8748 // If more than one function is selected, [...]
8749 if (Matches.size() > 1) {
8750 if (FoundNonTemplateFunction)
8751 EliminateAllTemplateMatches();
8752 else
8753 EliminateAllExceptMostSpecializedTemplate();
8754 }
8755 }
8756 }
8757
8758private:
8759 bool isTargetTypeAFunction() const {
8760 return TargetFunctionType->isFunctionType();
8761 }
8762
8763 // [ToType] [Return]
8764
8765 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8766 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8767 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8768 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8769 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8770 }
8771
8772 // return true if any matching specializations were found
8773 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8774 const DeclAccessPair& CurAccessFunPair) {
8775 if (CXXMethodDecl *Method
8776 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8777 // Skip non-static function templates when converting to pointer, and
8778 // static when converting to member pointer.
8779 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8780 return false;
8781 }
8782 else if (TargetTypeIsNonStaticMemberFunction)
8783 return false;
8784
8785 // C++ [over.over]p2:
8786 // If the name is a function template, template argument deduction is
8787 // done (14.8.2.2), and if the argument deduction succeeds, the
8788 // resulting template argument list is used to generate a single
8789 // function template specialization, which is added to the set of
8790 // overloaded functions considered.
8791 FunctionDecl *Specialization = 0;
8792 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8793 if (Sema::TemplateDeductionResult Result
8794 = S.DeduceTemplateArguments(FunctionTemplate,
8795 &OvlExplicitTemplateArgs,
8796 TargetFunctionType, Specialization,
8797 Info)) {
8798 // FIXME: make a note of the failed deduction for diagnostics.
8799 (void)Result;
8800 return false;
8801 }
8802
8803 // Template argument deduction ensures that we have an exact match.
8804 // This function template specicalization works.
8805 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8806 assert(TargetFunctionType
8807 == Context.getCanonicalType(Specialization->getType()));
8808 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8809 return true;
8810 }
8811
8812 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8813 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008814 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008815 // Skip non-static functions when converting to pointer, and static
8816 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008817 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8818 return false;
8819 }
8820 else if (TargetTypeIsNonStaticMemberFunction)
8821 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008822
Chandler Carruthbd647292009-12-29 06:17:27 +00008823 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00008824 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008825 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8826 if (S.CheckCUDATarget(Caller, FunDecl))
8827 return false;
8828
Douglas Gregor43c79c22009-12-09 00:47:37 +00008829 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008830 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8831 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008832 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8833 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008834 Matches.push_back(std::make_pair(CurAccessFunPair,
8835 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008836 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008837 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008838 }
Mike Stump1eb44332009-09-09 15:08:12 +00008839 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008840
8841 return false;
8842 }
8843
8844 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8845 bool Ret = false;
8846
8847 // If the overload expression doesn't have the form of a pointer to
8848 // member, don't try to convert it to a pointer-to-member type.
8849 if (IsInvalidFormOfPointerToMemberFunction())
8850 return false;
8851
8852 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8853 E = OvlExpr->decls_end();
8854 I != E; ++I) {
8855 // Look through any using declarations to find the underlying function.
8856 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8857
8858 // C++ [over.over]p3:
8859 // Non-member functions and static member functions match
8860 // targets of type "pointer-to-function" or "reference-to-function."
8861 // Nonstatic member functions match targets of
8862 // type "pointer-to-member-function."
8863 // Note that according to DR 247, the containing class does not matter.
8864 if (FunctionTemplateDecl *FunctionTemplate
8865 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8866 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8867 Ret = true;
8868 }
8869 // If we have explicit template arguments supplied, skip non-templates.
8870 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8871 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8872 Ret = true;
8873 }
8874 assert(Ret || Matches.empty());
8875 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008876 }
8877
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008878 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008879 // [...] and any given function template specialization F1 is
8880 // eliminated if the set contains a second function template
8881 // specialization whose function template is more specialized
8882 // than the function template of F1 according to the partial
8883 // ordering rules of 14.5.5.2.
8884
8885 // The algorithm specified above is quadratic. We instead use a
8886 // two-pass algorithm (similar to the one used to identify the
8887 // best viable function in an overload set) that identifies the
8888 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008889
8890 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8891 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8892 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008893
John McCallc373d482010-01-27 01:50:18 +00008894 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008895 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8896 TPOC_Other, 0, SourceExpr->getLocStart(),
8897 S.PDiag(),
8898 S.PDiag(diag::err_addr_ovl_ambiguous)
8899 << Matches[0].second->getDeclName(),
8900 S.PDiag(diag::note_ovl_candidate)
8901 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008902 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008903
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008904 if (Result != MatchesCopy.end()) {
8905 // Make it the first and only element
8906 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8907 Matches[0].second = cast<FunctionDecl>(*Result);
8908 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008909 }
8910 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008911
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008912 void EliminateAllTemplateMatches() {
8913 // [...] any function template specializations in the set are
8914 // eliminated if the set also contains a non-template function, [...]
8915 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8916 if (Matches[I].second->getPrimaryTemplate() == 0)
8917 ++I;
8918 else {
8919 Matches[I] = Matches[--N];
8920 Matches.set_size(N);
8921 }
8922 }
8923 }
8924
8925public:
8926 void ComplainNoMatchesFound() const {
8927 assert(Matches.empty());
8928 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8929 << OvlExpr->getName() << TargetFunctionType
8930 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008931 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008932 }
8933
8934 bool IsInvalidFormOfPointerToMemberFunction() const {
8935 return TargetTypeIsNonStaticMemberFunction &&
8936 !OvlExprInfo.HasFormOfMemberPointer;
8937 }
8938
8939 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8940 // TODO: Should we condition this on whether any functions might
8941 // have matched, or is it more appropriate to do that in callers?
8942 // TODO: a fixit wouldn't hurt.
8943 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8944 << TargetType << OvlExpr->getSourceRange();
8945 }
8946
8947 void ComplainOfInvalidConversion() const {
8948 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8949 << OvlExpr->getName() << TargetType;
8950 }
8951
8952 void ComplainMultipleMatchesFound() const {
8953 assert(Matches.size() > 1);
8954 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8955 << OvlExpr->getName()
8956 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008957 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008958 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008959
8960 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8961
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008962 int getNumMatches() const { return Matches.size(); }
8963
8964 FunctionDecl* getMatchingFunctionDecl() const {
8965 if (Matches.size() != 1) return 0;
8966 return Matches[0].second;
8967 }
8968
8969 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8970 if (Matches.size() != 1) return 0;
8971 return &Matches[0].first;
8972 }
8973};
8974
8975/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8976/// an overloaded function (C++ [over.over]), where @p From is an
8977/// expression with overloaded function type and @p ToType is the type
8978/// we're trying to resolve to. For example:
8979///
8980/// @code
8981/// int f(double);
8982/// int f(int);
8983///
8984/// int (*pfd)(double) = f; // selects f(double)
8985/// @endcode
8986///
8987/// This routine returns the resulting FunctionDecl if it could be
8988/// resolved, and NULL otherwise. When @p Complain is true, this
8989/// routine will emit diagnostics if there is an error.
8990FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008991Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8992 QualType TargetType,
8993 bool Complain,
8994 DeclAccessPair &FoundResult,
8995 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008996 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008997
8998 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8999 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009000 int NumMatches = Resolver.getNumMatches();
9001 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009002 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009003 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9004 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9005 else
9006 Resolver.ComplainNoMatchesFound();
9007 }
9008 else if (NumMatches > 1 && Complain)
9009 Resolver.ComplainMultipleMatchesFound();
9010 else if (NumMatches == 1) {
9011 Fn = Resolver.getMatchingFunctionDecl();
9012 assert(Fn);
9013 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Eli Friedman5f2987c2012-02-02 03:46:19 +00009014 MarkFunctionReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00009015 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009016 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009017 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009018
9019 if (pHadMultipleCandidates)
9020 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009021 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009022}
9023
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009024/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009025/// resolve that overloaded function expression down to a single function.
9026///
9027/// This routine can only resolve template-ids that refer to a single function
9028/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009029/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009030/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009031FunctionDecl *
9032Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9033 bool Complain,
9034 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009035 // C++ [over.over]p1:
9036 // [...] [Note: any redundant set of parentheses surrounding the
9037 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009038 // C++ [over.over]p1:
9039 // [...] The overloaded function name can be preceded by the &
9040 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009041
Douglas Gregor4b52e252009-12-21 23:17:24 +00009042 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009043 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009044 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009045
9046 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009047 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009048
Douglas Gregor4b52e252009-12-21 23:17:24 +00009049 // Look through all of the overloaded functions, searching for one
9050 // whose type matches exactly.
9051 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009052 for (UnresolvedSetIterator I = ovl->decls_begin(),
9053 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009054 // C++0x [temp.arg.explicit]p3:
9055 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009056 // where deduction is not done, if a template argument list is
9057 // specified and it, along with any default template arguments,
9058 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009059 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009060 FunctionTemplateDecl *FunctionTemplate
9061 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009062
Douglas Gregor4b52e252009-12-21 23:17:24 +00009063 // C++ [over.over]p2:
9064 // If the name is a function template, template argument deduction is
9065 // done (14.8.2.2), and if the argument deduction succeeds, the
9066 // resulting template argument list is used to generate a single
9067 // function template specialization, which is added to the set of
9068 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009069 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00009070 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009071 if (TemplateDeductionResult Result
9072 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9073 Specialization, Info)) {
9074 // FIXME: make a note of the failed deduction for diagnostics.
9075 (void)Result;
9076 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009077 }
9078
John McCall864c0412011-04-26 20:42:42 +00009079 assert(Specialization && "no specialization and no error?");
9080
Douglas Gregor4b52e252009-12-21 23:17:24 +00009081 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009082 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009083 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009084 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9085 << ovl->getName();
9086 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009087 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009088 return 0;
John McCall864c0412011-04-26 20:42:42 +00009089 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009090
John McCall864c0412011-04-26 20:42:42 +00009091 Matched = Specialization;
9092 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009093 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009094
Douglas Gregor4b52e252009-12-21 23:17:24 +00009095 return Matched;
9096}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009097
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009098
9099
9100
John McCall6dbba4f2011-10-11 23:14:30 +00009101// Resolve and fix an overloaded expression that can be resolved
9102// because it identifies a single function template specialization.
9103//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009104// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009105//
9106// Return true if it was logically possible to so resolve the
9107// expression, regardless of whether or not it succeeded. Always
9108// returns true if 'complain' is set.
9109bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9110 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9111 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009112 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009113 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009114 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009115
John McCall6dbba4f2011-10-11 23:14:30 +00009116 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009117
John McCall864c0412011-04-26 20:42:42 +00009118 DeclAccessPair found;
9119 ExprResult SingleFunctionExpression;
9120 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9121 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009122 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009123 SrcExpr = ExprError();
9124 return true;
9125 }
John McCall864c0412011-04-26 20:42:42 +00009126
9127 // It is only correct to resolve to an instance method if we're
9128 // resolving a form that's permitted to be a pointer to member.
9129 // Otherwise we'll end up making a bound member expression, which
9130 // is illegal in all the contexts we resolve like this.
9131 if (!ovl.HasFormOfMemberPointer &&
9132 isa<CXXMethodDecl>(fn) &&
9133 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009134 if (!complain) return false;
9135
9136 Diag(ovl.Expression->getExprLoc(),
9137 diag::err_bound_member_function)
9138 << 0 << ovl.Expression->getSourceRange();
9139
9140 // TODO: I believe we only end up here if there's a mix of
9141 // static and non-static candidates (otherwise the expression
9142 // would have 'bound member' type, not 'overload' type).
9143 // Ideally we would note which candidate was chosen and why
9144 // the static candidates were rejected.
9145 SrcExpr = ExprError();
9146 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009147 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009148
John McCall864c0412011-04-26 20:42:42 +00009149 // Fix the expresion to refer to 'fn'.
9150 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009151 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009152
9153 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009154 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009155 SingleFunctionExpression =
9156 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009157 if (SingleFunctionExpression.isInvalid()) {
9158 SrcExpr = ExprError();
9159 return true;
9160 }
9161 }
John McCall864c0412011-04-26 20:42:42 +00009162 }
9163
9164 if (!SingleFunctionExpression.isUsable()) {
9165 if (complain) {
9166 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9167 << ovl.Expression->getName()
9168 << DestTypeForComplaining
9169 << OpRangeForComplaining
9170 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009171 NoteAllOverloadCandidates(SrcExpr.get());
9172
9173 SrcExpr = ExprError();
9174 return true;
9175 }
9176
9177 return false;
John McCall864c0412011-04-26 20:42:42 +00009178 }
9179
John McCall6dbba4f2011-10-11 23:14:30 +00009180 SrcExpr = SingleFunctionExpression;
9181 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009182}
9183
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009184/// \brief Add a single candidate to the overload set.
9185static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009186 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009187 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009188 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009189 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009190 bool PartialOverloading,
9191 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009192 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009193 if (isa<UsingShadowDecl>(Callee))
9194 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9195
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009196 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009197 if (ExplicitTemplateArgs) {
9198 assert(!KnownValid && "Explicit template arguments?");
9199 return;
9200 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009201 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9202 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009203 return;
John McCallba135432009-11-21 08:51:07 +00009204 }
9205
9206 if (FunctionTemplateDecl *FuncTemplate
9207 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009208 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009209 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009210 return;
9211 }
9212
Richard Smith2ced0442011-06-26 22:19:54 +00009213 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009214}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009215
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009216/// \brief Add the overload candidates named by callee and/or found by argument
9217/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009218void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009219 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009220 OverloadCandidateSet &CandidateSet,
9221 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009222
9223#ifndef NDEBUG
9224 // Verify that ArgumentDependentLookup is consistent with the rules
9225 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009226 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009227 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9228 // and let Y be the lookup set produced by argument dependent
9229 // lookup (defined as follows). If X contains
9230 //
9231 // -- a declaration of a class member, or
9232 //
9233 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009234 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009235 //
9236 // -- a declaration that is neither a function or a function
9237 // template
9238 //
9239 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009240
John McCall3b4294e2009-12-16 12:17:52 +00009241 if (ULE->requiresADL()) {
9242 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9243 E = ULE->decls_end(); I != E; ++I) {
9244 assert(!(*I)->getDeclContext()->isRecord());
9245 assert(isa<UsingShadowDecl>(*I) ||
9246 !(*I)->getDeclContext()->isFunctionOrMethod());
9247 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009248 }
9249 }
9250#endif
9251
John McCall3b4294e2009-12-16 12:17:52 +00009252 // It would be nice to avoid this copy.
9253 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009254 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009255 if (ULE->hasExplicitTemplateArgs()) {
9256 ULE->copyTemplateArgumentsInto(TABuffer);
9257 ExplicitTemplateArgs = &TABuffer;
9258 }
9259
9260 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9261 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009262 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9263 CandidateSet, PartialOverloading,
9264 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009265
John McCall3b4294e2009-12-16 12:17:52 +00009266 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009267 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009268 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009269 Args, ExplicitTemplateArgs,
9270 CandidateSet, PartialOverloading,
Richard Smithad762fc2011-04-14 22:09:26 +00009271 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009272}
John McCall578b69b2009-12-16 08:11:27 +00009273
Richard Smithf50e88a2011-06-05 22:42:48 +00009274/// Attempt to recover from an ill-formed use of a non-dependent name in a
9275/// template, where the non-dependent name was declared after the template
9276/// was defined. This is common in code written for a compilers which do not
9277/// correctly implement two-stage name lookup.
9278///
9279/// Returns true if a viable candidate was found and a diagnostic was issued.
9280static bool
9281DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9282 const CXXScopeSpec &SS, LookupResult &R,
9283 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009284 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009285 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9286 return false;
9287
9288 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009289 if (DC->isTransparentContext())
9290 continue;
9291
Richard Smithf50e88a2011-06-05 22:42:48 +00009292 SemaRef.LookupQualifiedName(R, DC);
9293
9294 if (!R.empty()) {
9295 R.suppressDiagnostics();
9296
9297 if (isa<CXXRecordDecl>(DC)) {
9298 // Don't diagnose names we find in classes; we get much better
9299 // diagnostics for these from DiagnoseEmptyLookup.
9300 R.clear();
9301 return false;
9302 }
9303
9304 OverloadCandidateSet Candidates(FnLoc);
9305 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9306 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009307 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009308 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009309
9310 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009311 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009312 // No viable functions. Don't bother the user with notes for functions
9313 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009314 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009315 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009316 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009317
9318 // Find the namespaces where ADL would have looked, and suggest
9319 // declaring the function there instead.
9320 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9321 Sema::AssociatedClassSet AssociatedClasses;
Ahmed Charles13a140c2012-02-25 11:00:22 +00009322 SemaRef.FindAssociatedClassesAndNamespaces(Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009323 AssociatedNamespaces,
9324 AssociatedClasses);
9325 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00009326 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009327 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009328 for (Sema::AssociatedNamespaceSet::iterator
9329 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00009330 end = AssociatedNamespaces.end(); it != end; ++it) {
9331 if (!Std->Encloses(*it))
9332 SuggestedNamespaces.insert(*it);
9333 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00009334 } else {
9335 // Lacking the 'std::' namespace, use all of the associated namespaces.
9336 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00009337 }
9338
9339 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9340 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009341 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009342 SemaRef.Diag(Best->Function->getLocation(),
9343 diag::note_not_found_by_two_phase_lookup)
9344 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009345 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009346 SemaRef.Diag(Best->Function->getLocation(),
9347 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009348 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009349 } else {
9350 // FIXME: It would be useful to list the associated namespaces here,
9351 // but the diagnostics infrastructure doesn't provide a way to produce
9352 // a localized representation of a list of items.
9353 SemaRef.Diag(Best->Function->getLocation(),
9354 diag::note_not_found_by_two_phase_lookup)
9355 << R.getLookupName() << 2;
9356 }
9357
9358 // Try to recover by calling this function.
9359 return true;
9360 }
9361
9362 R.clear();
9363 }
9364
9365 return false;
9366}
9367
9368/// Attempt to recover from ill-formed use of a non-dependent operator in a
9369/// template, where the non-dependent operator was declared after the template
9370/// was defined.
9371///
9372/// Returns true if a viable candidate was found and a diagnostic was issued.
9373static bool
9374DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9375 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009376 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009377 DeclarationName OpName =
9378 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9379 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9380 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009381 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009382}
9383
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009384namespace {
9385// Callback to limit the allowed keywords and to only accept typo corrections
9386// that are keywords or whose decls refer to functions (or template functions)
9387// that accept the given number of arguments.
9388class RecoveryCallCCC : public CorrectionCandidateCallback {
9389 public:
9390 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9391 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009392 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009393 WantRemainingKeywords = false;
9394 }
9395
9396 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9397 if (!candidate.getCorrectionDecl())
9398 return candidate.isKeyword();
9399
9400 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9401 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9402 FunctionDecl *FD = 0;
9403 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9404 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9405 FD = FTD->getTemplatedDecl();
9406 if (!HasExplicitTemplateArgs && !FD) {
9407 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9408 // If the Decl is neither a function nor a template function,
9409 // determine if it is a pointer or reference to a function. If so,
9410 // check against the number of arguments expected for the pointee.
9411 QualType ValType = cast<ValueDecl>(ND)->getType();
9412 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9413 ValType = ValType->getPointeeType();
9414 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9415 if (FPT->getNumArgs() == NumArgs)
9416 return true;
9417 }
9418 }
9419 if (FD && FD->getNumParams() >= NumArgs &&
9420 FD->getMinRequiredArguments() <= NumArgs)
9421 return true;
9422 }
9423 return false;
9424 }
9425
9426 private:
9427 unsigned NumArgs;
9428 bool HasExplicitTemplateArgs;
9429};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009430
9431// Callback that effectively disabled typo correction
9432class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9433 public:
9434 NoTypoCorrectionCCC() {
9435 WantTypeSpecifiers = false;
9436 WantExpressionKeywords = false;
9437 WantCXXNamedCasts = false;
9438 WantRemainingKeywords = false;
9439 }
9440
9441 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9442 return false;
9443 }
9444};
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009445}
9446
John McCall578b69b2009-12-16 08:11:27 +00009447/// Attempts to recover from a call where no functions were found.
9448///
9449/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009450static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009451BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009452 UnresolvedLookupExpr *ULE,
9453 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009454 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009455 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009456 bool EmptyLookup, bool AllowTypoCorrection) {
John McCall578b69b2009-12-16 08:11:27 +00009457
9458 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009459 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009460 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009461
John McCall3b4294e2009-12-16 12:17:52 +00009462 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009463 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009464 if (ULE->hasExplicitTemplateArgs()) {
9465 ULE->copyTemplateArgumentsInto(TABuffer);
9466 ExplicitTemplateArgs = &TABuffer;
9467 }
9468
John McCall578b69b2009-12-16 08:11:27 +00009469 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9470 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009471 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009472 NoTypoCorrectionCCC RejectAll;
9473 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9474 (CorrectionCandidateCallback*)&Validator :
9475 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009476 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009477 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009478 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009479 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009480 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009481 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009482
John McCall3b4294e2009-12-16 12:17:52 +00009483 assert(!R.empty() && "lookup results empty despite recovery");
9484
9485 // Build an implicit member call if appropriate. Just drop the
9486 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009487 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009488 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009489 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9490 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009491 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009492 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009493 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009494 else
9495 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9496
9497 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009498 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009499
9500 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009501 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009502 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009503 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009504 MultiExprArg(Args.data(), Args.size()),
9505 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009506}
Douglas Gregord7a95972010-06-08 17:35:15 +00009507
Douglas Gregorf6b89692008-11-26 05:54:23 +00009508/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00009509/// (which eventually refers to the declaration Func) and the call
9510/// arguments Args/NumArgs, attempt to resolve the function call down
9511/// to a specific function. If overload resolution succeeds, returns
9512/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00009513/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00009514/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00009515ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009516Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00009517 SourceLocation LParenLoc,
9518 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00009519 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009520 Expr *ExecConfig,
9521 bool AllowTypoCorrection) {
John McCall3b4294e2009-12-16 12:17:52 +00009522#ifndef NDEBUG
9523 if (ULE->requiresADL()) {
9524 // To do ADL, we must have found an unqualified name.
9525 assert(!ULE->getQualifier() && "qualified name with ADL");
9526
9527 // We don't perform ADL for implicit declarations of builtins.
9528 // Verify that this was correctly set up.
9529 FunctionDecl *F;
9530 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9531 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9532 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009533 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009534
John McCall3b4294e2009-12-16 12:17:52 +00009535 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009536 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00009537 } else
9538 assert(!ULE->isStdAssociatedNamespace() &&
9539 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00009540#endif
9541
John McCall5acb0c92011-10-17 18:40:02 +00009542 UnbridgedCastsSet UnbridgedCasts;
9543 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9544 return ExprError();
9545
John McCall5769d612010-02-08 23:07:23 +00009546 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00009547
John McCall3b4294e2009-12-16 12:17:52 +00009548 // Add the functions denoted by the callee to the set of candidate
9549 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009550 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
9551 CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009552
9553 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009554 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9555 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009556 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009557 // In Microsoft mode, if we are inside a template class member function then
9558 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009559 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009560 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009561 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009562 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009563 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
9564 Context.DependentTy, VK_RValue,
9565 RParenLoc);
9566 CE->setTypeDependent(true);
9567 return Owned(CE);
9568 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009569 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
9570 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009571 RParenLoc, /*EmptyLookup=*/true,
9572 AllowTypoCorrection);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009573 }
John McCall578b69b2009-12-16 08:11:27 +00009574
John McCall5acb0c92011-10-17 18:40:02 +00009575 UnbridgedCasts.restore();
9576
Douglas Gregorf6b89692008-11-26 05:54:23 +00009577 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009578 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00009579 case OR_Success: {
9580 FunctionDecl *FDecl = Best->Function;
Eli Friedman5f2987c2012-02-02 03:46:19 +00009581 MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00009582 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00009583 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00009584 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00009585 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
9586 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009587 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009588
Richard Smithf50e88a2011-06-05 22:42:48 +00009589 case OR_No_Viable_Function: {
9590 // Try to recover by looking for viable functions which the user might
9591 // have meant to call.
9592 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009593 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9594 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009595 /*EmptyLookup=*/false,
9596 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009597 if (!Recovery.isInvalid())
9598 return Recovery;
9599
Daniel Dunbar96a00142012-03-09 18:35:03 +00009600 Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009601 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009602 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009603 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9604 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009605 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009606 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009607
9608 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +00009609 Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009610 << ULE->getName() << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009611 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9612 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009613 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009614
9615 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009616 {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009617 Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009618 << Best->Function->isDeleted()
9619 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009620 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009621 << Fn->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009622 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9623 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009624
9625 // We emitted an error for the unvailable/deleted function call but keep
9626 // the call in the AST.
9627 FunctionDecl *FDecl = Best->Function;
9628 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
9629 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9630 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00009631 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009632 }
9633
Douglas Gregorff331c12010-07-25 18:17:45 +00009634 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009635 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009636}
9637
John McCall6e266892010-01-26 03:27:55 +00009638static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009639 return Functions.size() > 1 ||
9640 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9641}
9642
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009643/// \brief Create a unary operation that may resolve to an overloaded
9644/// operator.
9645///
9646/// \param OpLoc The location of the operator itself (e.g., '*').
9647///
9648/// \param OpcIn The UnaryOperator::Opcode that describes this
9649/// operator.
9650///
9651/// \param Functions The set of non-member functions that will be
9652/// considered by overload resolution. The caller needs to build this
9653/// set based on the context using, e.g.,
9654/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9655/// set should not contain any member functions; those will be added
9656/// by CreateOverloadedUnaryOp().
9657///
9658/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009659ExprResult
John McCall6e266892010-01-26 03:27:55 +00009660Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9661 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009662 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009663 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009664
9665 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9666 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9667 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009668 // TODO: provide better source location info.
9669 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009670
John McCall5acb0c92011-10-17 18:40:02 +00009671 if (checkPlaceholderForOverload(*this, Input))
9672 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009673
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009674 Expr *Args[2] = { Input, 0 };
9675 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009676
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009677 // For post-increment and post-decrement, add the implicit '0' as
9678 // the second argument, so that we know this is a post-increment or
9679 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009680 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009681 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009682 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9683 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009684 NumArgs = 2;
9685 }
9686
9687 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009688 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009689 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009690 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009691 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009692 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009693 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009694
John McCallc373d482010-01-27 01:50:18 +00009695 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009696 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009697 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009698 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009699 /*ADL*/ true, IsOverloaded(Fns),
9700 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009701 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009702 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009703 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009704 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009705 OpLoc));
9706 }
9707
9708 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009709 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009710
9711 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009712 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
9713 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009714
9715 // Add operator candidates that are member functions.
9716 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9717
John McCall6e266892010-01-26 03:27:55 +00009718 // Add candidates from ADL.
9719 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009720 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +00009721 /*ExplicitTemplateArgs*/ 0,
9722 CandidateSet);
9723
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009724 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009725 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009726
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009727 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9728
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009729 // Perform overload resolution.
9730 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009731 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009732 case OR_Success: {
9733 // We found a built-in operator or an overloaded operator.
9734 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009735
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009736 if (FnDecl) {
9737 // We matched an overloaded operator. Build a call to that
9738 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009739
Eli Friedman5f2987c2012-02-02 03:46:19 +00009740 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009741
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009742 // Convert the arguments.
9743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009744 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009745
John Wiegley429bb272011-04-08 18:41:53 +00009746 ExprResult InputRes =
9747 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9748 Best->FoundDecl, Method);
9749 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009750 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009751 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009752 } else {
9753 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009754 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009755 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009756 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009757 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009758 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009759 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009760 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009761 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009762 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009763 }
9764
John McCallb697e082010-05-06 18:15:07 +00009765 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9766
John McCallf89e55a2010-11-18 06:31:45 +00009767 // Determine the result type.
9768 QualType ResultTy = FnDecl->getResultType();
9769 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9770 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009771
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009772 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009773 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +00009774 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009775 if (FnExpr.isInvalid())
9776 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009777
Eli Friedman4c3b8962009-11-18 03:58:17 +00009778 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009779 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009780 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009781 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009782
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009783 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009784 FnDecl))
9785 return ExprError();
9786
John McCall9ae2f072010-08-23 23:25:46 +00009787 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009788 } else {
9789 // We matched a built-in operator. Convert the arguments, then
9790 // break out so that we will build the appropriate built-in
9791 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009792 ExprResult InputRes =
9793 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9794 Best->Conversions[0], AA_Passing);
9795 if (InputRes.isInvalid())
9796 return ExprError();
9797 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009798 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009799 }
John Wiegley429bb272011-04-08 18:41:53 +00009800 }
9801
9802 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009803 // This is an erroneous use of an operator which can be overloaded by
9804 // a non-member function. Check for non-member operators which were
9805 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009806 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
9807 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +00009808 // FIXME: Recover by calling the found function.
9809 return ExprError();
9810
John Wiegley429bb272011-04-08 18:41:53 +00009811 // No viable function; fall through to handling this as a
9812 // built-in operator, which will produce an error message for us.
9813 break;
9814
9815 case OR_Ambiguous:
9816 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9817 << UnaryOperator::getOpcodeStr(Opc)
9818 << Input->getType()
9819 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009820 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
9821 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +00009822 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9823 return ExprError();
9824
9825 case OR_Deleted:
9826 Diag(OpLoc, diag::err_ovl_deleted_oper)
9827 << Best->Function->isDeleted()
9828 << UnaryOperator::getOpcodeStr(Opc)
9829 << getDeletedOrUnavailableSuffix(Best->Function)
9830 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +00009831 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
9832 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +00009833 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009834 return ExprError();
9835 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009836
9837 // Either we found no viable overloaded operator or we matched a
9838 // built-in operator. In either case, fall through to trying to
9839 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009840 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009841}
9842
Douglas Gregor063daf62009-03-13 18:40:31 +00009843/// \brief Create a binary operation that may resolve to an overloaded
9844/// operator.
9845///
9846/// \param OpLoc The location of the operator itself (e.g., '+').
9847///
9848/// \param OpcIn The BinaryOperator::Opcode that describes this
9849/// operator.
9850///
9851/// \param Functions The set of non-member functions that will be
9852/// considered by overload resolution. The caller needs to build this
9853/// set based on the context using, e.g.,
9854/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9855/// set should not contain any member functions; those will be added
9856/// by CreateOverloadedBinOp().
9857///
9858/// \param LHS Left-hand argument.
9859/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009860ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009861Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009862 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009863 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009864 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009865 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009866 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009867
9868 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9869 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9870 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9871
9872 // If either side is type-dependent, create an appropriate dependent
9873 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009874 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009875 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009876 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009877 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009878 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009879 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009880 Context.DependentTy,
9881 VK_RValue, OK_Ordinary,
9882 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009883
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009884 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9885 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009886 VK_LValue,
9887 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009888 Context.DependentTy,
9889 Context.DependentTy,
9890 OpLoc));
9891 }
John McCall6e266892010-01-26 03:27:55 +00009892
9893 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009894 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009895 // TODO: provide better source location info in DNLoc component.
9896 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009897 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009898 = UnresolvedLookupExpr::Create(Context, NamingClass,
9899 NestedNameSpecifierLoc(), OpNameInfo,
9900 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009901 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009902 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009903 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009904 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009905 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009906 OpLoc));
9907 }
9908
John McCall5acb0c92011-10-17 18:40:02 +00009909 // Always do placeholder-like conversions on the RHS.
9910 if (checkPlaceholderForOverload(*this, Args[1]))
9911 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009912
John McCall3c3b7f92011-10-25 17:37:35 +00009913 // Do placeholder-like conversion on the LHS; note that we should
9914 // not get here with a PseudoObject LHS.
9915 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009916 if (checkPlaceholderForOverload(*this, Args[0]))
9917 return ExprError();
9918
Sebastian Redl275c2b42009-11-18 23:10:33 +00009919 // If this is the assignment operator, we only perform overload resolution
9920 // if the left-hand side is a class or enumeration type. This is actually
9921 // a hack. The standard requires that we do overload resolution between the
9922 // various built-in candidates, but as DR507 points out, this can lead to
9923 // problems. So we do it this way, which pretty much follows what GCC does.
9924 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009925 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009926 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009927
John McCall0e800c92010-12-04 08:14:53 +00009928 // If this is the .* operator, which is not overloadable, just
9929 // create a built-in binary operator.
9930 if (Opc == BO_PtrMemD)
9931 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9932
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009933 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009934 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009935
9936 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009937 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009938
9939 // Add operator candidates that are member functions.
9940 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9941
John McCall6e266892010-01-26 03:27:55 +00009942 // Add candidates from ADL.
9943 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009944 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +00009945 /*ExplicitTemplateArgs*/ 0,
9946 CandidateSet);
9947
Douglas Gregor063daf62009-03-13 18:40:31 +00009948 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009949 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009950
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009951 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9952
Douglas Gregor063daf62009-03-13 18:40:31 +00009953 // Perform overload resolution.
9954 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009955 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00009956 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00009957 // We found a built-in operator or an overloaded operator.
9958 FunctionDecl *FnDecl = Best->Function;
9959
9960 if (FnDecl) {
9961 // We matched an overloaded operator. Build a call to that
9962 // operator.
9963
Eli Friedman5f2987c2012-02-02 03:46:19 +00009964 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009965
Douglas Gregor063daf62009-03-13 18:40:31 +00009966 // Convert the arguments.
9967 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00009968 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00009969 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009970
Chandler Carruth6df868e2010-12-12 08:17:55 +00009971 ExprResult Arg1 =
9972 PerformCopyInitialization(
9973 InitializedEntity::InitializeParameter(Context,
9974 FnDecl->getParamDecl(0)),
9975 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009976 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009977 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009978
John Wiegley429bb272011-04-08 18:41:53 +00009979 ExprResult Arg0 =
9980 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9981 Best->FoundDecl, Method);
9982 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009983 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009984 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009985 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009986 } else {
9987 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00009988 ExprResult Arg0 = PerformCopyInitialization(
9989 InitializedEntity::InitializeParameter(Context,
9990 FnDecl->getParamDecl(0)),
9991 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009992 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009993 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009994
Chandler Carruth6df868e2010-12-12 08:17:55 +00009995 ExprResult Arg1 =
9996 PerformCopyInitialization(
9997 InitializedEntity::InitializeParameter(Context,
9998 FnDecl->getParamDecl(1)),
9999 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010000 if (Arg1.isInvalid())
10001 return ExprError();
10002 Args[0] = LHS = Arg0.takeAs<Expr>();
10003 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010004 }
10005
John McCallb697e082010-05-06 18:15:07 +000010006 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10007
John McCallf89e55a2010-11-18 06:31:45 +000010008 // Determine the result type.
10009 QualType ResultTy = FnDecl->getResultType();
10010 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10011 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010012
10013 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010014 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10015 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010016 if (FnExpr.isInvalid())
10017 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010018
John McCall9ae2f072010-08-23 23:25:46 +000010019 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010020 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010021 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010022
10023 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010024 FnDecl))
10025 return ExprError();
10026
John McCall9ae2f072010-08-23 23:25:46 +000010027 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010028 } else {
10029 // We matched a built-in operator. Convert the arguments, then
10030 // break out so that we will build the appropriate built-in
10031 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010032 ExprResult ArgsRes0 =
10033 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10034 Best->Conversions[0], AA_Passing);
10035 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010036 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010037 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010038
John Wiegley429bb272011-04-08 18:41:53 +000010039 ExprResult ArgsRes1 =
10040 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10041 Best->Conversions[1], AA_Passing);
10042 if (ArgsRes1.isInvalid())
10043 return ExprError();
10044 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010045 break;
10046 }
10047 }
10048
Douglas Gregor33074752009-09-30 21:46:01 +000010049 case OR_No_Viable_Function: {
10050 // C++ [over.match.oper]p9:
10051 // If the operator is the operator , [...] and there are no
10052 // viable functions, then the operator is assumed to be the
10053 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010054 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010055 break;
10056
Chandler Carruth6df868e2010-12-12 08:17:55 +000010057 // For class as left operand for assignment or compound assigment
10058 // operator do not fall through to handling in built-in, but report that
10059 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010060 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010061 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010062 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010063 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10064 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010065 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010066 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010067 // This is an erroneous use of an operator which can be overloaded by
10068 // a non-member function. Check for non-member operators which were
10069 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010070 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010071 // FIXME: Recover by calling the found function.
10072 return ExprError();
10073
Douglas Gregor33074752009-09-30 21:46:01 +000010074 // No viable function; try to create a built-in operation, which will
10075 // produce an error. Then, show the non-viable candidates.
10076 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010077 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010078 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010079 "C++ binary operator overloading is missing candidates!");
10080 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010081 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010082 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +000010083 return move(Result);
10084 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010085
10086 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010087 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010088 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010089 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010090 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010091 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010092 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010093 return ExprError();
10094
10095 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010096 if (isImplicitlyDeleted(Best->Function)) {
10097 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10098 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10099 << getSpecialMember(Method)
10100 << BinaryOperator::getOpcodeStr(Opc)
10101 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010102
10103 if (getSpecialMember(Method) != CXXInvalid) {
10104 // The user probably meant to call this special member. Just
10105 // explain why it's deleted.
10106 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010107 return ExprError();
10108 }
10109 } else {
10110 Diag(OpLoc, diag::err_ovl_deleted_oper)
10111 << Best->Function->isDeleted()
10112 << BinaryOperator::getOpcodeStr(Opc)
10113 << getDeletedOrUnavailableSuffix(Best->Function)
10114 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10115 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010116 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010117 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010118 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010119 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010120
Douglas Gregor33074752009-09-30 21:46:01 +000010121 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010122 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010123}
10124
John McCall60d7b3a2010-08-24 06:29:42 +000010125ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010126Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10127 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010128 Expr *Base, Expr *Idx) {
10129 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010130 DeclarationName OpName =
10131 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10132
10133 // If either side is type-dependent, create an appropriate dependent
10134 // expression.
10135 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10136
John McCallc373d482010-01-27 01:50:18 +000010137 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010138 // CHECKME: no 'operator' keyword?
10139 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10140 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010141 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010142 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010143 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010144 /*ADL*/ true, /*Overloaded*/ false,
10145 UnresolvedSetIterator(),
10146 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010147 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010148
Sebastian Redlf322ed62009-10-29 20:17:01 +000010149 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
10150 Args, 2,
10151 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010152 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010153 RLoc));
10154 }
10155
John McCall5acb0c92011-10-17 18:40:02 +000010156 // Handle placeholders on both operands.
10157 if (checkPlaceholderForOverload(*this, Args[0]))
10158 return ExprError();
10159 if (checkPlaceholderForOverload(*this, Args[1]))
10160 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010161
Sebastian Redlf322ed62009-10-29 20:17:01 +000010162 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010163 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010164
10165 // Subscript can only be overloaded as a member function.
10166
10167 // Add operator candidates that are member functions.
10168 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10169
10170 // Add builtin operator candidates.
10171 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10172
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010173 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10174
Sebastian Redlf322ed62009-10-29 20:17:01 +000010175 // Perform overload resolution.
10176 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010177 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010178 case OR_Success: {
10179 // We found a built-in operator or an overloaded operator.
10180 FunctionDecl *FnDecl = Best->Function;
10181
10182 if (FnDecl) {
10183 // We matched an overloaded operator. Build a call to that
10184 // operator.
10185
Eli Friedman5f2987c2012-02-02 03:46:19 +000010186 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010187
John McCall9aa472c2010-03-19 07:35:19 +000010188 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010189 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010190
Sebastian Redlf322ed62009-10-29 20:17:01 +000010191 // Convert the arguments.
10192 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010193 ExprResult Arg0 =
10194 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10195 Best->FoundDecl, Method);
10196 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010197 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010198 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010199
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010200 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010201 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010202 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010203 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010204 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010205 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010206 Owned(Args[1]));
10207 if (InputInit.isInvalid())
10208 return ExprError();
10209
10210 Args[1] = InputInit.takeAs<Expr>();
10211
Sebastian Redlf322ed62009-10-29 20:17:01 +000010212 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010213 QualType ResultTy = FnDecl->getResultType();
10214 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10215 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010216
10217 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010218 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10219 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010220 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10221 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010222 OpLocInfo.getLoc(),
10223 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010224 if (FnExpr.isInvalid())
10225 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010226
John McCall9ae2f072010-08-23 23:25:46 +000010227 CXXOperatorCallExpr *TheCall =
10228 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +000010229 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +000010230 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010231
John McCall9ae2f072010-08-23 23:25:46 +000010232 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010233 FnDecl))
10234 return ExprError();
10235
John McCall9ae2f072010-08-23 23:25:46 +000010236 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010237 } else {
10238 // We matched a built-in operator. Convert the arguments, then
10239 // break out so that we will build the appropriate built-in
10240 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010241 ExprResult ArgsRes0 =
10242 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10243 Best->Conversions[0], AA_Passing);
10244 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010245 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010246 Args[0] = ArgsRes0.take();
10247
10248 ExprResult ArgsRes1 =
10249 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10250 Best->Conversions[1], AA_Passing);
10251 if (ArgsRes1.isInvalid())
10252 return ExprError();
10253 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010254
10255 break;
10256 }
10257 }
10258
10259 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010260 if (CandidateSet.empty())
10261 Diag(LLoc, diag::err_ovl_no_oper)
10262 << Args[0]->getType() << /*subscript*/ 0
10263 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10264 else
10265 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10266 << Args[0]->getType()
10267 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010268 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010269 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010270 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010271 }
10272
10273 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010274 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010275 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010276 << Args[0]->getType() << Args[1]->getType()
10277 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010278 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010279 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010280 return ExprError();
10281
10282 case OR_Deleted:
10283 Diag(LLoc, diag::err_ovl_deleted_oper)
10284 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010285 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010286 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010287 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010288 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010289 return ExprError();
10290 }
10291
10292 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010293 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010294}
10295
Douglas Gregor88a35142008-12-22 05:46:06 +000010296/// BuildCallToMemberFunction - Build a call to a member
10297/// function. MemExpr is the expression that refers to the member
10298/// function (and includes the object parameter), Args/NumArgs are the
10299/// arguments to the function call (not including the object
10300/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010301/// expression refers to a non-static member function or an overloaded
10302/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010303ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010304Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10305 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010306 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010307 assert(MemExprE->getType() == Context.BoundMemberTy ||
10308 MemExprE->getType() == Context.OverloadTy);
10309
Douglas Gregor88a35142008-12-22 05:46:06 +000010310 // Dig out the member expression. This holds both the object
10311 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010312 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010313
John McCall864c0412011-04-26 20:42:42 +000010314 // Determine whether this is a call to a pointer-to-member function.
10315 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10316 assert(op->getType() == Context.BoundMemberTy);
10317 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10318
10319 QualType fnType =
10320 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10321
10322 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10323 QualType resultType = proto->getCallResultType(Context);
10324 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10325
10326 // Check that the object type isn't more qualified than the
10327 // member function we're calling.
10328 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10329
10330 QualType objectType = op->getLHS()->getType();
10331 if (op->getOpcode() == BO_PtrMemI)
10332 objectType = objectType->castAs<PointerType>()->getPointeeType();
10333 Qualifiers objectQuals = objectType.getQualifiers();
10334
10335 Qualifiers difference = objectQuals - funcQuals;
10336 difference.removeObjCGCAttr();
10337 difference.removeAddressSpace();
10338 if (difference) {
10339 std::string qualsString = difference.getAsString();
10340 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10341 << fnType.getUnqualifiedType()
10342 << qualsString
10343 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10344 }
10345
10346 CXXMemberCallExpr *call
10347 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
10348 resultType, valueKind, RParenLoc);
10349
10350 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010351 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010352 call, 0))
10353 return ExprError();
10354
10355 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10356 return ExprError();
10357
10358 return MaybeBindToTemporary(call);
10359 }
10360
John McCall5acb0c92011-10-17 18:40:02 +000010361 UnbridgedCastsSet UnbridgedCasts;
10362 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10363 return ExprError();
10364
John McCall129e2df2009-11-30 22:42:35 +000010365 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010366 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010367 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010368 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010369 if (isa<MemberExpr>(NakedMemExpr)) {
10370 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010371 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010372 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010373 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010374 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010375 } else {
10376 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010377 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010378
John McCall701c89e2009-12-03 04:06:58 +000010379 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010380 Expr::Classification ObjectClassification
10381 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10382 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010383
Douglas Gregor88a35142008-12-22 05:46:06 +000010384 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010385 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010386
John McCallaa81e162009-12-01 22:10:20 +000010387 // FIXME: avoid copy.
10388 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10389 if (UnresExpr->hasExplicitTemplateArgs()) {
10390 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10391 TemplateArgs = &TemplateArgsBuffer;
10392 }
10393
John McCall129e2df2009-11-30 22:42:35 +000010394 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10395 E = UnresExpr->decls_end(); I != E; ++I) {
10396
John McCall701c89e2009-12-03 04:06:58 +000010397 NamedDecl *Func = *I;
10398 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10399 if (isa<UsingShadowDecl>(Func))
10400 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10401
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010402
Francois Pichetdbee3412011-01-18 05:04:39 +000010403 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010404 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010405 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10406 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010407 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010408 // If explicit template arguments were provided, we can't call a
10409 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010410 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010411 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010412
John McCall9aa472c2010-03-19 07:35:19 +000010413 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010414 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010415 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010416 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010417 } else {
John McCall129e2df2009-11-30 22:42:35 +000010418 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010419 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010420 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010421 llvm::makeArrayRef(Args, NumArgs),
10422 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010423 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010424 }
Douglas Gregordec06662009-08-21 18:42:58 +000010425 }
Mike Stump1eb44332009-09-09 15:08:12 +000010426
John McCall129e2df2009-11-30 22:42:35 +000010427 DeclarationName DeclName = UnresExpr->getMemberName();
10428
John McCall5acb0c92011-10-17 18:40:02 +000010429 UnbridgedCasts.restore();
10430
Douglas Gregor88a35142008-12-22 05:46:06 +000010431 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010432 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010433 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010434 case OR_Success:
10435 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010436 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010437 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010438 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010439 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010440 break;
10441
10442 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010443 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010444 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010445 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010446 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10447 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010448 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010449 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010450
10451 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010452 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010453 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010454 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10455 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010456 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010457 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010458
10459 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010460 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010461 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010462 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010463 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010464 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010465 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10466 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010467 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010468 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010469 }
10470
John McCall6bb80172010-03-30 21:47:33 +000010471 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010472
John McCallaa81e162009-12-01 22:10:20 +000010473 // If overload resolution picked a static member, build a
10474 // non-member call based on that function.
10475 if (Method->isStatic()) {
10476 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10477 Args, NumArgs, RParenLoc);
10478 }
10479
John McCall129e2df2009-11-30 22:42:35 +000010480 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010481 }
10482
John McCallf89e55a2010-11-18 06:31:45 +000010483 QualType ResultType = Method->getResultType();
10484 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10485 ResultType = ResultType.getNonLValueExprType(Context);
10486
Douglas Gregor88a35142008-12-22 05:46:06 +000010487 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010488 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +000010489 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +000010490 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010491
Anders Carlssoneed3e692009-10-10 00:06:20 +000010492 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010493 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010494 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010495 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010496
Douglas Gregor88a35142008-12-22 05:46:06 +000010497 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010498 // We only need to do this if there was actually an overload; otherwise
10499 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010500 if (!Method->isStatic()) {
10501 ExprResult ObjectArg =
10502 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10503 FoundDecl, Method);
10504 if (ObjectArg.isInvalid())
10505 return ExprError();
10506 MemExpr->setBase(ObjectArg.take());
10507 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010508
10509 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010510 const FunctionProtoType *Proto =
10511 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010512 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010513 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010514 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010515
Eli Friedmane61eb042012-02-18 04:48:30 +000010516 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10517
John McCall9ae2f072010-08-23 23:25:46 +000010518 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +000010519 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010520
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010521 if ((isa<CXXConstructorDecl>(CurContext) ||
10522 isa<CXXDestructorDecl>(CurContext)) &&
10523 TheCall->getMethodDecl()->isPure()) {
10524 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10525
Chandler Carruthae198062011-06-27 08:31:58 +000010526 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010527 Diag(MemExpr->getLocStart(),
10528 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10529 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10530 << MD->getParent()->getDeclName();
10531
10532 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010533 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010534 }
John McCall9ae2f072010-08-23 23:25:46 +000010535 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010536}
10537
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010538/// BuildCallToObjectOfClassType - Build a call to an object of class
10539/// type (C++ [over.call.object]), which can end up invoking an
10540/// overloaded function call operator (@c operator()) or performing a
10541/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010542ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010543Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010544 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010545 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010546 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010547 if (checkPlaceholderForOverload(*this, Obj))
10548 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010549 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010550
10551 UnbridgedCastsSet UnbridgedCasts;
10552 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10553 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010554
John Wiegley429bb272011-04-08 18:41:53 +000010555 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10556 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010557
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010558 // C++ [over.call.object]p1:
10559 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010560 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010561 // candidate functions includes at least the function call
10562 // operators of T. The function call operators of T are obtained by
10563 // ordinary lookup of the name operator() in the context of
10564 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010565 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010566 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010567
John Wiegley429bb272011-04-08 18:41:53 +000010568 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +000010569 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010570 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010571 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010572
John McCalla24dc2e2009-11-17 02:14:36 +000010573 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10574 LookupQualifiedName(R, Record->getDecl());
10575 R.suppressDiagnostics();
10576
Douglas Gregor593564b2009-11-15 07:48:03 +000010577 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010578 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010579 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10580 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010581 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010582 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010583
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010584 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010585 // In addition, for each (non-explicit in C++0x) conversion function
10586 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010587 //
10588 // operator conversion-type-id () cv-qualifier;
10589 //
10590 // where cv-qualifier is the same cv-qualification as, or a
10591 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010592 // denotes the type "pointer to function of (P1,...,Pn) returning
10593 // R", or the type "reference to pointer to function of
10594 // (P1,...,Pn) returning R", or the type "reference to function
10595 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010596 // is also considered as a candidate function. Similarly,
10597 // surrogate call functions are added to the set of candidate
10598 // functions for each conversion function declared in an
10599 // accessible base class provided the function is not hidden
10600 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +000010601 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010602 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +000010603 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +000010604 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010605 NamedDecl *D = *I;
10606 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10607 if (isa<UsingShadowDecl>(D))
10608 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010609
Douglas Gregor4a27d702009-10-21 06:18:39 +000010610 // Skip over templated conversion functions; they aren't
10611 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010612 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010613 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010614
John McCall701c89e2009-12-03 04:06:58 +000010615 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010616 if (!Conv->isExplicit()) {
10617 // Strip the reference type (if any) and then the pointer type (if
10618 // any) to get down to what might be a function type.
10619 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10620 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10621 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010622
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010623 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10624 {
10625 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010626 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10627 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010628 }
10629 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010630 }
Mike Stump1eb44332009-09-09 15:08:12 +000010631
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010632 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10633
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010634 // Perform overload resolution.
10635 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010636 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010637 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010638 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010639 // Overload resolution succeeded; we'll build the appropriate call
10640 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010641 break;
10642
10643 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010644 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010645 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010646 << Object.get()->getType() << /*call*/ 1
10647 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010648 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010649 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010650 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010651 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010652 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10653 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010654 break;
10655
10656 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010657 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010658 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010659 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010660 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10661 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010662 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010663
10664 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010665 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010666 diag::err_ovl_deleted_object_call)
10667 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010668 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010669 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010670 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010671 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10672 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010673 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010674 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010675
Douglas Gregorff331c12010-07-25 18:17:45 +000010676 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010677 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010678
John McCall5acb0c92011-10-17 18:40:02 +000010679 UnbridgedCasts.restore();
10680
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010681 if (Best->Function == 0) {
10682 // Since there is no function declaration, this is one of the
10683 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010684 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010685 = cast<CXXConversionDecl>(
10686 Best->Conversions[0].UserDefined.ConversionFunction);
10687
John Wiegley429bb272011-04-08 18:41:53 +000010688 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010689 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010690
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010691 // We selected one of the surrogate functions that converts the
10692 // object parameter to a function pointer. Perform the conversion
10693 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010694
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010695 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010696 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010697 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10698 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010699 if (Call.isInvalid())
10700 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010701 // Record usage of conversion in an implicit cast.
10702 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10703 CK_UserDefinedConversion,
10704 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010705
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010706 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010707 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010708 }
10709
Eli Friedman5f2987c2012-02-02 03:46:19 +000010710 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010711 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010712 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010713
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010714 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10715 // that calls this method, using Object for the implicit object
10716 // parameter and passing along the remaining arguments.
10717 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010718 const FunctionProtoType *Proto =
10719 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010720
10721 unsigned NumArgsInProto = Proto->getNumArgs();
10722 unsigned NumArgsToCheck = NumArgs;
10723
10724 // Build the full argument list for the method call (the
10725 // implicit object parameter is placed at the beginning of the
10726 // list).
10727 Expr **MethodArgs;
10728 if (NumArgs < NumArgsInProto) {
10729 NumArgsToCheck = NumArgsInProto;
10730 MethodArgs = new Expr*[NumArgsInProto + 1];
10731 } else {
10732 MethodArgs = new Expr*[NumArgs + 1];
10733 }
John Wiegley429bb272011-04-08 18:41:53 +000010734 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010735 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10736 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010737
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010738 DeclarationNameInfo OpLocInfo(
10739 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
10740 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010741 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010742 HadMultipleCandidates,
10743 OpLocInfo.getLoc(),
10744 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010745 if (NewFn.isInvalid())
10746 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010747
10748 // Once we've built TheCall, all of the expressions are properly
10749 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010750 QualType ResultTy = Method->getResultType();
10751 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10752 ResultTy = ResultTy.getNonLValueExprType(Context);
10753
John McCall9ae2f072010-08-23 23:25:46 +000010754 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010755 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010756 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010757 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010758 delete [] MethodArgs;
10759
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010760 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010761 Method))
10762 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010763
Douglas Gregor518fda12009-01-13 05:10:00 +000010764 // We may have default arguments. If so, we need to allocate more
10765 // slots in the call for them.
10766 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010767 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010768 else if (NumArgs > NumArgsInProto)
10769 NumArgsToCheck = NumArgsInProto;
10770
Chris Lattner312531a2009-04-12 08:11:20 +000010771 bool IsError = false;
10772
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010773 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010774 ExprResult ObjRes =
10775 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10776 Best->FoundDecl, Method);
10777 if (ObjRes.isInvalid())
10778 IsError = true;
10779 else
10780 Object = move(ObjRes);
10781 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010782
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010783 // Check the argument types.
10784 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010785 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010786 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010787 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010788
Douglas Gregor518fda12009-01-13 05:10:00 +000010789 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010790
John McCall60d7b3a2010-08-24 06:29:42 +000010791 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010792 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010793 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010794 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010795 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010796
Anders Carlsson3faa4862010-01-29 18:43:53 +000010797 IsError |= InputInit.isInvalid();
10798 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010799 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010800 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010801 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10802 if (DefArg.isInvalid()) {
10803 IsError = true;
10804 break;
10805 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010806
Douglas Gregord47c47d2009-11-09 19:27:57 +000010807 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010808 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010809
10810 TheCall->setArg(i + 1, Arg);
10811 }
10812
10813 // If this is a variadic call, handle args passed through "...".
10814 if (Proto->isVariadic()) {
10815 // Promote the arguments (C99 6.5.2.2p7).
10816 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010817 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10818 IsError |= Arg.isInvalid();
10819 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010820 }
10821 }
10822
Chris Lattner312531a2009-04-12 08:11:20 +000010823 if (IsError) return true;
10824
Eli Friedmane61eb042012-02-18 04:48:30 +000010825 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10826
John McCall9ae2f072010-08-23 23:25:46 +000010827 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010828 return true;
10829
John McCall182f7092010-08-24 06:09:16 +000010830 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010831}
10832
Douglas Gregor8ba10742008-11-20 16:27:02 +000010833/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010834/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010835/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010836ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010837Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010838 assert(Base->getType()->isRecordType() &&
10839 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010840
John McCall5acb0c92011-10-17 18:40:02 +000010841 if (checkPlaceholderForOverload(*this, Base))
10842 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010843
John McCall5769d612010-02-08 23:07:23 +000010844 SourceLocation Loc = Base->getExprLoc();
10845
Douglas Gregor8ba10742008-11-20 16:27:02 +000010846 // C++ [over.ref]p1:
10847 //
10848 // [...] An expression x->m is interpreted as (x.operator->())->m
10849 // for a class object x of type T if T::operator->() exists and if
10850 // the operator is selected as the best match function by the
10851 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010852 DeclarationName OpName =
10853 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010854 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010855 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010856
John McCall5769d612010-02-08 23:07:23 +000010857 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +000010858 PDiag(diag::err_typecheck_incomplete_tag)
10859 << Base->getSourceRange()))
10860 return ExprError();
10861
John McCalla24dc2e2009-11-17 02:14:36 +000010862 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10863 LookupQualifiedName(R, BaseRecord->getDecl());
10864 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010865
10866 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010867 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010868 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10869 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010870 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010871
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010872 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10873
Douglas Gregor8ba10742008-11-20 16:27:02 +000010874 // Perform overload resolution.
10875 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010876 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010877 case OR_Success:
10878 // Overload resolution succeeded; we'll build the call below.
10879 break;
10880
10881 case OR_No_Viable_Function:
10882 if (CandidateSet.empty())
10883 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010884 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010885 else
10886 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010887 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010888 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010889 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010890
10891 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010892 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10893 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010894 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010895 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010896
10897 case OR_Deleted:
10898 Diag(OpLoc, diag::err_ovl_deleted_oper)
10899 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010900 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010901 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010902 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010903 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010904 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010905 }
10906
Eli Friedman5f2987c2012-02-02 03:46:19 +000010907 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010908 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010909 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010910
Douglas Gregor8ba10742008-11-20 16:27:02 +000010911 // Convert the object parameter.
10912 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010913 ExprResult BaseResult =
10914 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10915 Best->FoundDecl, Method);
10916 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010917 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010918 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010919
Douglas Gregor8ba10742008-11-20 16:27:02 +000010920 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010921 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010922 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010923 if (FnExpr.isInvalid())
10924 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010925
John McCallf89e55a2010-11-18 06:31:45 +000010926 QualType ResultTy = Method->getResultType();
10927 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10928 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010929 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010930 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010931 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010932
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010933 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010934 Method))
10935 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010936
10937 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010938}
10939
Richard Smith36f5cfe2012-03-09 08:00:36 +000010940/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
10941/// a literal operator described by the provided lookup results.
10942ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
10943 DeclarationNameInfo &SuffixInfo,
10944 ArrayRef<Expr*> Args,
10945 SourceLocation LitEndLoc,
10946 TemplateArgumentListInfo *TemplateArgs) {
10947 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000010948
Richard Smith36f5cfe2012-03-09 08:00:36 +000010949 OverloadCandidateSet CandidateSet(UDSuffixLoc);
10950 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
10951 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000010952
Richard Smith36f5cfe2012-03-09 08:00:36 +000010953 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10954
Richard Smith36f5cfe2012-03-09 08:00:36 +000010955 // Perform overload resolution. This will usually be trivial, but might need
10956 // to perform substitutions for a literal operator template.
10957 OverloadCandidateSet::iterator Best;
10958 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
10959 case OR_Success:
10960 case OR_Deleted:
10961 break;
10962
10963 case OR_No_Viable_Function:
10964 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
10965 << R.getLookupName();
10966 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
10967 return ExprError();
10968
10969 case OR_Ambiguous:
10970 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
10971 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
10972 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000010973 }
10974
Richard Smith36f5cfe2012-03-09 08:00:36 +000010975 FunctionDecl *FD = Best->Function;
10976 MarkFunctionReferenced(UDSuffixLoc, FD);
10977 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000010978
Richard Smith36f5cfe2012-03-09 08:00:36 +000010979 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
10980 SuffixInfo.getLoc(),
10981 SuffixInfo.getInfo());
10982 if (Fn.isInvalid())
10983 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000010984
10985 // Check the argument types. This should almost always be a no-op, except
10986 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000010987 Expr *ConvArgs[2];
10988 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
10989 ExprResult InputInit = PerformCopyInitialization(
10990 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
10991 SourceLocation(), Args[ArgIdx]);
10992 if (InputInit.isInvalid())
10993 return true;
10994 ConvArgs[ArgIdx] = InputInit.take();
10995 }
10996
Richard Smith9fcce652012-03-07 08:35:16 +000010997 QualType ResultTy = FD->getResultType();
10998 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10999 ResultTy = ResultTy.getNonLValueExprType(Context);
11000
Richard Smith9fcce652012-03-07 08:35:16 +000011001 UserDefinedLiteral *UDL =
11002 new (Context) UserDefinedLiteral(Context, Fn.take(), ConvArgs, Args.size(),
11003 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11004
11005 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11006 return ExprError();
11007
11008 if (CheckFunctionCall(FD, UDL))
11009 return ExprError();
11010
11011 return MaybeBindToTemporary(UDL);
11012}
11013
Douglas Gregor904eed32008-11-10 20:40:00 +000011014/// FixOverloadedFunctionReference - E is an expression that refers to
11015/// a C++ overloaded function (possibly with some parentheses and
11016/// perhaps a '&' around it). We have resolved the overloaded function
11017/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011018/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011019Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011020 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011021 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011022 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11023 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011024 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011025 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011026
Douglas Gregor699ee522009-11-20 19:42:02 +000011027 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011028 }
11029
Douglas Gregor699ee522009-11-20 19:42:02 +000011030 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011031 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11032 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011033 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011034 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011035 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011036 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011037 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011038 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011039
11040 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011041 ICE->getCastKind(),
11042 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011043 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011044 }
11045
Douglas Gregor699ee522009-11-20 19:42:02 +000011046 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011047 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011048 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011049 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11050 if (Method->isStatic()) {
11051 // Do nothing: static member functions aren't any different
11052 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011053 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011054 // Fix the sub expression, which really has to be an
11055 // UnresolvedLookupExpr holding an overloaded member function
11056 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011057 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11058 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011059 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011060 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011061
John McCallba135432009-11-21 08:51:07 +000011062 assert(isa<DeclRefExpr>(SubExpr)
11063 && "fixed to something other than a decl ref");
11064 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11065 && "fixed to a member ref with no nested name qualifier");
11066
11067 // We have taken the address of a pointer to member
11068 // function. Perform the computation here so that we get the
11069 // appropriate pointer to member type.
11070 QualType ClassType
11071 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11072 QualType MemPtrType
11073 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11074
John McCallf89e55a2010-11-18 06:31:45 +000011075 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11076 VK_RValue, OK_Ordinary,
11077 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011078 }
11079 }
John McCall6bb80172010-03-30 21:47:33 +000011080 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11081 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011082 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011083 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011084
John McCall2de56d12010-08-25 11:45:40 +000011085 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011086 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011087 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011088 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011089 }
John McCallba135432009-11-21 08:51:07 +000011090
11091 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011092 // FIXME: avoid copy.
11093 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011094 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011095 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11096 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011097 }
11098
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011099 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11100 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011101 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011102 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011103 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011104 ULE->getNameLoc(),
11105 Fn->getType(),
11106 VK_LValue,
11107 Found.getDecl(),
11108 TemplateArgs);
11109 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11110 return DRE;
John McCallba135432009-11-21 08:51:07 +000011111 }
11112
John McCall129e2df2009-11-30 22:42:35 +000011113 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011114 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011115 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11116 if (MemExpr->hasExplicitTemplateArgs()) {
11117 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11118 TemplateArgs = &TemplateArgsBuffer;
11119 }
John McCalld5532b62009-11-23 01:53:49 +000011120
John McCallaa81e162009-12-01 22:10:20 +000011121 Expr *Base;
11122
John McCallf89e55a2010-11-18 06:31:45 +000011123 // If we're filling in a static method where we used to have an
11124 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011125 if (MemExpr->isImplicitAccess()) {
11126 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011127 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11128 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011129 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011130 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011131 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011132 MemExpr->getMemberLoc(),
11133 Fn->getType(),
11134 VK_LValue,
11135 Found.getDecl(),
11136 TemplateArgs);
11137 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11138 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011139 } else {
11140 SourceLocation Loc = MemExpr->getMemberLoc();
11141 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011142 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011143 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011144 Base = new (Context) CXXThisExpr(Loc,
11145 MemExpr->getBaseType(),
11146 /*isImplicit=*/true);
11147 }
John McCallaa81e162009-12-01 22:10:20 +000011148 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011149 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011150
John McCallf5307512011-04-27 00:36:17 +000011151 ExprValueKind valueKind;
11152 QualType type;
11153 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11154 valueKind = VK_LValue;
11155 type = Fn->getType();
11156 } else {
11157 valueKind = VK_RValue;
11158 type = Context.BoundMemberTy;
11159 }
11160
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011161 MemberExpr *ME = MemberExpr::Create(Context, Base,
11162 MemExpr->isArrow(),
11163 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011164 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011165 Fn,
11166 Found,
11167 MemExpr->getMemberNameInfo(),
11168 TemplateArgs,
11169 type, valueKind, OK_Ordinary);
11170 ME->setHadMultipleCandidates(true);
11171 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011172 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011173
John McCall3fa5cae2010-10-26 07:05:15 +000011174 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011175}
11176
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011177ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011178 DeclAccessPair Found,
11179 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011180 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011181}
11182
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011183} // end namespace clang