blob: 02584525c97c0b8358a0471d3d6450dd66b9723d [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
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/Sema/Overload.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000015#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000018#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000019#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000020#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000023#include "clang/Basic/PartialDiagnostic.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Lex/Preprocessor.h"
25#include "clang/Sema/Initialization.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/SemaInternal.h"
28#include "clang/Sema/Template.h"
29#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000030#include "llvm/ADT/DenseSet.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000032#include "llvm/ADT/SmallPtrSet.h"
Richard Smithb8590f32012-05-07 09:03:25 +000033#include "llvm/ADT/SmallString.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034#include <algorithm>
35
36namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000037using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000038
John McCallf89e55a2010-11-18 06:31:45 +000039/// A convenience routine for creating a decayed reference to a
40/// function.
John Wiegley429bb272011-04-08 18:41:53 +000041static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000042CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000043 SourceLocation Loc = SourceLocation(),
44 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
John McCallf4b88a42012-03-10 09:33:50 +000045 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, false, Fn->getType(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000046 VK_LValue, Loc, LocInfo);
47 if (HadMultipleCandidates)
48 DRE->setHadMultipleCandidates(true);
49 ExprResult E = S.Owned(DRE);
John Wiegley429bb272011-04-08 18:41:53 +000050 E = S.DefaultFunctionArrayConversion(E.take());
51 if (E.isInvalid())
52 return ExprError();
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000053 return E;
John McCallf89e55a2010-11-18 06:31:45 +000054}
55
John McCall120d63c2010-08-24 20:38:10 +000056static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
57 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000058 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000059 bool CStyle,
60 bool AllowObjCWritebackConversion);
Sam Panzerd0125862012-08-16 02:38:47 +000061
Fariborz Jahaniand97f5582011-03-23 19:50:54 +000062static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
63 QualType &ToType,
64 bool InOverloadResolution,
65 StandardConversionSequence &SCS,
66 bool CStyle);
John McCall120d63c2010-08-24 20:38:10 +000067static OverloadingResult
68IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
69 UserDefinedConversionSequence& User,
70 OverloadCandidateSet& Conversions,
71 bool AllowExplicit);
72
73
74static ImplicitConversionSequence::CompareKind
75CompareStandardConversionSequences(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareQualificationConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84static ImplicitConversionSequence::CompareKind
85CompareDerivedToBaseConversions(Sema &S,
86 const StandardConversionSequence& SCS1,
87 const StandardConversionSequence& SCS2);
88
89
90
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000091/// GetConversionCategory - Retrieve the implicit conversion
92/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000093ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000094GetConversionCategory(ImplicitConversionKind Kind) {
95 static const ImplicitConversionCategory
96 Category[(int)ICK_Num_Conversion_Kinds] = {
97 ICC_Identity,
98 ICC_Lvalue_Transformation,
99 ICC_Lvalue_Transformation,
100 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000101 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000102 ICC_Qualification_Adjustment,
103 ICC_Promotion,
104 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 ICC_Promotion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
111 ICC_Conversion,
112 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000113 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000114 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000115 ICC_Conversion,
116 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000117 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000118 ICC_Conversion
119 };
120 return Category[(int)Kind];
121}
122
123/// GetConversionRank - Retrieve the implicit conversion rank
124/// corresponding to the given implicit conversion kind.
125ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
126 static const ImplicitConversionRank
127 Rank[(int)ICK_Num_Conversion_Kinds] = {
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
131 ICR_Exact_Match,
132 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000133 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134 ICR_Promotion,
135 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 ICR_Promotion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
142 ICR_Conversion,
143 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000144 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000145 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000146 ICR_Conversion,
147 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000148 ICR_Complex_Real_Conversion,
149 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000150 ICR_Conversion,
151 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152 };
153 return Rank[(int)Kind];
154}
155
156/// GetImplicitConversionName - Return the name of this kind of
157/// implicit conversion.
158const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000159 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000160 "No conversion",
161 "Lvalue-to-rvalue",
162 "Array-to-pointer",
163 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000164 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000165 "Qualification",
166 "Integral promotion",
167 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000168 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169 "Integral conversion",
170 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000171 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 "Floating-integral conversion",
173 "Pointer conversion",
174 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000175 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000176 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000177 "Derived-to-base conversion",
178 "Vector conversion",
179 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000180 "Complex-real conversion",
181 "Block Pointer conversion",
182 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000183 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000184 };
185 return Name[Kind];
186}
187
Douglas Gregor60d62c22008-10-31 16:23:19 +0000188/// StandardConversionSequence - Set the standard conversion
189/// sequence to the identity conversion.
190void StandardConversionSequence::setAsIdentityConversion() {
191 First = ICK_Identity;
192 Second = ICK_Identity;
193 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000194 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000195 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000196 ReferenceBinding = false;
197 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000198 IsLvalueReference = true;
199 BindsToFunctionLvalue = false;
200 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000201 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000202 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000203 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000204}
205
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000206/// getRank - Retrieve the rank of this standard conversion sequence
207/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
208/// implicit conversions.
209ImplicitConversionRank StandardConversionSequence::getRank() const {
210 ImplicitConversionRank Rank = ICR_Exact_Match;
211 if (GetConversionRank(First) > Rank)
212 Rank = GetConversionRank(First);
213 if (GetConversionRank(Second) > Rank)
214 Rank = GetConversionRank(Second);
215 if (GetConversionRank(Third) > Rank)
216 Rank = GetConversionRank(Third);
217 return Rank;
218}
219
220/// isPointerConversionToBool - Determines whether this conversion is
221/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000222/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000224bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer or function-to-pointer implicit conversions, so
227 // check for their presence as well as checking whether FromType is
228 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000229 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000230 (getFromType()->isPointerType() ||
231 getFromType()->isObjCObjectPointerType() ||
232 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000233 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000234 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
235 return true;
236
237 return false;
238}
239
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000240/// isPointerConversionToVoidPointer - Determines whether this
241/// conversion is a conversion of a pointer to a void pointer. This is
242/// used as part of the ranking of standard conversion sequences (C++
243/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000244bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000245StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000246isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000247 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000248 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000249
250 // Note that FromType has not necessarily been transformed by the
251 // array-to-pointer implicit conversion, so check for its presence
252 // and redo the conversion to get a pointer.
253 if (First == ICK_Array_To_Pointer)
254 FromType = Context.getArrayDecayedType(FromType);
255
Douglas Gregorf9af5242011-04-15 20:45:44 +0000256 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000257 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000258 return ToPtrType->getPointeeType()->isVoidType();
259
260 return false;
261}
262
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000263/// Skip any implicit casts which could be either part of a narrowing conversion
264/// or after one in an implicit conversion.
265static const Expr *IgnoreNarrowingConversion(const Expr *Converted) {
266 while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Converted)) {
267 switch (ICE->getCastKind()) {
268 case CK_NoOp:
269 case CK_IntegralCast:
270 case CK_IntegralToBoolean:
271 case CK_IntegralToFloating:
272 case CK_FloatingToIntegral:
273 case CK_FloatingToBoolean:
274 case CK_FloatingCast:
275 Converted = ICE->getSubExpr();
276 continue;
277
278 default:
279 return Converted;
280 }
281 }
282
283 return Converted;
284}
285
286/// Check if this standard conversion sequence represents a narrowing
287/// conversion, according to C++11 [dcl.init.list]p7.
288///
289/// \param Ctx The AST context.
290/// \param Converted The result of applying this standard conversion sequence.
291/// \param ConstantValue If this is an NK_Constant_Narrowing conversion, the
292/// value of the expression prior to the narrowing conversion.
Richard Smithf6028062012-03-23 23:55:39 +0000293/// \param ConstantType If this is an NK_Constant_Narrowing conversion, the
294/// type of the expression prior to the narrowing conversion.
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000295NarrowingKind
Richard Smith8ef7b202012-01-18 23:55:52 +0000296StandardConversionSequence::getNarrowingKind(ASTContext &Ctx,
297 const Expr *Converted,
Richard Smithf6028062012-03-23 23:55:39 +0000298 APValue &ConstantValue,
299 QualType &ConstantType) const {
David Blaikie4e4d0842012-03-11 07:00:24 +0000300 assert(Ctx.getLangOpts().CPlusPlus && "narrowing check outside C++");
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000301
302 // C++11 [dcl.init.list]p7:
303 // A narrowing conversion is an implicit conversion ...
304 QualType FromType = getToType(0);
305 QualType ToType = getToType(1);
306 switch (Second) {
307 // -- from a floating-point type to an integer type, or
308 //
309 // -- from an integer type or unscoped enumeration type to a floating-point
310 // type, except where the source is a constant expression and the actual
311 // value after conversion will fit into the target type and will produce
312 // the original value when converted back to the original type, or
313 case ICK_Floating_Integral:
314 if (FromType->isRealFloatingType() && ToType->isIntegralType(Ctx)) {
315 return NK_Type_Narrowing;
316 } else if (FromType->isIntegralType(Ctx) && ToType->isRealFloatingType()) {
317 llvm::APSInt IntConstantValue;
318 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
319 if (Initializer &&
320 Initializer->isIntegerConstantExpr(IntConstantValue, Ctx)) {
321 // Convert the integer to the floating type.
322 llvm::APFloat Result(Ctx.getFloatTypeSemantics(ToType));
323 Result.convertFromAPInt(IntConstantValue, IntConstantValue.isSigned(),
324 llvm::APFloat::rmNearestTiesToEven);
325 // And back.
326 llvm::APSInt ConvertedValue = IntConstantValue;
327 bool ignored;
328 Result.convertToInteger(ConvertedValue,
329 llvm::APFloat::rmTowardZero, &ignored);
330 // If the resulting value is different, this was a narrowing conversion.
331 if (IntConstantValue != ConvertedValue) {
332 ConstantValue = APValue(IntConstantValue);
Richard Smithf6028062012-03-23 23:55:39 +0000333 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000334 return NK_Constant_Narrowing;
335 }
336 } else {
337 // Variables are always narrowings.
338 return NK_Variable_Narrowing;
339 }
340 }
341 return NK_Not_Narrowing;
342
343 // -- from long double to double or float, or from double to float, except
344 // where the source is a constant expression and the actual value after
345 // conversion is within the range of values that can be represented (even
346 // if it cannot be represented exactly), or
347 case ICK_Floating_Conversion:
348 if (FromType->isRealFloatingType() && ToType->isRealFloatingType() &&
349 Ctx.getFloatingTypeOrder(FromType, ToType) == 1) {
350 // FromType is larger than ToType.
351 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
352 if (Initializer->isCXX11ConstantExpr(Ctx, &ConstantValue)) {
353 // Constant!
354 assert(ConstantValue.isFloat());
355 llvm::APFloat FloatVal = ConstantValue.getFloat();
356 // Convert the source value into the target type.
357 bool ignored;
358 llvm::APFloat::opStatus ConvertStatus = FloatVal.convert(
359 Ctx.getFloatTypeSemantics(ToType),
360 llvm::APFloat::rmNearestTiesToEven, &ignored);
361 // If there was no overflow, the source value is within the range of
362 // values that can be represented.
Richard Smithf6028062012-03-23 23:55:39 +0000363 if (ConvertStatus & llvm::APFloat::opOverflow) {
364 ConstantType = Initializer->getType();
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000365 return NK_Constant_Narrowing;
Richard Smithf6028062012-03-23 23:55:39 +0000366 }
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000367 } else {
368 return NK_Variable_Narrowing;
369 }
370 }
371 return NK_Not_Narrowing;
372
373 // -- from an integer type or unscoped enumeration type to an integer type
374 // that cannot represent all the values of the original type, except where
375 // the source is a constant expression and the actual value after
376 // conversion will fit into the target type and will produce the original
377 // value when converted back to the original type.
378 case ICK_Boolean_Conversion: // Bools are integers too.
379 if (!FromType->isIntegralOrUnscopedEnumerationType()) {
380 // Boolean conversions can be from pointers and pointers to members
381 // [conv.bool], and those aren't considered narrowing conversions.
382 return NK_Not_Narrowing;
383 } // Otherwise, fall through to the integral case.
384 case ICK_Integral_Conversion: {
385 assert(FromType->isIntegralOrUnscopedEnumerationType());
386 assert(ToType->isIntegralOrUnscopedEnumerationType());
387 const bool FromSigned = FromType->isSignedIntegerOrEnumerationType();
388 const unsigned FromWidth = Ctx.getIntWidth(FromType);
389 const bool ToSigned = ToType->isSignedIntegerOrEnumerationType();
390 const unsigned ToWidth = Ctx.getIntWidth(ToType);
391
392 if (FromWidth > ToWidth ||
Richard Smithcd65f492012-06-13 01:07:41 +0000393 (FromWidth == ToWidth && FromSigned != ToSigned) ||
394 (FromSigned && !ToSigned)) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000395 // Not all values of FromType can be represented in ToType.
396 llvm::APSInt InitializerValue;
397 const Expr *Initializer = IgnoreNarrowingConversion(Converted);
Richard Smithcd65f492012-06-13 01:07:41 +0000398 if (!Initializer->isIntegerConstantExpr(InitializerValue, Ctx)) {
399 // Such conversions on variables are always narrowing.
400 return NK_Variable_Narrowing;
Richard Smith5d7700e2012-06-19 21:28:35 +0000401 }
402 bool Narrowing = false;
403 if (FromWidth < ToWidth) {
Richard Smithcd65f492012-06-13 01:07:41 +0000404 // Negative -> unsigned is narrowing. Otherwise, more bits is never
405 // narrowing.
406 if (InitializerValue.isSigned() && InitializerValue.isNegative())
Richard Smith5d7700e2012-06-19 21:28:35 +0000407 Narrowing = true;
Richard Smithcd65f492012-06-13 01:07:41 +0000408 } else {
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000409 // Add a bit to the InitializerValue so we don't have to worry about
410 // signed vs. unsigned comparisons.
411 InitializerValue = InitializerValue.extend(
412 InitializerValue.getBitWidth() + 1);
413 // Convert the initializer to and from the target width and signed-ness.
414 llvm::APSInt ConvertedValue = InitializerValue;
415 ConvertedValue = ConvertedValue.trunc(ToWidth);
416 ConvertedValue.setIsSigned(ToSigned);
417 ConvertedValue = ConvertedValue.extend(InitializerValue.getBitWidth());
418 ConvertedValue.setIsSigned(InitializerValue.isSigned());
419 // If the result is different, this was a narrowing conversion.
Richard Smith5d7700e2012-06-19 21:28:35 +0000420 if (ConvertedValue != InitializerValue)
421 Narrowing = true;
422 }
423 if (Narrowing) {
424 ConstantType = Initializer->getType();
425 ConstantValue = APValue(InitializerValue);
426 return NK_Constant_Narrowing;
Richard Smith4c3fc9b2012-01-18 05:21:49 +0000427 }
428 }
429 return NK_Not_Narrowing;
430 }
431
432 default:
433 // Other kinds of conversions are not narrowings.
434 return NK_Not_Narrowing;
435 }
436}
437
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000438/// DebugPrint - Print this standard conversion sequence to standard
439/// error. Useful for debugging overloading issues.
440void StandardConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000441 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000442 bool PrintedSomething = false;
443 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000444 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000445 PrintedSomething = true;
446 }
447
448 if (Second != ICK_Identity) {
449 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000450 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000451 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000452 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000453
454 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000455 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000456 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000457 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000458 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000459 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000460 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000461 PrintedSomething = true;
462 }
463
464 if (Third != ICK_Identity) {
465 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000466 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000467 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000468 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000469 PrintedSomething = true;
470 }
471
472 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000473 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474 }
475}
476
477/// DebugPrint - Print this user-defined conversion sequence to standard
478/// error. Useful for debugging overloading issues.
479void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000480 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481 if (Before.First || Before.Second || Before.Third) {
482 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000483 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000484 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000485 if (ConversionFunction)
486 OS << '\'' << *ConversionFunction << '\'';
487 else
488 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000490 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491 After.DebugPrint();
492 }
493}
494
495/// DebugPrint - Print this implicit conversion sequence to standard
496/// error. Useful for debugging overloading issues.
497void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000498 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499 switch (ConversionKind) {
500 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000501 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 Standard.DebugPrint();
503 break;
504 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000505 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506 UserDefined.DebugPrint();
507 break;
508 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000509 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510 break;
John McCall1d318332010-01-12 00:44:57 +0000511 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000512 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000513 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000515 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 break;
517 }
518
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000519 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000520}
521
John McCall1d318332010-01-12 00:44:57 +0000522void AmbiguousConversionSequence::construct() {
523 new (&conversions()) ConversionSet();
524}
525
526void AmbiguousConversionSequence::destruct() {
527 conversions().~ConversionSet();
528}
529
530void
531AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
532 FromTypePtr = O.FromTypePtr;
533 ToTypePtr = O.ToTypePtr;
534 new (&conversions()) ConversionSet(O.conversions());
535}
536
Douglas Gregora9333192010-05-08 17:41:32 +0000537namespace {
538 // Structure used by OverloadCandidate::DeductionFailureInfo to store
539 // template parameter and template argument information.
540 struct DFIParamWithArguments {
541 TemplateParameter Param;
542 TemplateArgument FirstArg;
543 TemplateArgument SecondArg;
544 };
545}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000546
Douglas Gregora9333192010-05-08 17:41:32 +0000547/// \brief Convert from Sema's representation of template deduction information
548/// to the form used in overload-candidate information.
549OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000550static MakeDeductionFailureInfo(ASTContext &Context,
551 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000552 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000553 OverloadCandidate::DeductionFailureInfo Result;
554 Result.Result = static_cast<unsigned>(TDK);
Richard Smithb8590f32012-05-07 09:03:25 +0000555 Result.HasDiagnostic = false;
Douglas Gregora9333192010-05-08 17:41:32 +0000556 Result.Data = 0;
557 switch (TDK) {
558 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000559 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000560 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000561 case Sema::TDK_TooManyArguments:
562 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000563 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000564
Douglas Gregora9333192010-05-08 17:41:32 +0000565 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000566 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000567 Result.Data = Info.Param.getOpaqueValue();
568 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000569
Douglas Gregora9333192010-05-08 17:41:32 +0000570 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000571 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000572 // FIXME: Should allocate from normal heap so that we can free this later.
573 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000574 Saved->Param = Info.Param;
575 Saved->FirstArg = Info.FirstArg;
576 Saved->SecondArg = Info.SecondArg;
577 Result.Data = Saved;
578 break;
579 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000580
Douglas Gregora9333192010-05-08 17:41:32 +0000581 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000582 Result.Data = Info.take();
Richard Smithb8590f32012-05-07 09:03:25 +0000583 if (Info.hasSFINAEDiagnostic()) {
584 PartialDiagnosticAt *Diag = new (Result.Diagnostic) PartialDiagnosticAt(
585 SourceLocation(), PartialDiagnostic::NullDiagnostic());
586 Info.takeSFINAEDiagnostic(*Diag);
587 Result.HasDiagnostic = true;
588 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000589 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000590
Douglas Gregora9333192010-05-08 17:41:32 +0000591 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000592 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000593 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000594 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000595
Douglas Gregora9333192010-05-08 17:41:32 +0000596 return Result;
597}
John McCall1d318332010-01-12 00:44:57 +0000598
Douglas Gregora9333192010-05-08 17:41:32 +0000599void OverloadCandidate::DeductionFailureInfo::Destroy() {
600 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
601 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000602 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000603 case Sema::TDK_InstantiationDepth:
604 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000605 case Sema::TDK_TooManyArguments:
606 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000607 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000608 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000609
Douglas Gregora9333192010-05-08 17:41:32 +0000610 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000611 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000612 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000613 Data = 0;
614 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000615
616 case Sema::TDK_SubstitutionFailure:
Richard Smithb8590f32012-05-07 09:03:25 +0000617 // FIXME: Destroy the template argument list?
Douglas Gregorec20f462010-05-08 20:07:26 +0000618 Data = 0;
Richard Smithb8590f32012-05-07 09:03:25 +0000619 if (PartialDiagnosticAt *Diag = getSFINAEDiagnostic()) {
620 Diag->~PartialDiagnosticAt();
621 HasDiagnostic = false;
622 }
Douglas Gregorec20f462010-05-08 20:07:26 +0000623 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000624
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000625 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000626 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000627 case Sema::TDK_FailedOverloadResolution:
628 break;
629 }
630}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000631
Richard Smithb8590f32012-05-07 09:03:25 +0000632PartialDiagnosticAt *
633OverloadCandidate::DeductionFailureInfo::getSFINAEDiagnostic() {
634 if (HasDiagnostic)
635 return static_cast<PartialDiagnosticAt*>(static_cast<void*>(Diagnostic));
636 return 0;
637}
638
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000639TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000640OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
641 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
642 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000643 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000644 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000645 case Sema::TDK_TooManyArguments:
646 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000647 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000648 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000649
Douglas Gregora9333192010-05-08 17:41:32 +0000650 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000651 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000652 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000653
654 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000655 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000656 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000657
Douglas Gregora9333192010-05-08 17:41:32 +0000658 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000659 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000660 case Sema::TDK_FailedOverloadResolution:
661 break;
662 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000663
Douglas Gregora9333192010-05-08 17:41:32 +0000664 return TemplateParameter();
665}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000666
Douglas Gregorec20f462010-05-08 20:07:26 +0000667TemplateArgumentList *
668OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
669 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
670 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000671 case Sema::TDK_Invalid:
Douglas Gregorec20f462010-05-08 20:07:26 +0000672 case Sema::TDK_InstantiationDepth:
673 case Sema::TDK_TooManyArguments:
674 case Sema::TDK_TooFewArguments:
675 case Sema::TDK_Incomplete:
676 case Sema::TDK_InvalidExplicitArguments:
677 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000678 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000679 return 0;
680
681 case Sema::TDK_SubstitutionFailure:
682 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000683
Douglas Gregorec20f462010-05-08 20:07:26 +0000684 // Unhandled
685 case Sema::TDK_NonDeducedMismatch:
686 case Sema::TDK_FailedOverloadResolution:
687 break;
688 }
689
690 return 0;
691}
692
Douglas Gregora9333192010-05-08 17:41:32 +0000693const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
694 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
695 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000696 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000697 case Sema::TDK_InstantiationDepth:
698 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000699 case Sema::TDK_TooManyArguments:
700 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000701 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000702 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000703 return 0;
704
Douglas Gregora9333192010-05-08 17:41:32 +0000705 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000706 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000707 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000708
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000709 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000710 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000711 case Sema::TDK_FailedOverloadResolution:
712 break;
713 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000714
Douglas Gregora9333192010-05-08 17:41:32 +0000715 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000716}
Douglas Gregora9333192010-05-08 17:41:32 +0000717
718const TemplateArgument *
719OverloadCandidate::DeductionFailureInfo::getSecondArg() {
720 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
721 case Sema::TDK_Success:
Douglas Gregorae19fbb2012-09-13 21:01:57 +0000722 case Sema::TDK_Invalid:
Douglas Gregora9333192010-05-08 17:41:32 +0000723 case Sema::TDK_InstantiationDepth:
724 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000725 case Sema::TDK_TooManyArguments:
726 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000727 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000728 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000729 return 0;
730
Douglas Gregora9333192010-05-08 17:41:32 +0000731 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000732 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000733 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
734
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000735 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000736 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000737 case Sema::TDK_FailedOverloadResolution:
738 break;
739 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000740
Douglas Gregora9333192010-05-08 17:41:32 +0000741 return 0;
742}
743
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000744void OverloadCandidateSet::destroyCandidates() {
Richard Smithe3898ac2012-07-18 23:52:59 +0000745 for (iterator i = begin(), e = end(); i != e; ++i) {
Benjamin Kramer9e2822b2012-01-14 20:16:52 +0000746 for (unsigned ii = 0, ie = i->NumConversions; ii != ie; ++ii)
747 i->Conversions[ii].~ImplicitConversionSequence();
Richard Smithe3898ac2012-07-18 23:52:59 +0000748 if (!i->Viable && i->FailureKind == ovl_fail_bad_deduction)
749 i->DeductionFailure.Destroy();
750 }
Benjamin Kramerf5b132f2012-10-09 15:52:25 +0000751}
752
753void OverloadCandidateSet::clear() {
754 destroyCandidates();
Benjamin Kramer314f5542012-01-14 19:31:39 +0000755 NumInlineSequences = 0;
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +0000756 Candidates.clear();
Douglas Gregora9333192010-05-08 17:41:32 +0000757 Functions.clear();
758}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000759
John McCall5acb0c92011-10-17 18:40:02 +0000760namespace {
761 class UnbridgedCastsSet {
762 struct Entry {
763 Expr **Addr;
764 Expr *Saved;
765 };
766 SmallVector<Entry, 2> Entries;
767
768 public:
769 void save(Sema &S, Expr *&E) {
770 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
771 Entry entry = { &E, E };
772 Entries.push_back(entry);
773 E = S.stripARCUnbridgedCast(E);
774 }
775
776 void restore() {
777 for (SmallVectorImpl<Entry>::iterator
778 i = Entries.begin(), e = Entries.end(); i != e; ++i)
779 *i->Addr = i->Saved;
780 }
781 };
782}
783
784/// checkPlaceholderForOverload - Do any interesting placeholder-like
785/// preprocessing on the given expression.
786///
787/// \param unbridgedCasts a collection to which to add unbridged casts;
788/// without this, they will be immediately diagnosed as errors
789///
790/// Return true on unrecoverable error.
791static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
792 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000793 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
794 // We can't handle overloaded expressions here because overload
795 // resolution might reasonably tweak them.
796 if (placeholder->getKind() == BuiltinType::Overload) return false;
797
798 // If the context potentially accepts unbridged ARC casts, strip
799 // the unbridged cast and add it to the collection for later restoration.
800 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
801 unbridgedCasts) {
802 unbridgedCasts->save(S, E);
803 return false;
804 }
805
806 // Go ahead and check everything else.
807 ExprResult result = S.CheckPlaceholderExpr(E);
808 if (result.isInvalid())
809 return true;
810
811 E = result.take();
812 return false;
813 }
814
815 // Nothing to do.
816 return false;
817}
818
819/// checkArgPlaceholdersForOverload - Check a set of call operands for
820/// placeholders.
821static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
822 unsigned numArgs,
823 UnbridgedCastsSet &unbridged) {
824 for (unsigned i = 0; i != numArgs; ++i)
825 if (checkPlaceholderForOverload(S, args[i], &unbridged))
826 return true;
827
828 return false;
829}
830
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000831// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000832// overload of the declarations in Old. This routine returns false if
833// New and Old cannot be overloaded, e.g., if New has the same
834// signature as some function in Old (C++ 1.3.10) or if the Old
835// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000836// it does return false, MatchedDecl will point to the decl that New
837// cannot be overloaded with. This decl may be a UsingShadowDecl on
838// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000839//
840// Example: Given the following input:
841//
842// void f(int, float); // #1
843// void f(int, int); // #2
844// int f(int, int); // #3
845//
846// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000847// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000848//
John McCall51fa86f2009-12-02 08:47:38 +0000849// When we process #2, Old contains only the FunctionDecl for #1. By
850// comparing the parameter types, we see that #1 and #2 are overloaded
851// (since they have different signatures), so this routine returns
852// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000853//
John McCall51fa86f2009-12-02 08:47:38 +0000854// When we process #3, Old is an overload set containing #1 and #2. We
855// compare the signatures of #3 to #1 (they're overloaded, so we do
856// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
857// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000858// signature), IsOverload returns false and MatchedDecl will be set to
859// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000860//
861// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
862// into a class by a using declaration. The rules for whether to hide
863// shadow declarations ignore some properties which otherwise figure
864// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000865Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000866Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
867 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000868 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000869 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000870 NamedDecl *OldD = *I;
871
872 bool OldIsUsingDecl = false;
873 if (isa<UsingShadowDecl>(OldD)) {
874 OldIsUsingDecl = true;
875
876 // We can always introduce two using declarations into the same
877 // context, even if they have identical signatures.
878 if (NewIsUsingDecl) continue;
879
880 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
881 }
882
883 // If either declaration was introduced by a using declaration,
884 // we'll need to use slightly different rules for matching.
885 // Essentially, these rules are the normal rules, except that
886 // function templates hide function templates with different
887 // return types or template parameter lists.
888 bool UseMemberUsingDeclRules =
889 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
890
John McCall51fa86f2009-12-02 08:47:38 +0000891 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000892 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
893 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
894 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
895 continue;
896 }
897
John McCall871b2e72009-12-09 03:35:25 +0000898 Match = *I;
899 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000900 }
John McCall51fa86f2009-12-02 08:47:38 +0000901 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000902 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
903 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
904 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
905 continue;
906 }
907
John McCall871b2e72009-12-09 03:35:25 +0000908 Match = *I;
909 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000910 }
John McCalld7945c62010-11-10 03:01:53 +0000911 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000912 // We can overload with these, which can show up when doing
913 // redeclaration checks for UsingDecls.
914 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000915 } else if (isa<TagDecl>(OldD)) {
916 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000917 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
918 // Optimistically assume that an unresolved using decl will
919 // overload; if it doesn't, we'll have to diagnose during
920 // template instantiation.
921 } else {
John McCall68263142009-11-18 22:49:29 +0000922 // (C++ 13p1):
923 // Only function declarations can be overloaded; object and type
924 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000925 Match = *I;
926 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000927 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000928 }
John McCall68263142009-11-18 22:49:29 +0000929
John McCall871b2e72009-12-09 03:35:25 +0000930 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000931}
932
Rafael Espindola78eeba82012-12-28 14:21:58 +0000933static bool canBeOverloaded(const FunctionDecl &D) {
934 if (D.getAttr<OverloadableAttr>())
935 return true;
936 if (D.hasCLanguageLinkage())
937 return false;
938 return true;
939}
940
John McCallad00b772010-06-16 08:42:20 +0000941bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
942 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000943 // If both of the functions are extern "C", then they are not
944 // overloads.
Rafael Espindola78eeba82012-12-28 14:21:58 +0000945 if (!canBeOverloaded(*Old) && !canBeOverloaded(*New))
John McCall7b492022010-08-12 07:09:11 +0000946 return false;
947
John McCall68263142009-11-18 22:49:29 +0000948 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
949 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
950
951 // C++ [temp.fct]p2:
952 // A function template can be overloaded with other function templates
953 // and with normal (non-template) functions.
954 if ((OldTemplate == 0) != (NewTemplate == 0))
955 return true;
956
957 // Is the function New an overload of the function Old?
958 QualType OldQType = Context.getCanonicalType(Old->getType());
959 QualType NewQType = Context.getCanonicalType(New->getType());
960
961 // Compare the signatures (C++ 1.3.10) of the two functions to
962 // determine whether they are overloads. If we find any mismatch
963 // in the signature, they are overloads.
964
965 // If either of these functions is a K&R-style function (no
966 // prototype), then we consider them to have matching signatures.
967 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
968 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
969 return false;
970
John McCallf4c73712011-01-19 06:33:43 +0000971 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
972 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000973
974 // The signature of a function includes the types of its
975 // parameters (C++ 1.3.10), which includes the presence or absence
976 // of the ellipsis; see C++ DR 357).
977 if (OldQType != NewQType &&
978 (OldType->getNumArgs() != NewType->getNumArgs() ||
979 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000980 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000981 return true;
982
983 // C++ [temp.over.link]p4:
984 // The signature of a function template consists of its function
985 // signature, its return type and its template parameter list. The names
986 // of the template parameters are significant only for establishing the
987 // relationship between the template parameters and the rest of the
988 // signature.
989 //
990 // We check the return type and template parameter lists for function
991 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000992 //
993 // However, we don't consider either of these when deciding whether
994 // a member introduced by a shadow declaration is hidden.
995 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000996 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
997 OldTemplate->getTemplateParameters(),
998 false, TPL_TemplateMatch) ||
999 OldType->getResultType() != NewType->getResultType()))
1000 return true;
1001
1002 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001003 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +00001004 //
1005 // As part of this, also check whether one of the member functions
1006 // is static, in which case they are not overloads (C++
1007 // 13.1p2). While not part of the definition of the signature,
1008 // this check is important to determine whether these functions
1009 // can be overloaded.
1010 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1011 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1012 if (OldMethod && NewMethod &&
1013 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001014 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +00001015 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1016 if (!UseUsingDeclRules &&
1017 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1018 (OldMethod->getRefQualifier() == RQ_None ||
1019 NewMethod->getRefQualifier() == RQ_None)) {
1020 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001021 // - Member function declarations with the same name and the same
1022 // parameter-type-list as well as member function template
1023 // declarations with the same name, the same parameter-type-list, and
1024 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +00001025 // them, but not all, have a ref-qualifier (8.3.5).
1026 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1027 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1028 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1029 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001030
John McCall68263142009-11-18 22:49:29 +00001031 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001032 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001033
John McCall68263142009-11-18 22:49:29 +00001034 // The signatures match; this is not an overload.
1035 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001036}
1037
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001038/// \brief Checks availability of the function depending on the current
1039/// function context. Inside an unavailable function, unavailability is ignored.
1040///
1041/// \returns true if \arg FD is unavailable and current context is inside
1042/// an available function, false otherwise.
1043bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1044 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1045}
1046
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001047/// \brief Tries a user-defined conversion from From to ToType.
1048///
1049/// Produces an implicit conversion sequence for when a standard conversion
1050/// is not an option. See TryImplicitConversion for more information.
1051static ImplicitConversionSequence
1052TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1053 bool SuppressUserConversions,
1054 bool AllowExplicit,
1055 bool InOverloadResolution,
1056 bool CStyle,
1057 bool AllowObjCWritebackConversion) {
1058 ImplicitConversionSequence ICS;
1059
1060 if (SuppressUserConversions) {
1061 // We're not in the case above, so there is no conversion that
1062 // we can perform.
1063 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1064 return ICS;
1065 }
1066
1067 // Attempt user-defined conversion.
1068 OverloadCandidateSet Conversions(From->getExprLoc());
1069 OverloadingResult UserDefResult
1070 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1071 AllowExplicit);
1072
1073 if (UserDefResult == OR_Success) {
1074 ICS.setUserDefined();
1075 // C++ [over.ics.user]p4:
1076 // A conversion of an expression of class type to the same class
1077 // type is given Exact Match rank, and a conversion of an
1078 // expression of class type to a base class of that type is
1079 // given Conversion rank, in spite of the fact that a copy
1080 // constructor (i.e., a user-defined conversion function) is
1081 // called for those cases.
1082 if (CXXConstructorDecl *Constructor
1083 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1084 QualType FromCanon
1085 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1086 QualType ToCanon
1087 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1088 if (Constructor->isCopyConstructor() &&
1089 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1090 // Turn this into a "standard" conversion sequence, so that it
1091 // gets ranked with standard conversion sequences.
1092 ICS.setStandard();
1093 ICS.Standard.setAsIdentityConversion();
1094 ICS.Standard.setFromType(From->getType());
1095 ICS.Standard.setAllToTypes(ToType);
1096 ICS.Standard.CopyConstructor = Constructor;
1097 if (ToCanon != FromCanon)
1098 ICS.Standard.Second = ICK_Derived_To_Base;
1099 }
1100 }
1101
1102 // C++ [over.best.ics]p4:
1103 // However, when considering the argument of a user-defined
1104 // conversion function that is a candidate by 13.3.1.3 when
1105 // invoked for the copying of the temporary in the second step
1106 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1107 // 13.3.1.6 in all cases, only standard conversion sequences and
1108 // ellipsis conversion sequences are allowed.
1109 if (SuppressUserConversions && ICS.isUserDefined()) {
1110 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1111 }
1112 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1113 ICS.setAmbiguous();
1114 ICS.Ambiguous.setFromType(From->getType());
1115 ICS.Ambiguous.setToType(ToType);
1116 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1117 Cand != Conversions.end(); ++Cand)
1118 if (Cand->Viable)
1119 ICS.Ambiguous.addConversion(Cand->Function);
1120 } else {
1121 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1122 }
1123
1124 return ICS;
1125}
1126
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001127/// TryImplicitConversion - Attempt to perform an implicit conversion
1128/// from the given expression (Expr) to the given type (ToType). This
1129/// function returns an implicit conversion sequence that can be used
1130/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001131///
1132/// void f(float f);
1133/// void g(int i) { f(i); }
1134///
1135/// this routine would produce an implicit conversion sequence to
1136/// describe the initialization of f from i, which will be a standard
1137/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1138/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1139//
1140/// Note that this routine only determines how the conversion can be
1141/// performed; it does not actually perform the conversion. As such,
1142/// it will not produce any diagnostics if no conversion is available,
1143/// but will instead return an implicit conversion sequence of kind
1144/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001145///
1146/// If @p SuppressUserConversions, then user-defined conversions are
1147/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001148/// If @p AllowExplicit, then explicit user-defined conversions are
1149/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001150///
1151/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1152/// writeback conversion, which allows __autoreleasing id* parameters to
1153/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001154static ImplicitConversionSequence
1155TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1156 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001157 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001158 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001159 bool CStyle,
1160 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001161 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001162 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001163 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001164 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001165 return ICS;
1166 }
1167
David Blaikie4e4d0842012-03-11 07:00:24 +00001168 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001169 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001170 return ICS;
1171 }
1172
Douglas Gregor604eb652010-08-11 02:15:33 +00001173 // C++ [over.ics.user]p4:
1174 // A conversion of an expression of class type to the same class
1175 // type is given Exact Match rank, and a conversion of an
1176 // expression of class type to a base class of that type is
1177 // given Conversion rank, in spite of the fact that a copy/move
1178 // constructor (i.e., a user-defined conversion function) is
1179 // called for those cases.
1180 QualType FromType = From->getType();
1181 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001182 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1183 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001184 ICS.setStandard();
1185 ICS.Standard.setAsIdentityConversion();
1186 ICS.Standard.setFromType(FromType);
1187 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001188
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001189 // We don't actually check at this point whether there is a valid
1190 // copy/move constructor, since overloading just assumes that it
1191 // exists. When we actually perform initialization, we'll find the
1192 // appropriate constructor to copy the returned object, if needed.
1193 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001194
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001195 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001196 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001197 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001198
Douglas Gregor604eb652010-08-11 02:15:33 +00001199 return ICS;
1200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001201
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001202 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1203 AllowExplicit, InOverloadResolution, CStyle,
1204 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001205}
1206
John McCallf85e1932011-06-15 23:02:42 +00001207ImplicitConversionSequence
1208Sema::TryImplicitConversion(Expr *From, QualType ToType,
1209 bool SuppressUserConversions,
1210 bool AllowExplicit,
1211 bool InOverloadResolution,
1212 bool CStyle,
1213 bool AllowObjCWritebackConversion) {
1214 return clang::TryImplicitConversion(*this, From, ToType,
1215 SuppressUserConversions, AllowExplicit,
1216 InOverloadResolution, CStyle,
1217 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001218}
1219
Douglas Gregor575c63a2010-04-16 22:27:05 +00001220/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001221/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001222/// converted expression. Flavor is the kind of conversion we're
1223/// performing, used in the error message. If @p AllowExplicit,
1224/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001225ExprResult
1226Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001227 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001228 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001229 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001230}
1231
John Wiegley429bb272011-04-08 18:41:53 +00001232ExprResult
1233Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001234 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001235 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001236 if (checkPlaceholderForOverload(*this, From))
1237 return ExprError();
1238
John McCallf85e1932011-06-15 23:02:42 +00001239 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1240 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001241 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001242 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001243
John McCall120d63c2010-08-24 20:38:10 +00001244 ICS = clang::TryImplicitConversion(*this, From, ToType,
1245 /*SuppressUserConversions=*/false,
1246 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001247 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001248 /*CStyle=*/false,
1249 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001250 return PerformImplicitConversion(From, ToType, ICS, Action);
1251}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001252
1253/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001254/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001255bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1256 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001257 if (Context.hasSameUnqualifiedType(FromType, ToType))
1258 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001259
John McCall00ccbef2010-12-21 00:44:39 +00001260 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1261 // where F adds one of the following at most once:
1262 // - a pointer
1263 // - a member pointer
1264 // - a block pointer
1265 CanQualType CanTo = Context.getCanonicalType(ToType);
1266 CanQualType CanFrom = Context.getCanonicalType(FromType);
1267 Type::TypeClass TyClass = CanTo->getTypeClass();
1268 if (TyClass != CanFrom->getTypeClass()) return false;
1269 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1270 if (TyClass == Type::Pointer) {
1271 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1272 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1273 } else if (TyClass == Type::BlockPointer) {
1274 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1275 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1276 } else if (TyClass == Type::MemberPointer) {
1277 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1278 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1279 } else {
1280 return false;
1281 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001282
John McCall00ccbef2010-12-21 00:44:39 +00001283 TyClass = CanTo->getTypeClass();
1284 if (TyClass != CanFrom->getTypeClass()) return false;
1285 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1286 return false;
1287 }
1288
1289 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1290 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1291 if (!EInfo.getNoReturn()) return false;
1292
1293 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1294 assert(QualType(FromFn, 0).isCanonical());
1295 if (QualType(FromFn, 0) != CanTo) return false;
1296
1297 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001298 return true;
1299}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001300
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001301/// \brief Determine whether the conversion from FromType to ToType is a valid
1302/// vector conversion.
1303///
1304/// \param ICK Will be set to the vector conversion kind, if this is a vector
1305/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001306static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1307 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001308 // We need at least one of these types to be a vector type to have a vector
1309 // conversion.
1310 if (!ToType->isVectorType() && !FromType->isVectorType())
1311 return false;
1312
1313 // Identical types require no conversions.
1314 if (Context.hasSameUnqualifiedType(FromType, ToType))
1315 return false;
1316
1317 // There are no conversions between extended vector types, only identity.
1318 if (ToType->isExtVectorType()) {
1319 // There are no conversions between extended vector types other than the
1320 // identity conversion.
1321 if (FromType->isExtVectorType())
1322 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001323
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001324 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001325 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001326 ICK = ICK_Vector_Splat;
1327 return true;
1328 }
1329 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001330
1331 // We can perform the conversion between vector types in the following cases:
1332 // 1)vector types are equivalent AltiVec and GCC vector types
1333 // 2)lax vector conversions are permitted and the vector types are of the
1334 // same size
1335 if (ToType->isVectorType() && FromType->isVectorType()) {
1336 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001337 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001338 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001339 ICK = ICK_Vector_Conversion;
1340 return true;
1341 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001342 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001343
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001344 return false;
1345}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001346
Douglas Gregor7d000652012-04-12 20:48:09 +00001347static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1348 bool InOverloadResolution,
1349 StandardConversionSequence &SCS,
1350 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001351
Douglas Gregor60d62c22008-10-31 16:23:19 +00001352/// IsStandardConversion - Determines whether there is a standard
1353/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1354/// expression From to the type ToType. Standard conversion sequences
1355/// only consider non-class types; for conversions that involve class
1356/// types, use TryImplicitConversion. If a conversion exists, SCS will
1357/// contain the standard conversion sequence required to perform this
1358/// conversion and this routine will return true. Otherwise, this
1359/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001360static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1361 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001362 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001363 bool CStyle,
1364 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001365 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001366
Douglas Gregor60d62c22008-10-31 16:23:19 +00001367 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001368 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001369 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001370 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001371 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001372 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001373
Douglas Gregorf9201e02009-02-11 23:02:49 +00001374 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001375 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001376 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001377 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001378 return false;
1379
Mike Stump1eb44332009-09-09 15:08:12 +00001380 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001381 }
1382
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001383 // The first conversion can be an lvalue-to-rvalue conversion,
1384 // array-to-pointer conversion, or function-to-pointer conversion
1385 // (C++ 4p1).
1386
John McCall120d63c2010-08-24 20:38:10 +00001387 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001388 DeclAccessPair AccessPair;
1389 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001390 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001391 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001392 // We were able to resolve the address of the overloaded function,
1393 // so we can convert to the type of that function.
1394 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001395
1396 // we can sometimes resolve &foo<int> regardless of ToType, so check
1397 // if the type matches (identity) or we are converting to bool
1398 if (!S.Context.hasSameUnqualifiedType(
1399 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1400 QualType resultTy;
1401 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001402 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001403 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1404 // otherwise, only a boolean conversion is standard
1405 if (!ToType->isBooleanType())
1406 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001407 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001408
Chandler Carruth90434232011-03-29 08:08:18 +00001409 // Check if the "from" expression is taking the address of an overloaded
1410 // function and recompute the FromType accordingly. Take advantage of the
1411 // fact that non-static member functions *must* have such an address-of
1412 // expression.
1413 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1414 if (Method && !Method->isStatic()) {
1415 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1416 "Non-unary operator on non-static member address");
1417 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1418 == UO_AddrOf &&
1419 "Non-address-of operator on non-static member address");
1420 const Type *ClassType
1421 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1422 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001423 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1424 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1425 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001426 "Non-address-of operator for overloaded function expression");
1427 FromType = S.Context.getPointerType(FromType);
1428 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001429
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001430 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001431 assert(S.Context.hasSameType(
1432 FromType,
1433 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001434 } else {
1435 return false;
1436 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001437 }
John McCall21480112011-08-30 00:57:29 +00001438 // Lvalue-to-rvalue conversion (C++11 4.1):
1439 // A glvalue (3.10) of a non-function, non-array type T can
1440 // be converted to a prvalue.
1441 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001442 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001443 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001444 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001445 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001446
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001447 // C11 6.3.2.1p2:
1448 // ... if the lvalue has atomic type, the value has the non-atomic version
1449 // of the type of the lvalue ...
1450 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1451 FromType = Atomic->getValueType();
1452
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001453 // If T is a non-class type, the type of the rvalue is the
1454 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001455 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1456 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001457 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001458 } else if (FromType->isArrayType()) {
1459 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001460 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001461
1462 // An lvalue or rvalue of type "array of N T" or "array of unknown
1463 // bound of T" can be converted to an rvalue of type "pointer to
1464 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001465 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001466
John McCall120d63c2010-08-24 20:38:10 +00001467 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001468 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001469 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001470
1471 // For the purpose of ranking in overload resolution
1472 // (13.3.3.1.1), this conversion is considered an
1473 // array-to-pointer conversion followed by a qualification
1474 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001475 SCS.Second = ICK_Identity;
1476 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001477 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001478 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001479 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001480 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001481 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001482 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001483 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001484
1485 // An lvalue of function type T can be converted to an rvalue of
1486 // type "pointer to T." The result is a pointer to the
1487 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001488 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001489 } else {
1490 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001491 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001492 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001493 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001494
1495 // The second conversion can be an integral promotion, floating
1496 // point promotion, integral conversion, floating point conversion,
1497 // floating-integral conversion, pointer conversion,
1498 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001499 // For overloading in C, this can also be a "compatible-type"
1500 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001501 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001502 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001503 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001504 // The unqualified versions of the types are the same: there's no
1505 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001506 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001507 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001508 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001509 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001510 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001511 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001512 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001513 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001514 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001515 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001516 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001517 SCS.Second = ICK_Complex_Promotion;
1518 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001519 } else if (ToType->isBooleanType() &&
1520 (FromType->isArithmeticType() ||
1521 FromType->isAnyPointerType() ||
1522 FromType->isBlockPointerType() ||
1523 FromType->isMemberPointerType() ||
1524 FromType->isNullPtrType())) {
1525 // Boolean conversions (C++ 4.12).
1526 SCS.Second = ICK_Boolean_Conversion;
1527 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001528 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001529 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001530 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001531 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001532 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001533 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001534 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001535 SCS.Second = ICK_Complex_Conversion;
1536 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001537 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1538 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001539 // Complex-real conversions (C99 6.3.1.7)
1540 SCS.Second = ICK_Complex_Real;
1541 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001542 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001543 // Floating point conversions (C++ 4.8).
1544 SCS.Second = ICK_Floating_Conversion;
1545 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001546 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001547 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001548 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001549 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001550 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001551 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001552 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001553 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001554 SCS.Second = ICK_Block_Pointer_Conversion;
1555 } else if (AllowObjCWritebackConversion &&
1556 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1557 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001558 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1559 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001560 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001561 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001562 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001563 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001564 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001565 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001566 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001567 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001568 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001569 SCS.Second = SecondICK;
1570 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001571 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001572 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001573 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001574 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001575 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001576 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001577 // Treat a conversion that strips "noreturn" as an identity conversion.
1578 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001579 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1580 InOverloadResolution,
1581 SCS, CStyle)) {
1582 SCS.Second = ICK_TransparentUnionConversion;
1583 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001584 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1585 CStyle)) {
1586 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001587 // appropriately.
1588 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001589 } else {
1590 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001591 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001592 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001593 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001594
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001595 QualType CanonFrom;
1596 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001597 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001598 bool ObjCLifetimeConversion;
1599 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1600 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001601 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001602 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001603 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001604 CanonFrom = S.Context.getCanonicalType(FromType);
1605 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001606 } else {
1607 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001608 SCS.Third = ICK_Identity;
1609
Mike Stump1eb44332009-09-09 15:08:12 +00001610 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001611 // [...] Any difference in top-level cv-qualification is
1612 // subsumed by the initialization itself and does not constitute
1613 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001614 CanonFrom = S.Context.getCanonicalType(FromType);
1615 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001616 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001617 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001618 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001619 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1620 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001621 FromType = ToType;
1622 CanonFrom = CanonTo;
1623 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001624 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001625 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001626
1627 // If we have not converted the argument type to the parameter type,
1628 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001629 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001630 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001631
Douglas Gregor60d62c22008-10-31 16:23:19 +00001632 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001633}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001634
1635static bool
1636IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1637 QualType &ToType,
1638 bool InOverloadResolution,
1639 StandardConversionSequence &SCS,
1640 bool CStyle) {
1641
1642 const RecordType *UT = ToType->getAsUnionType();
1643 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1644 return false;
1645 // The field to initialize within the transparent union.
1646 RecordDecl *UD = UT->getDecl();
1647 // It's compatible if the expression matches any of the fields.
1648 for (RecordDecl::field_iterator it = UD->field_begin(),
1649 itend = UD->field_end();
1650 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001651 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1652 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001653 ToType = it->getType();
1654 return true;
1655 }
1656 }
1657 return false;
1658}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001659
1660/// IsIntegralPromotion - Determines whether the conversion from the
1661/// expression From (whose potentially-adjusted type is FromType) to
1662/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1663/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001664bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001665 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001666 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001667 if (!To) {
1668 return false;
1669 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670
1671 // An rvalue of type char, signed char, unsigned char, short int, or
1672 // unsigned short int can be converted to an rvalue of type int if
1673 // int can represent all the values of the source type; otherwise,
1674 // the source rvalue can be converted to an rvalue of type unsigned
1675 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001676 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1677 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001678 if (// We can promote any signed, promotable integer type to an int
1679 (FromType->isSignedIntegerType() ||
1680 // We can promote any unsigned integer type whose size is
1681 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001682 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001683 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001684 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001685 }
1686
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001687 return To->getKind() == BuiltinType::UInt;
1688 }
1689
Richard Smithe7ff9192012-09-13 21:18:54 +00001690 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001691 // A prvalue of an unscoped enumeration type whose underlying type is not
1692 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1693 // following types that can represent all the values of the enumeration
1694 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1695 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001696 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001697 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001698 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001699 // with lowest integer conversion rank (4.13) greater than the rank of long
1700 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001701 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001702 // C++11 [conv.prom]p4:
1703 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1704 // can be converted to a prvalue of its underlying type. Moreover, if
1705 // integral promotion can be applied to its underlying type, a prvalue of an
1706 // unscoped enumeration type whose underlying type is fixed can also be
1707 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001708 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1709 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1710 // provided for a scoped enumeration.
1711 if (FromEnumType->getDecl()->isScoped())
1712 return false;
1713
Richard Smithe7ff9192012-09-13 21:18:54 +00001714 // We can perform an integral promotion to the underlying type of the enum,
1715 // even if that's not the promoted type.
1716 if (FromEnumType->getDecl()->isFixed()) {
1717 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1718 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1719 IsIntegralPromotion(From, Underlying, ToType);
1720 }
1721
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001722 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001723 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001724 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001725 return Context.hasSameUnqualifiedType(ToType,
1726 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001727 }
John McCall842aef82009-12-09 09:09:27 +00001728
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001729 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1731 // to an rvalue a prvalue of the first of the following types that can
1732 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001733 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001734 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001735 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001736 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001737 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001738 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001739 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001740 // Determine whether the type we're converting from is signed or
1741 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001742 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001743 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001744
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001745 // The types we'll try to promote to, in the appropriate
1746 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001747 QualType PromoteTypes[6] = {
1748 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001749 Context.LongTy, Context.UnsignedLongTy ,
1750 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001751 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001752 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001753 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1754 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001755 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001756 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1757 // We found the type that we can promote to. If this is the
1758 // type we wanted, we have a promotion. Otherwise, no
1759 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001760 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001761 }
1762 }
1763 }
1764
1765 // An rvalue for an integral bit-field (9.6) can be converted to an
1766 // rvalue of type int if int can represent all the values of the
1767 // bit-field; otherwise, it can be converted to unsigned int if
1768 // unsigned int can represent all the values of the bit-field. If
1769 // the bit-field is larger yet, no integral promotion applies to
1770 // it. If the bit-field has an enumerated type, it is treated as any
1771 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001772 // FIXME: We should delay checking of bit-fields until we actually perform the
1773 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001774 using llvm::APSInt;
1775 if (From)
1776 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001777 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001778 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001779 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1780 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1781 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001782
Douglas Gregor86f19402008-12-20 23:49:58 +00001783 // Are we promoting to an int from a bitfield that fits in an int?
1784 if (BitWidth < ToSize ||
1785 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1786 return To->getKind() == BuiltinType::Int;
1787 }
Mike Stump1eb44332009-09-09 15:08:12 +00001788
Douglas Gregor86f19402008-12-20 23:49:58 +00001789 // Are we promoting to an unsigned int from an unsigned bitfield
1790 // that fits into an unsigned int?
1791 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1792 return To->getKind() == BuiltinType::UInt;
1793 }
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Douglas Gregor86f19402008-12-20 23:49:58 +00001795 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001796 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001797 }
Mike Stump1eb44332009-09-09 15:08:12 +00001798
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001799 // An rvalue of type bool can be converted to an rvalue of type int,
1800 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001801 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001802 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001803 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001804
1805 return false;
1806}
1807
1808/// IsFloatingPointPromotion - Determines whether the conversion from
1809/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1810/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001811bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001812 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1813 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001814 /// An rvalue of type float can be converted to an rvalue of type
1815 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001816 if (FromBuiltin->getKind() == BuiltinType::Float &&
1817 ToBuiltin->getKind() == BuiltinType::Double)
1818 return true;
1819
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001820 // C99 6.3.1.5p1:
1821 // When a float is promoted to double or long double, or a
1822 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001823 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001824 (FromBuiltin->getKind() == BuiltinType::Float ||
1825 FromBuiltin->getKind() == BuiltinType::Double) &&
1826 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1827 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001828
1829 // Half can be promoted to float.
1830 if (FromBuiltin->getKind() == BuiltinType::Half &&
1831 ToBuiltin->getKind() == BuiltinType::Float)
1832 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001833 }
1834
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001835 return false;
1836}
1837
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001838/// \brief Determine if a conversion is a complex promotion.
1839///
1840/// A complex promotion is defined as a complex -> complex conversion
1841/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001842/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001843bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001844 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001845 if (!FromComplex)
1846 return false;
1847
John McCall183700f2009-09-21 23:43:11 +00001848 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001849 if (!ToComplex)
1850 return false;
1851
1852 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001853 ToComplex->getElementType()) ||
1854 IsIntegralPromotion(0, FromComplex->getElementType(),
1855 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001856}
1857
Douglas Gregorcb7de522008-11-26 23:31:11 +00001858/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1859/// the pointer type FromPtr to a pointer to type ToPointee, with the
1860/// same type qualifiers as FromPtr has on its pointee type. ToType,
1861/// if non-empty, will be a pointer to ToType that may or may not have
1862/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001863///
Mike Stump1eb44332009-09-09 15:08:12 +00001864static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001865BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001866 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001867 ASTContext &Context,
1868 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001869 assert((FromPtr->getTypeClass() == Type::Pointer ||
1870 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1871 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001872
John McCallf85e1932011-06-15 23:02:42 +00001873 /// Conversions to 'id' subsume cv-qualifier conversions.
1874 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001875 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001876
1877 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001878 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001879 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001880 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001881
John McCallf85e1932011-06-15 23:02:42 +00001882 if (StripObjCLifetime)
1883 Quals.removeObjCLifetime();
1884
Mike Stump1eb44332009-09-09 15:08:12 +00001885 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001886 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001887 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001888 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001889 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001890
1891 // Build a pointer to ToPointee. It has the right qualifiers
1892 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001893 if (isa<ObjCObjectPointerType>(ToType))
1894 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001895 return Context.getPointerType(ToPointee);
1896 }
1897
1898 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001899 QualType QualifiedCanonToPointee
1900 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001901
Douglas Gregorda80f742010-12-01 21:43:58 +00001902 if (isa<ObjCObjectPointerType>(ToType))
1903 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1904 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001905}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001906
Mike Stump1eb44332009-09-09 15:08:12 +00001907static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001908 bool InOverloadResolution,
1909 ASTContext &Context) {
1910 // Handle value-dependent integral null pointer constants correctly.
1911 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1912 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001913 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001914 return !InOverloadResolution;
1915
Douglas Gregorce940492009-09-25 04:25:58 +00001916 return Expr->isNullPointerConstant(Context,
1917 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1918 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001919}
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001921/// IsPointerConversion - Determines whether the conversion of the
1922/// expression From, which has the (possibly adjusted) type FromType,
1923/// can be converted to the type ToType via a pointer conversion (C++
1924/// 4.10). If so, returns true and places the converted type (that
1925/// might differ from ToType in its cv-qualifiers at some level) into
1926/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001927///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001928/// This routine also supports conversions to and from block pointers
1929/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1930/// pointers to interfaces. FIXME: Once we've determined the
1931/// appropriate overloading rules for Objective-C, we may want to
1932/// split the Objective-C checks into a different routine; however,
1933/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001934/// conversions, so for now they live here. IncompatibleObjC will be
1935/// set if the conversion is an allowed Objective-C conversion that
1936/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001937bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001938 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001939 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001940 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001941 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001942 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1943 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001944 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001945
Mike Stump1eb44332009-09-09 15:08:12 +00001946 // Conversion from a null pointer constant to any Objective-C pointer type.
1947 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001948 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001949 ConvertedType = ToType;
1950 return true;
1951 }
1952
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001953 // Blocks: Block pointers can be converted to void*.
1954 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001955 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001956 ConvertedType = ToType;
1957 return true;
1958 }
1959 // Blocks: A null pointer constant can be converted to a block
1960 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001961 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001962 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001963 ConvertedType = ToType;
1964 return true;
1965 }
1966
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001967 // If the left-hand-side is nullptr_t, the right side can be a null
1968 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001969 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001970 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001971 ConvertedType = ToType;
1972 return true;
1973 }
1974
Ted Kremenek6217b802009-07-29 21:53:49 +00001975 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001976 if (!ToTypePtr)
1977 return false;
1978
1979 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001980 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001981 ConvertedType = ToType;
1982 return true;
1983 }
Sebastian Redl07779722008-10-31 14:43:28 +00001984
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001985 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001986 // , including objective-c pointers.
1987 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001988 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001989 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001990 ConvertedType = BuildSimilarlyQualifiedPointerType(
1991 FromType->getAs<ObjCObjectPointerType>(),
1992 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001993 ToType, Context);
1994 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001995 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001996 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001997 if (!FromTypePtr)
1998 return false;
1999
2000 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002001
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002002 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00002003 // pointer conversion, so don't do all of the work below.
2004 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
2005 return false;
2006
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002007 // An rvalue of type "pointer to cv T," where T is an object type,
2008 // can be converted to an rvalue of type "pointer to cv void" (C++
2009 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002010 if (FromPointeeType->isIncompleteOrObjectType() &&
2011 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002012 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002013 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002014 ToType, Context,
2015 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002016 return true;
2017 }
2018
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002019 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002020 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002021 ToPointeeType->isVoidType()) {
2022 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2023 ToPointeeType,
2024 ToType, Context);
2025 return true;
2026 }
2027
Douglas Gregorf9201e02009-02-11 23:02:49 +00002028 // When we're overloading in C, we allow a special kind of pointer
2029 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002030 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002031 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002032 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002033 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002034 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002035 return true;
2036 }
2037
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002038 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002039 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002040 // An rvalue of type "pointer to cv D," where D is a class type,
2041 // can be converted to an rvalue of type "pointer to cv B," where
2042 // B is a base class (clause 10) of D. If B is an inaccessible
2043 // (clause 11) or ambiguous (10.2) base class of D, a program that
2044 // necessitates this conversion is ill-formed. The result of the
2045 // conversion is a pointer to the base class sub-object of the
2046 // derived class object. The null pointer value is converted to
2047 // the null pointer value of the destination type.
2048 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002049 // Note that we do not check for ambiguity or inaccessibility
2050 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002051 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002052 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002053 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002054 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002055 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002057 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002058 ToType, Context);
2059 return true;
2060 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002061
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002062 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2063 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2064 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2065 ToPointeeType,
2066 ToType, Context);
2067 return true;
2068 }
2069
Douglas Gregorc7887512008-12-19 19:13:09 +00002070 return false;
2071}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002072
2073/// \brief Adopt the given qualifiers for the given type.
2074static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2075 Qualifiers TQs = T.getQualifiers();
2076
2077 // Check whether qualifiers already match.
2078 if (TQs == Qs)
2079 return T;
2080
2081 if (Qs.compatiblyIncludes(TQs))
2082 return Context.getQualifiedType(T, Qs);
2083
2084 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2085}
Douglas Gregorc7887512008-12-19 19:13:09 +00002086
2087/// isObjCPointerConversion - Determines whether this is an
2088/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2089/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002090bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002091 QualType& ConvertedType,
2092 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002093 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002094 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002095
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002096 // The set of qualifiers on the type we're converting from.
2097 Qualifiers FromQualifiers = FromType.getQualifiers();
2098
Steve Naroff14108da2009-07-10 23:34:53 +00002099 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002100 const ObjCObjectPointerType* ToObjCPtr =
2101 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002102 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002103 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002104
Steve Naroff14108da2009-07-10 23:34:53 +00002105 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002106 // If the pointee types are the same (ignoring qualifications),
2107 // then this is not a pointer conversion.
2108 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2109 FromObjCPtr->getPointeeType()))
2110 return false;
2111
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002112 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002113 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002114 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002115 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002116 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002117 return true;
2118 }
2119 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002120 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002121 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002122 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002123 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002124 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002125 return true;
2126 }
2127 // Objective C++: We're able to convert from a pointer to an
2128 // interface to a pointer to a different interface.
2129 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002130 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2131 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002132 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002133 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2134 FromObjCPtr->getPointeeType()))
2135 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002136 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002137 ToObjCPtr->getPointeeType(),
2138 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002139 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002140 return true;
2141 }
2142
2143 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2144 // Okay: this is some kind of implicit downcast of Objective-C
2145 // interfaces, which is permitted. However, we're going to
2146 // complain about it.
2147 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002148 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002149 ToObjCPtr->getPointeeType(),
2150 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002151 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002152 return true;
2153 }
Mike Stump1eb44332009-09-09 15:08:12 +00002154 }
Steve Naroff14108da2009-07-10 23:34:53 +00002155 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002156 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002157 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002158 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002159 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002160 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002161 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002162 // to a block pointer type.
2163 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002164 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002165 return true;
2166 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002167 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002168 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002169 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002170 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002171 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002172 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002173 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002174 return true;
2175 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002176 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002177 return false;
2178
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002179 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002180 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002181 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002182 else if (const BlockPointerType *FromBlockPtr =
2183 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002184 FromPointeeType = FromBlockPtr->getPointeeType();
2185 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002186 return false;
2187
Douglas Gregorc7887512008-12-19 19:13:09 +00002188 // If we have pointers to pointers, recursively check whether this
2189 // is an Objective-C conversion.
2190 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2191 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2192 IncompatibleObjC)) {
2193 // We always complain about this conversion.
2194 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002195 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002196 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002197 return true;
2198 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002199 // Allow conversion of pointee being objective-c pointer to another one;
2200 // as in I* to id.
2201 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2202 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2203 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2204 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002205
Douglas Gregorda80f742010-12-01 21:43:58 +00002206 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002207 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002208 return true;
2209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002210
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002211 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002212 // differences in the argument and result types are in Objective-C
2213 // pointer conversions. If so, we permit the conversion (but
2214 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002215 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002216 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002217 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002218 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002219 if (FromFunctionType && ToFunctionType) {
2220 // If the function types are exactly the same, this isn't an
2221 // Objective-C pointer conversion.
2222 if (Context.getCanonicalType(FromPointeeType)
2223 == Context.getCanonicalType(ToPointeeType))
2224 return false;
2225
2226 // Perform the quick checks that will tell us whether these
2227 // function types are obviously different.
2228 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2229 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2230 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2231 return false;
2232
2233 bool HasObjCConversion = false;
2234 if (Context.getCanonicalType(FromFunctionType->getResultType())
2235 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2236 // Okay, the types match exactly. Nothing to do.
2237 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2238 ToFunctionType->getResultType(),
2239 ConvertedType, IncompatibleObjC)) {
2240 // Okay, we have an Objective-C pointer conversion.
2241 HasObjCConversion = true;
2242 } else {
2243 // Function types are too different. Abort.
2244 return false;
2245 }
Mike Stump1eb44332009-09-09 15:08:12 +00002246
Douglas Gregorc7887512008-12-19 19:13:09 +00002247 // Check argument types.
2248 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2249 ArgIdx != NumArgs; ++ArgIdx) {
2250 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2251 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2252 if (Context.getCanonicalType(FromArgType)
2253 == Context.getCanonicalType(ToArgType)) {
2254 // Okay, the types match exactly. Nothing to do.
2255 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2256 ConvertedType, IncompatibleObjC)) {
2257 // Okay, we have an Objective-C pointer conversion.
2258 HasObjCConversion = true;
2259 } else {
2260 // Argument types are too different. Abort.
2261 return false;
2262 }
2263 }
2264
2265 if (HasObjCConversion) {
2266 // We had an Objective-C conversion. Allow this pointer
2267 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002268 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002269 IncompatibleObjC = true;
2270 return true;
2271 }
2272 }
2273
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002274 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002275}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002276
John McCallf85e1932011-06-15 23:02:42 +00002277/// \brief Determine whether this is an Objective-C writeback conversion,
2278/// used for parameter passing when performing automatic reference counting.
2279///
2280/// \param FromType The type we're converting form.
2281///
2282/// \param ToType The type we're converting to.
2283///
2284/// \param ConvertedType The type that will be produced after applying
2285/// this conversion.
2286bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2287 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002288 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002289 Context.hasSameUnqualifiedType(FromType, ToType))
2290 return false;
2291
2292 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2293 QualType ToPointee;
2294 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2295 ToPointee = ToPointer->getPointeeType();
2296 else
2297 return false;
2298
2299 Qualifiers ToQuals = ToPointee.getQualifiers();
2300 if (!ToPointee->isObjCLifetimeType() ||
2301 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002302 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002303 return false;
2304
2305 // Argument must be a pointer to __strong to __weak.
2306 QualType FromPointee;
2307 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2308 FromPointee = FromPointer->getPointeeType();
2309 else
2310 return false;
2311
2312 Qualifiers FromQuals = FromPointee.getQualifiers();
2313 if (!FromPointee->isObjCLifetimeType() ||
2314 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2315 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2316 return false;
2317
2318 // Make sure that we have compatible qualifiers.
2319 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2320 if (!ToQuals.compatiblyIncludes(FromQuals))
2321 return false;
2322
2323 // Remove qualifiers from the pointee type we're converting from; they
2324 // aren't used in the compatibility check belong, and we'll be adding back
2325 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2326 FromPointee = FromPointee.getUnqualifiedType();
2327
2328 // The unqualified form of the pointee types must be compatible.
2329 ToPointee = ToPointee.getUnqualifiedType();
2330 bool IncompatibleObjC;
2331 if (Context.typesAreCompatible(FromPointee, ToPointee))
2332 FromPointee = ToPointee;
2333 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2334 IncompatibleObjC))
2335 return false;
2336
2337 /// \brief Construct the type we're converting to, which is a pointer to
2338 /// __autoreleasing pointee.
2339 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2340 ConvertedType = Context.getPointerType(FromPointee);
2341 return true;
2342}
2343
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002344bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2345 QualType& ConvertedType) {
2346 QualType ToPointeeType;
2347 if (const BlockPointerType *ToBlockPtr =
2348 ToType->getAs<BlockPointerType>())
2349 ToPointeeType = ToBlockPtr->getPointeeType();
2350 else
2351 return false;
2352
2353 QualType FromPointeeType;
2354 if (const BlockPointerType *FromBlockPtr =
2355 FromType->getAs<BlockPointerType>())
2356 FromPointeeType = FromBlockPtr->getPointeeType();
2357 else
2358 return false;
2359 // We have pointer to blocks, check whether the only
2360 // differences in the argument and result types are in Objective-C
2361 // pointer conversions. If so, we permit the conversion.
2362
2363 const FunctionProtoType *FromFunctionType
2364 = FromPointeeType->getAs<FunctionProtoType>();
2365 const FunctionProtoType *ToFunctionType
2366 = ToPointeeType->getAs<FunctionProtoType>();
2367
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002368 if (!FromFunctionType || !ToFunctionType)
2369 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002370
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002371 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002372 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002373
2374 // Perform the quick checks that will tell us whether these
2375 // function types are obviously different.
2376 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2377 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2378 return false;
2379
2380 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2381 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2382 if (FromEInfo != ToEInfo)
2383 return false;
2384
2385 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002386 if (Context.hasSameType(FromFunctionType->getResultType(),
2387 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002388 // Okay, the types match exactly. Nothing to do.
2389 } else {
2390 QualType RHS = FromFunctionType->getResultType();
2391 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002392 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002393 !RHS.hasQualifiers() && LHS.hasQualifiers())
2394 LHS = LHS.getUnqualifiedType();
2395
2396 if (Context.hasSameType(RHS,LHS)) {
2397 // OK exact match.
2398 } else if (isObjCPointerConversion(RHS, LHS,
2399 ConvertedType, IncompatibleObjC)) {
2400 if (IncompatibleObjC)
2401 return false;
2402 // Okay, we have an Objective-C pointer conversion.
2403 }
2404 else
2405 return false;
2406 }
2407
2408 // Check argument types.
2409 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2410 ArgIdx != NumArgs; ++ArgIdx) {
2411 IncompatibleObjC = false;
2412 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2413 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2414 if (Context.hasSameType(FromArgType, ToArgType)) {
2415 // Okay, the types match exactly. Nothing to do.
2416 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2417 ConvertedType, IncompatibleObjC)) {
2418 if (IncompatibleObjC)
2419 return false;
2420 // Okay, we have an Objective-C pointer conversion.
2421 } else
2422 // Argument types are too different. Abort.
2423 return false;
2424 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002425 if (LangOpts.ObjCAutoRefCount &&
2426 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2427 ToFunctionType))
2428 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002429
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002430 ConvertedType = ToType;
2431 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002432}
2433
Richard Trieu6efd4c52011-11-23 22:32:32 +00002434enum {
2435 ft_default,
2436 ft_different_class,
2437 ft_parameter_arity,
2438 ft_parameter_mismatch,
2439 ft_return_type,
2440 ft_qualifer_mismatch
2441};
2442
2443/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2444/// function types. Catches different number of parameter, mismatch in
2445/// parameter types, and different return types.
2446void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2447 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002448 // If either type is not valid, include no extra info.
2449 if (FromType.isNull() || ToType.isNull()) {
2450 PDiag << ft_default;
2451 return;
2452 }
2453
Richard Trieu6efd4c52011-11-23 22:32:32 +00002454 // Get the function type from the pointers.
2455 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2456 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2457 *ToMember = ToType->getAs<MemberPointerType>();
2458 if (FromMember->getClass() != ToMember->getClass()) {
2459 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2460 << QualType(FromMember->getClass(), 0);
2461 return;
2462 }
2463 FromType = FromMember->getPointeeType();
2464 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002465 }
2466
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002467 if (FromType->isPointerType())
2468 FromType = FromType->getPointeeType();
2469 if (ToType->isPointerType())
2470 ToType = ToType->getPointeeType();
2471
2472 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002473 FromType = FromType.getNonReferenceType();
2474 ToType = ToType.getNonReferenceType();
2475
Richard Trieu6efd4c52011-11-23 22:32:32 +00002476 // Don't print extra info for non-specialized template functions.
2477 if (FromType->isInstantiationDependentType() &&
2478 !FromType->getAs<TemplateSpecializationType>()) {
2479 PDiag << ft_default;
2480 return;
2481 }
2482
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002483 // No extra info for same types.
2484 if (Context.hasSameType(FromType, ToType)) {
2485 PDiag << ft_default;
2486 return;
2487 }
2488
Richard Trieu6efd4c52011-11-23 22:32:32 +00002489 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2490 *ToFunction = ToType->getAs<FunctionProtoType>();
2491
2492 // Both types need to be function types.
2493 if (!FromFunction || !ToFunction) {
2494 PDiag << ft_default;
2495 return;
2496 }
2497
2498 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2499 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2500 << FromFunction->getNumArgs();
2501 return;
2502 }
2503
2504 // Handle different parameter types.
2505 unsigned ArgPos;
2506 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2507 PDiag << ft_parameter_mismatch << ArgPos + 1
2508 << ToFunction->getArgType(ArgPos)
2509 << FromFunction->getArgType(ArgPos);
2510 return;
2511 }
2512
2513 // Handle different return type.
2514 if (!Context.hasSameType(FromFunction->getResultType(),
2515 ToFunction->getResultType())) {
2516 PDiag << ft_return_type << ToFunction->getResultType()
2517 << FromFunction->getResultType();
2518 return;
2519 }
2520
2521 unsigned FromQuals = FromFunction->getTypeQuals(),
2522 ToQuals = ToFunction->getTypeQuals();
2523 if (FromQuals != ToQuals) {
2524 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2525 return;
2526 }
2527
2528 // Unable to find a difference, so add no extra info.
2529 PDiag << ft_default;
2530}
2531
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002532/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002533/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002534/// they have same number of arguments. This routine assumes that Objective-C
2535/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002536/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002537/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002538bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002539 const FunctionProtoType *NewType,
2540 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002541 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002542 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2543 N = NewType->arg_type_begin(),
2544 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2545 if (!Context.hasSameType(*O, *N)) {
2546 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2547 return false;
2548 }
2549 }
2550 return true;
2551 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002552
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002553 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2554 N = NewType->arg_type_begin(),
2555 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2556 QualType ToType = (*O);
2557 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002558 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002559 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2560 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002561 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2562 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2563 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2564 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002565 continue;
2566 }
John McCallc12c5bb2010-05-15 11:32:37 +00002567 else if (const ObjCObjectPointerType *PTTo =
2568 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002569 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002570 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002571 if (Context.hasSameUnqualifiedType(
2572 PTTo->getObjectType()->getBaseType(),
2573 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002574 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002575 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002576 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002577 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002578 }
2579 }
2580 return true;
2581}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002582
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002583/// CheckPointerConversion - Check the pointer conversion from the
2584/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002585/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002586/// conversions for which IsPointerConversion has already returned
2587/// true. It returns true and produces a diagnostic if there was an
2588/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002589bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002590 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002591 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002592 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002593 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002594 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002595
John McCalldaa8e4e2010-11-15 09:13:47 +00002596 Kind = CK_BitCast;
2597
David Blaikie50800fc2012-08-08 17:33:31 +00002598 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2599 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2600 Expr::NPCK_ZeroExpression) {
2601 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2602 DiagRuntimeBehavior(From->getExprLoc(), From,
2603 PDiag(diag::warn_impcast_bool_to_null_pointer)
2604 << ToType << From->getSourceRange());
2605 else if (!isUnevaluatedContext())
2606 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2607 << ToType << From->getSourceRange();
2608 }
John McCall1d9b3b22011-09-09 05:25:32 +00002609 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2610 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002611 QualType FromPointeeType = FromPtrType->getPointeeType(),
2612 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002613
Douglas Gregor5fccd362010-03-03 23:55:11 +00002614 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2615 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002616 // We must have a derived-to-base conversion. Check an
2617 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002618 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2619 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002620 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002621 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002622 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002623
Anders Carlsson61faec12009-09-12 04:46:44 +00002624 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002625 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002626 }
2627 }
John McCall1d9b3b22011-09-09 05:25:32 +00002628 } else if (const ObjCObjectPointerType *ToPtrType =
2629 ToType->getAs<ObjCObjectPointerType>()) {
2630 if (const ObjCObjectPointerType *FromPtrType =
2631 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002632 // Objective-C++ conversions are always okay.
2633 // FIXME: We should have a different class of conversions for the
2634 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002635 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002636 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002637 } else if (FromType->isBlockPointerType()) {
2638 Kind = CK_BlockPointerToObjCPointerCast;
2639 } else {
2640 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002641 }
John McCall1d9b3b22011-09-09 05:25:32 +00002642 } else if (ToType->isBlockPointerType()) {
2643 if (!FromType->isBlockPointerType())
2644 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002645 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002646
2647 // We shouldn't fall into this case unless it's valid for other
2648 // reasons.
2649 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2650 Kind = CK_NullToPointer;
2651
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002652 return false;
2653}
2654
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002655/// IsMemberPointerConversion - Determines whether the conversion of the
2656/// expression From, which has the (possibly adjusted) type FromType, can be
2657/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2658/// If so, returns true and places the converted type (that might differ from
2659/// ToType in its cv-qualifiers at some level) into ConvertedType.
2660bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002661 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002662 bool InOverloadResolution,
2663 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002664 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002665 if (!ToTypePtr)
2666 return false;
2667
2668 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002669 if (From->isNullPointerConstant(Context,
2670 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2671 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002672 ConvertedType = ToType;
2673 return true;
2674 }
2675
2676 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002677 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002678 if (!FromTypePtr)
2679 return false;
2680
2681 // A pointer to member of B can be converted to a pointer to member of D,
2682 // where D is derived from B (C++ 4.11p2).
2683 QualType FromClass(FromTypePtr->getClass(), 0);
2684 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002685
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002686 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002687 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002688 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002689 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2690 ToClass.getTypePtr());
2691 return true;
2692 }
2693
2694 return false;
2695}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002696
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002697/// CheckMemberPointerConversion - Check the member pointer conversion from the
2698/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002699/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002700/// for which IsMemberPointerConversion has already returned true. It returns
2701/// true and produces a diagnostic if there was an error, or returns false
2702/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002703bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002704 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002705 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002706 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002707 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002708 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002709 if (!FromPtrType) {
2710 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002711 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002712 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002713 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002714 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002715 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002716 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002717
Ted Kremenek6217b802009-07-29 21:53:49 +00002718 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002719 assert(ToPtrType && "No member pointer cast has a target type "
2720 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002721
Sebastian Redl21593ac2009-01-28 18:33:18 +00002722 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2723 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002724
Sebastian Redl21593ac2009-01-28 18:33:18 +00002725 // FIXME: What about dependent types?
2726 assert(FromClass->isRecordType() && "Pointer into non-class.");
2727 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002728
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002729 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002730 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002731 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2732 assert(DerivationOkay &&
2733 "Should not have been called if derivation isn't OK.");
2734 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002735
Sebastian Redl21593ac2009-01-28 18:33:18 +00002736 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2737 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002738 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2739 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2740 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2741 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002742 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002743
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002744 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002745 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2746 << FromClass << ToClass << QualType(VBase, 0)
2747 << From->getSourceRange();
2748 return true;
2749 }
2750
John McCall6b2accb2010-02-10 09:31:12 +00002751 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002752 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2753 Paths.front(),
2754 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002755
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002756 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002757 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002758 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002759 return false;
2760}
2761
Douglas Gregor98cd5992008-10-21 23:43:52 +00002762/// IsQualificationConversion - Determines whether the conversion from
2763/// an rvalue of type FromType to ToType is a qualification conversion
2764/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002765///
2766/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2767/// when the qualification conversion involves a change in the Objective-C
2768/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002769bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002770Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002771 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002772 FromType = Context.getCanonicalType(FromType);
2773 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002774 ObjCLifetimeConversion = false;
2775
Douglas Gregor98cd5992008-10-21 23:43:52 +00002776 // If FromType and ToType are the same type, this is not a
2777 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002778 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002779 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002780
Douglas Gregor98cd5992008-10-21 23:43:52 +00002781 // (C++ 4.4p4):
2782 // A conversion can add cv-qualifiers at levels other than the first
2783 // in multi-level pointers, subject to the following rules: [...]
2784 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002785 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002786 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002787 // Within each iteration of the loop, we check the qualifiers to
2788 // determine if this still looks like a qualification
2789 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002790 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002791 // until there are no more pointers or pointers-to-members left to
2792 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002793 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002794
Douglas Gregor621c92a2011-04-25 18:40:17 +00002795 Qualifiers FromQuals = FromType.getQualifiers();
2796 Qualifiers ToQuals = ToType.getQualifiers();
2797
John McCallf85e1932011-06-15 23:02:42 +00002798 // Objective-C ARC:
2799 // Check Objective-C lifetime conversions.
2800 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2801 UnwrappedAnyPointer) {
2802 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2803 ObjCLifetimeConversion = true;
2804 FromQuals.removeObjCLifetime();
2805 ToQuals.removeObjCLifetime();
2806 } else {
2807 // Qualification conversions cannot cast between different
2808 // Objective-C lifetime qualifiers.
2809 return false;
2810 }
2811 }
2812
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002813 // Allow addition/removal of GC attributes but not changing GC attributes.
2814 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2815 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2816 FromQuals.removeObjCGCAttr();
2817 ToQuals.removeObjCGCAttr();
2818 }
2819
Douglas Gregor98cd5992008-10-21 23:43:52 +00002820 // -- for every j > 0, if const is in cv 1,j then const is in cv
2821 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002822 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002823 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002824
Douglas Gregor98cd5992008-10-21 23:43:52 +00002825 // -- if the cv 1,j and cv 2,j are different, then const is in
2826 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002827 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002828 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002829 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Douglas Gregor98cd5992008-10-21 23:43:52 +00002831 // Keep track of whether all prior cv-qualifiers in the "to" type
2832 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002833 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002834 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002835 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002836
2837 // We are left with FromType and ToType being the pointee types
2838 // after unwrapping the original FromType and ToType the same number
2839 // of types. If we unwrapped any pointers, and if FromType and
2840 // ToType have the same unqualified type (since we checked
2841 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002842 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002843}
2844
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002845/// \brief - Determine whether this is a conversion from a scalar type to an
2846/// atomic type.
2847///
2848/// If successful, updates \c SCS's second and third steps in the conversion
2849/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002850static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2851 bool InOverloadResolution,
2852 StandardConversionSequence &SCS,
2853 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002854 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2855 if (!ToAtomic)
2856 return false;
2857
2858 StandardConversionSequence InnerSCS;
2859 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2860 InOverloadResolution, InnerSCS,
2861 CStyle, /*AllowObjCWritebackConversion=*/false))
2862 return false;
2863
2864 SCS.Second = InnerSCS.Second;
2865 SCS.setToType(1, InnerSCS.getToType(1));
2866 SCS.Third = InnerSCS.Third;
2867 SCS.QualificationIncludesObjCLifetime
2868 = InnerSCS.QualificationIncludesObjCLifetime;
2869 SCS.setToType(2, InnerSCS.getToType(2));
2870 return true;
2871}
2872
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002873static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2874 CXXConstructorDecl *Constructor,
2875 QualType Type) {
2876 const FunctionProtoType *CtorType =
2877 Constructor->getType()->getAs<FunctionProtoType>();
2878 if (CtorType->getNumArgs() > 0) {
2879 QualType FirstArg = CtorType->getArgType(0);
2880 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2881 return true;
2882 }
2883 return false;
2884}
2885
Sebastian Redl56a04282012-02-11 23:51:08 +00002886static OverloadingResult
2887IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2888 CXXRecordDecl *To,
2889 UserDefinedConversionSequence &User,
2890 OverloadCandidateSet &CandidateSet,
2891 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002892 DeclContext::lookup_result R = S.LookupConstructors(To);
2893 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002894 Con != ConEnd; ++Con) {
2895 NamedDecl *D = *Con;
2896 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2897
2898 // Find the constructor (which may be a template).
2899 CXXConstructorDecl *Constructor = 0;
2900 FunctionTemplateDecl *ConstructorTmpl
2901 = dyn_cast<FunctionTemplateDecl>(D);
2902 if (ConstructorTmpl)
2903 Constructor
2904 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2905 else
2906 Constructor = cast<CXXConstructorDecl>(D);
2907
2908 bool Usable = !Constructor->isInvalidDecl() &&
2909 S.isInitListConstructor(Constructor) &&
2910 (AllowExplicit || !Constructor->isExplicit());
2911 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002912 // If the first argument is (a reference to) the target type,
2913 // suppress conversions.
2914 bool SuppressUserConversions =
2915 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002916 if (ConstructorTmpl)
2917 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2918 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002919 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002920 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002921 else
2922 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002923 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002924 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002925 }
2926 }
2927
2928 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2929
2930 OverloadCandidateSet::iterator Best;
2931 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2932 case OR_Success: {
2933 // Record the standard conversion we used and the conversion function.
2934 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002935 QualType ThisType = Constructor->getThisType(S.Context);
2936 // Initializer lists don't have conversions as such.
2937 User.Before.setAsIdentityConversion();
2938 User.HadMultipleCandidates = HadMultipleCandidates;
2939 User.ConversionFunction = Constructor;
2940 User.FoundConversionFunction = Best->FoundDecl;
2941 User.After.setAsIdentityConversion();
2942 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2943 User.After.setAllToTypes(ToType);
2944 return OR_Success;
2945 }
2946
2947 case OR_No_Viable_Function:
2948 return OR_No_Viable_Function;
2949 case OR_Deleted:
2950 return OR_Deleted;
2951 case OR_Ambiguous:
2952 return OR_Ambiguous;
2953 }
2954
2955 llvm_unreachable("Invalid OverloadResult!");
2956}
2957
Douglas Gregor734d9862009-01-30 23:27:23 +00002958/// Determines whether there is a user-defined conversion sequence
2959/// (C++ [over.ics.user]) that converts expression From to the type
2960/// ToType. If such a conversion exists, User will contain the
2961/// user-defined conversion sequence that performs such a conversion
2962/// and this routine will return true. Otherwise, this routine returns
2963/// false and User is unspecified.
2964///
Douglas Gregor734d9862009-01-30 23:27:23 +00002965/// \param AllowExplicit true if the conversion should consider C++0x
2966/// "explicit" conversion functions as well as non-explicit conversion
2967/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002968static OverloadingResult
2969IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002970 UserDefinedConversionSequence &User,
2971 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002972 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002973 // Whether we will only visit constructors.
2974 bool ConstructorsOnly = false;
2975
2976 // If the type we are conversion to is a class type, enumerate its
2977 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002978 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002979 // C++ [over.match.ctor]p1:
2980 // When objects of class type are direct-initialized (8.5), or
2981 // copy-initialized from an expression of the same or a
2982 // derived class type (8.5), overload resolution selects the
2983 // constructor. [...] For copy-initialization, the candidate
2984 // functions are all the converting constructors (12.3.1) of
2985 // that class. The argument list is the expression-list within
2986 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002987 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002988 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002989 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002990 ConstructorsOnly = true;
2991
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00002992 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002993 // RequireCompleteType may have returned true due to some invalid decl
2994 // during template instantiation, but ToType may be complete enough now
2995 // to try to recover.
2996 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002997 // We're not going to find any constructors.
2998 } else if (CXXRecordDecl *ToRecordDecl
2999 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003000
3001 Expr **Args = &From;
3002 unsigned NumArgs = 1;
3003 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003004 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00003005 // But first, see if there is an init-list-contructor that will work.
3006 OverloadingResult Result = IsInitializerListConstructorConversion(
3007 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3008 if (Result != OR_No_Viable_Function)
3009 return Result;
3010 // Never mind.
3011 CandidateSet.clear();
3012
3013 // If we're list-initializing, we pass the individual elements as
3014 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003015 Args = InitList->getInits();
3016 NumArgs = InitList->getNumInits();
3017 ListInitializing = true;
3018 }
3019
David Blaikie3bc93e32012-12-19 00:45:41 +00003020 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3021 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003022 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003023 NamedDecl *D = *Con;
3024 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3025
Douglas Gregordec06662009-08-21 18:42:58 +00003026 // Find the constructor (which may be a template).
3027 CXXConstructorDecl *Constructor = 0;
3028 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003029 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003030 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003031 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003032 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3033 else
John McCall9aa472c2010-03-19 07:35:19 +00003034 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003035
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003036 bool Usable = !Constructor->isInvalidDecl();
3037 if (ListInitializing)
3038 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3039 else
3040 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3041 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003042 bool SuppressUserConversions = !ConstructorsOnly;
3043 if (SuppressUserConversions && ListInitializing) {
3044 SuppressUserConversions = false;
3045 if (NumArgs == 1) {
3046 // If the first argument is (a reference to) the target type,
3047 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003048 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3049 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003050 }
3051 }
Douglas Gregordec06662009-08-21 18:42:58 +00003052 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003053 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3054 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003055 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003056 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003057 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003058 // Allow one user-defined conversion when user specifies a
3059 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003060 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003061 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003062 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003063 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003064 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003065 }
3066 }
3067
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003068 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003069 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003070 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003071 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003072 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003073 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003074 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003075 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3076 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003077 std::pair<CXXRecordDecl::conversion_iterator,
3078 CXXRecordDecl::conversion_iterator>
3079 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3080 for (CXXRecordDecl::conversion_iterator
3081 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003082 DeclAccessPair FoundDecl = I.getPair();
3083 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003084 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3085 if (isa<UsingShadowDecl>(D))
3086 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3087
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003088 CXXConversionDecl *Conv;
3089 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003090 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3091 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003092 else
John McCall32daa422010-03-31 01:36:47 +00003093 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003094
3095 if (AllowExplicit || !Conv->isExplicit()) {
3096 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003097 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3098 ActingContext, From, ToType,
3099 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003100 else
John McCall120d63c2010-08-24 20:38:10 +00003101 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3102 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003103 }
3104 }
3105 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003106 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003107
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003108 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3109
Douglas Gregor60d62c22008-10-31 16:23:19 +00003110 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003111 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003112 case OR_Success:
3113 // Record the standard conversion we used and the conversion function.
3114 if (CXXConstructorDecl *Constructor
3115 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3116 // C++ [over.ics.user]p1:
3117 // If the user-defined conversion is specified by a
3118 // constructor (12.3.1), the initial standard conversion
3119 // sequence converts the source type to the type required by
3120 // the argument of the constructor.
3121 //
3122 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003123 if (isa<InitListExpr>(From)) {
3124 // Initializer lists don't have conversions as such.
3125 User.Before.setAsIdentityConversion();
3126 } else {
3127 if (Best->Conversions[0].isEllipsis())
3128 User.EllipsisConversion = true;
3129 else {
3130 User.Before = Best->Conversions[0].Standard;
3131 User.EllipsisConversion = false;
3132 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003133 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003134 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003135 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003136 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003137 User.After.setAsIdentityConversion();
3138 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3139 User.After.setAllToTypes(ToType);
3140 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003141 }
3142 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003143 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3144 // C++ [over.ics.user]p1:
3145 //
3146 // [...] If the user-defined conversion is specified by a
3147 // conversion function (12.3.2), the initial standard
3148 // conversion sequence converts the source type to the
3149 // implicit object parameter of the conversion function.
3150 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003151 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003152 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003153 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003154 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003155
John McCall120d63c2010-08-24 20:38:10 +00003156 // C++ [over.ics.user]p2:
3157 // The second standard conversion sequence converts the
3158 // result of the user-defined conversion to the target type
3159 // for the sequence. Since an implicit conversion sequence
3160 // is an initialization, the special rules for
3161 // initialization by user-defined conversion apply when
3162 // selecting the best user-defined conversion for a
3163 // user-defined conversion sequence (see 13.3.3 and
3164 // 13.3.3.1).
3165 User.After = Best->FinalConversion;
3166 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003167 }
David Blaikie7530c032012-01-17 06:56:22 +00003168 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003169
John McCall120d63c2010-08-24 20:38:10 +00003170 case OR_No_Viable_Function:
3171 return OR_No_Viable_Function;
3172 case OR_Deleted:
3173 // No conversion here! We're done.
3174 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003175
John McCall120d63c2010-08-24 20:38:10 +00003176 case OR_Ambiguous:
3177 return OR_Ambiguous;
3178 }
3179
David Blaikie7530c032012-01-17 06:56:22 +00003180 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003181}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003182
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003183bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003184Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003185 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003186 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003187 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003188 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003189 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003190 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003191 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003192 diag::err_typecheck_ambiguous_condition)
3193 << From->getType() << ToType << From->getSourceRange();
3194 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003195 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003196 diag::err_typecheck_nonviable_condition)
3197 << From->getType() << ToType << From->getSourceRange();
3198 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003199 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003200 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003201 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003202}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003203
Douglas Gregorb734e242012-02-22 17:32:19 +00003204/// \brief Compare the user-defined conversion functions or constructors
3205/// of two user-defined conversion sequences to determine whether any ordering
3206/// is possible.
3207static ImplicitConversionSequence::CompareKind
3208compareConversionFunctions(Sema &S,
3209 FunctionDecl *Function1,
3210 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003211 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003212 return ImplicitConversionSequence::Indistinguishable;
3213
3214 // Objective-C++:
3215 // If both conversion functions are implicitly-declared conversions from
3216 // a lambda closure type to a function pointer and a block pointer,
3217 // respectively, always prefer the conversion to a function pointer,
3218 // because the function pointer is more lightweight and is more likely
3219 // to keep code working.
3220 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3221 if (!Conv1)
3222 return ImplicitConversionSequence::Indistinguishable;
3223
3224 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3225 if (!Conv2)
3226 return ImplicitConversionSequence::Indistinguishable;
3227
3228 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3229 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3230 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3231 if (Block1 != Block2)
3232 return Block1? ImplicitConversionSequence::Worse
3233 : ImplicitConversionSequence::Better;
3234 }
3235
3236 return ImplicitConversionSequence::Indistinguishable;
3237}
3238
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003239/// CompareImplicitConversionSequences - Compare two implicit
3240/// conversion sequences to determine whether one is better than the
3241/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003242static ImplicitConversionSequence::CompareKind
3243CompareImplicitConversionSequences(Sema &S,
3244 const ImplicitConversionSequence& ICS1,
3245 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003246{
3247 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3248 // conversion sequences (as defined in 13.3.3.1)
3249 // -- a standard conversion sequence (13.3.3.1.1) is a better
3250 // conversion sequence than a user-defined conversion sequence or
3251 // an ellipsis conversion sequence, and
3252 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3253 // conversion sequence than an ellipsis conversion sequence
3254 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003255 //
John McCall1d318332010-01-12 00:44:57 +00003256 // C++0x [over.best.ics]p10:
3257 // For the purpose of ranking implicit conversion sequences as
3258 // described in 13.3.3.2, the ambiguous conversion sequence is
3259 // treated as a user-defined sequence that is indistinguishable
3260 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003261 if (ICS1.getKindRank() < ICS2.getKindRank())
3262 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003263 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003264 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003265
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003266 // The following checks require both conversion sequences to be of
3267 // the same kind.
3268 if (ICS1.getKind() != ICS2.getKind())
3269 return ImplicitConversionSequence::Indistinguishable;
3270
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003271 ImplicitConversionSequence::CompareKind Result =
3272 ImplicitConversionSequence::Indistinguishable;
3273
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003274 // Two implicit conversion sequences of the same form are
3275 // indistinguishable conversion sequences unless one of the
3276 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003277 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003278 Result = CompareStandardConversionSequences(S,
3279 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003280 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003281 // User-defined conversion sequence U1 is a better conversion
3282 // sequence than another user-defined conversion sequence U2 if
3283 // they contain the same user-defined conversion function or
3284 // constructor and if the second standard conversion sequence of
3285 // U1 is better than the second standard conversion sequence of
3286 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003287 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003288 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003289 Result = CompareStandardConversionSequences(S,
3290 ICS1.UserDefined.After,
3291 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003292 else
3293 Result = compareConversionFunctions(S,
3294 ICS1.UserDefined.ConversionFunction,
3295 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003296 }
3297
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003298 // List-initialization sequence L1 is a better conversion sequence than
3299 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3300 // for some X and L2 does not.
3301 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003302 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003303 ICS1.isListInitializationSequence() &&
3304 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003305 if (ICS1.isStdInitializerListElement() &&
3306 !ICS2.isStdInitializerListElement())
3307 return ImplicitConversionSequence::Better;
3308 if (!ICS1.isStdInitializerListElement() &&
3309 ICS2.isStdInitializerListElement())
3310 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003311 }
3312
3313 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003314}
3315
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003316static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3317 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3318 Qualifiers Quals;
3319 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003320 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003322
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003323 return Context.hasSameUnqualifiedType(T1, T2);
3324}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003325
Douglas Gregorad323a82010-01-27 03:51:04 +00003326// Per 13.3.3.2p3, compare the given standard conversion sequences to
3327// determine if one is a proper subset of the other.
3328static ImplicitConversionSequence::CompareKind
3329compareStandardConversionSubsets(ASTContext &Context,
3330 const StandardConversionSequence& SCS1,
3331 const StandardConversionSequence& SCS2) {
3332 ImplicitConversionSequence::CompareKind Result
3333 = ImplicitConversionSequence::Indistinguishable;
3334
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003335 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003336 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003337 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3338 return ImplicitConversionSequence::Better;
3339 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3340 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003341
Douglas Gregorad323a82010-01-27 03:51:04 +00003342 if (SCS1.Second != SCS2.Second) {
3343 if (SCS1.Second == ICK_Identity)
3344 Result = ImplicitConversionSequence::Better;
3345 else if (SCS2.Second == ICK_Identity)
3346 Result = ImplicitConversionSequence::Worse;
3347 else
3348 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003349 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003350 return ImplicitConversionSequence::Indistinguishable;
3351
3352 if (SCS1.Third == SCS2.Third) {
3353 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3354 : ImplicitConversionSequence::Indistinguishable;
3355 }
3356
3357 if (SCS1.Third == ICK_Identity)
3358 return Result == ImplicitConversionSequence::Worse
3359 ? ImplicitConversionSequence::Indistinguishable
3360 : ImplicitConversionSequence::Better;
3361
3362 if (SCS2.Third == ICK_Identity)
3363 return Result == ImplicitConversionSequence::Better
3364 ? ImplicitConversionSequence::Indistinguishable
3365 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003366
Douglas Gregorad323a82010-01-27 03:51:04 +00003367 return ImplicitConversionSequence::Indistinguishable;
3368}
3369
Douglas Gregor440a4832011-01-26 14:52:12 +00003370/// \brief Determine whether one of the given reference bindings is better
3371/// than the other based on what kind of bindings they are.
3372static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3373 const StandardConversionSequence &SCS2) {
3374 // C++0x [over.ics.rank]p3b4:
3375 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3376 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003377 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003378 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003379 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003380 // reference*.
3381 //
3382 // FIXME: Rvalue references. We're going rogue with the above edits,
3383 // because the semantics in the current C++0x working paper (N3225 at the
3384 // time of this writing) break the standard definition of std::forward
3385 // and std::reference_wrapper when dealing with references to functions.
3386 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003387 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3388 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3389 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003390
Douglas Gregor440a4832011-01-26 14:52:12 +00003391 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3392 SCS2.IsLvalueReference) ||
3393 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3394 !SCS2.IsLvalueReference);
3395}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003396
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003397/// CompareStandardConversionSequences - Compare two standard
3398/// conversion sequences to determine whether one is better than the
3399/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003400static ImplicitConversionSequence::CompareKind
3401CompareStandardConversionSequences(Sema &S,
3402 const StandardConversionSequence& SCS1,
3403 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003404{
3405 // Standard conversion sequence S1 is a better conversion sequence
3406 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3407
3408 // -- S1 is a proper subsequence of S2 (comparing the conversion
3409 // sequences in the canonical form defined by 13.3.3.1.1,
3410 // excluding any Lvalue Transformation; the identity conversion
3411 // sequence is considered to be a subsequence of any
3412 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003413 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003414 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003415 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003416
3417 // -- the rank of S1 is better than the rank of S2 (by the rules
3418 // defined below), or, if not that,
3419 ImplicitConversionRank Rank1 = SCS1.getRank();
3420 ImplicitConversionRank Rank2 = SCS2.getRank();
3421 if (Rank1 < Rank2)
3422 return ImplicitConversionSequence::Better;
3423 else if (Rank2 < Rank1)
3424 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003425
Douglas Gregor57373262008-10-22 14:17:15 +00003426 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3427 // are indistinguishable unless one of the following rules
3428 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Douglas Gregor57373262008-10-22 14:17:15 +00003430 // A conversion that is not a conversion of a pointer, or
3431 // pointer to member, to bool is better than another conversion
3432 // that is such a conversion.
3433 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3434 return SCS2.isPointerConversionToBool()
3435 ? ImplicitConversionSequence::Better
3436 : ImplicitConversionSequence::Worse;
3437
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003438 // C++ [over.ics.rank]p4b2:
3439 //
3440 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003441 // conversion of B* to A* is better than conversion of B* to
3442 // void*, and conversion of A* to void* is better than conversion
3443 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003444 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003445 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003446 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003447 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003448 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3449 // Exactly one of the conversion sequences is a conversion to
3450 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003451 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3452 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003453 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3454 // Neither conversion sequence converts to a void pointer; compare
3455 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003456 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003457 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003458 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003459 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3460 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003461 // Both conversion sequences are conversions to void
3462 // pointers. Compare the source types to determine if there's an
3463 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003464 QualType FromType1 = SCS1.getFromType();
3465 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003466
3467 // Adjust the types we're converting from via the array-to-pointer
3468 // conversion, if we need to.
3469 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003470 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003471 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003472 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003473
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003474 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3475 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003476
John McCall120d63c2010-08-24 20:38:10 +00003477 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003478 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003479 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003480 return ImplicitConversionSequence::Worse;
3481
3482 // Objective-C++: If one interface is more specific than the
3483 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003484 const ObjCObjectPointerType* FromObjCPtr1
3485 = FromType1->getAs<ObjCObjectPointerType>();
3486 const ObjCObjectPointerType* FromObjCPtr2
3487 = FromType2->getAs<ObjCObjectPointerType>();
3488 if (FromObjCPtr1 && FromObjCPtr2) {
3489 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3490 FromObjCPtr2);
3491 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3492 FromObjCPtr1);
3493 if (AssignLeft != AssignRight) {
3494 return AssignLeft? ImplicitConversionSequence::Better
3495 : ImplicitConversionSequence::Worse;
3496 }
Douglas Gregor01919692009-12-13 21:37:05 +00003497 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003498 }
Douglas Gregor57373262008-10-22 14:17:15 +00003499
3500 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3501 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003502 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003503 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003504 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003505
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003506 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003507 // Check for a better reference binding based on the kind of bindings.
3508 if (isBetterReferenceBindingKind(SCS1, SCS2))
3509 return ImplicitConversionSequence::Better;
3510 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3511 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003512
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003513 // C++ [over.ics.rank]p3b4:
3514 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3515 // which the references refer are the same type except for
3516 // top-level cv-qualifiers, and the type to which the reference
3517 // initialized by S2 refers is more cv-qualified than the type
3518 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003519 QualType T1 = SCS1.getToType(2);
3520 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003521 T1 = S.Context.getCanonicalType(T1);
3522 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003523 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003524 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3525 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003526 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003527 // Objective-C++ ARC: If the references refer to objects with different
3528 // lifetimes, prefer bindings that don't change lifetime.
3529 if (SCS1.ObjCLifetimeConversionBinding !=
3530 SCS2.ObjCLifetimeConversionBinding) {
3531 return SCS1.ObjCLifetimeConversionBinding
3532 ? ImplicitConversionSequence::Worse
3533 : ImplicitConversionSequence::Better;
3534 }
3535
Chandler Carruth6df868e2010-12-12 08:17:55 +00003536 // If the type is an array type, promote the element qualifiers to the
3537 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003538 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003539 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003540 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003541 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003542 if (T2.isMoreQualifiedThan(T1))
3543 return ImplicitConversionSequence::Better;
3544 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003545 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003546 }
3547 }
Douglas Gregor57373262008-10-22 14:17:15 +00003548
Francois Pichet1c98d622011-09-18 21:37:37 +00003549 // In Microsoft mode, prefer an integral conversion to a
3550 // floating-to-integral conversion if the integral conversion
3551 // is between types of the same size.
3552 // For example:
3553 // void f(float);
3554 // void f(int);
3555 // int main {
3556 // long a;
3557 // f(a);
3558 // }
3559 // Here, MSVC will call f(int) instead of generating a compile error
3560 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003561 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003562 SCS1.Second == ICK_Integral_Conversion &&
3563 SCS2.Second == ICK_Floating_Integral &&
3564 S.Context.getTypeSize(SCS1.getFromType()) ==
3565 S.Context.getTypeSize(SCS1.getToType(2)))
3566 return ImplicitConversionSequence::Better;
3567
Douglas Gregor57373262008-10-22 14:17:15 +00003568 return ImplicitConversionSequence::Indistinguishable;
3569}
3570
3571/// CompareQualificationConversions - Compares two standard conversion
3572/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003573/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3574ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003575CompareQualificationConversions(Sema &S,
3576 const StandardConversionSequence& SCS1,
3577 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003578 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003579 // -- S1 and S2 differ only in their qualification conversion and
3580 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3581 // cv-qualification signature of type T1 is a proper subset of
3582 // the cv-qualification signature of type T2, and S1 is not the
3583 // deprecated string literal array-to-pointer conversion (4.2).
3584 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3585 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3586 return ImplicitConversionSequence::Indistinguishable;
3587
3588 // FIXME: the example in the standard doesn't use a qualification
3589 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003590 QualType T1 = SCS1.getToType(2);
3591 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003592 T1 = S.Context.getCanonicalType(T1);
3593 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003594 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003595 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3596 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003597
3598 // If the types are the same, we won't learn anything by unwrapped
3599 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003600 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003601 return ImplicitConversionSequence::Indistinguishable;
3602
Chandler Carruth28e318c2009-12-29 07:16:59 +00003603 // If the type is an array type, promote the element qualifiers to the type
3604 // for comparison.
3605 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003606 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003607 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003608 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003609
Mike Stump1eb44332009-09-09 15:08:12 +00003610 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003611 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003612
3613 // Objective-C++ ARC:
3614 // Prefer qualification conversions not involving a change in lifetime
3615 // to qualification conversions that do not change lifetime.
3616 if (SCS1.QualificationIncludesObjCLifetime !=
3617 SCS2.QualificationIncludesObjCLifetime) {
3618 Result = SCS1.QualificationIncludesObjCLifetime
3619 ? ImplicitConversionSequence::Worse
3620 : ImplicitConversionSequence::Better;
3621 }
3622
John McCall120d63c2010-08-24 20:38:10 +00003623 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003624 // Within each iteration of the loop, we check the qualifiers to
3625 // determine if this still looks like a qualification
3626 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003627 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003628 // until there are no more pointers or pointers-to-members left
3629 // to unwrap. This essentially mimics what
3630 // IsQualificationConversion does, but here we're checking for a
3631 // strict subset of qualifiers.
3632 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3633 // The qualifiers are the same, so this doesn't tell us anything
3634 // about how the sequences rank.
3635 ;
3636 else if (T2.isMoreQualifiedThan(T1)) {
3637 // T1 has fewer qualifiers, so it could be the better sequence.
3638 if (Result == ImplicitConversionSequence::Worse)
3639 // Neither has qualifiers that are a subset of the other's
3640 // qualifiers.
3641 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003642
Douglas Gregor57373262008-10-22 14:17:15 +00003643 Result = ImplicitConversionSequence::Better;
3644 } else if (T1.isMoreQualifiedThan(T2)) {
3645 // T2 has fewer qualifiers, so it could be the better sequence.
3646 if (Result == ImplicitConversionSequence::Better)
3647 // Neither has qualifiers that are a subset of the other's
3648 // qualifiers.
3649 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Douglas Gregor57373262008-10-22 14:17:15 +00003651 Result = ImplicitConversionSequence::Worse;
3652 } else {
3653 // Qualifiers are disjoint.
3654 return ImplicitConversionSequence::Indistinguishable;
3655 }
3656
3657 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003658 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003659 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003660 }
3661
Douglas Gregor57373262008-10-22 14:17:15 +00003662 // Check that the winning standard conversion sequence isn't using
3663 // the deprecated string literal array to pointer conversion.
3664 switch (Result) {
3665 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003666 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003667 Result = ImplicitConversionSequence::Indistinguishable;
3668 break;
3669
3670 case ImplicitConversionSequence::Indistinguishable:
3671 break;
3672
3673 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003674 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003675 Result = ImplicitConversionSequence::Indistinguishable;
3676 break;
3677 }
3678
3679 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003680}
3681
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003682/// CompareDerivedToBaseConversions - Compares two standard conversion
3683/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003684/// various kinds of derived-to-base conversions (C++
3685/// [over.ics.rank]p4b3). As part of these checks, we also look at
3686/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003687ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003688CompareDerivedToBaseConversions(Sema &S,
3689 const StandardConversionSequence& SCS1,
3690 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003691 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003692 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003693 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003694 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003695
3696 // Adjust the types we're converting from via the array-to-pointer
3697 // conversion, if we need to.
3698 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003699 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003700 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003701 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003702
3703 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003704 FromType1 = S.Context.getCanonicalType(FromType1);
3705 ToType1 = S.Context.getCanonicalType(ToType1);
3706 FromType2 = S.Context.getCanonicalType(FromType2);
3707 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003708
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003709 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003710 //
3711 // If class B is derived directly or indirectly from class A and
3712 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003713 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003714 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003715 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003716 SCS2.Second == ICK_Pointer_Conversion &&
3717 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3718 FromType1->isPointerType() && FromType2->isPointerType() &&
3719 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003720 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003721 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003722 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003723 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003724 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003725 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003727 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003728
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003729 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003730 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003731 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003732 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003733 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003734 return ImplicitConversionSequence::Worse;
3735 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003736
3737 // -- conversion of B* to A* is better than conversion of C* to A*,
3738 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003739 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003740 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003741 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003742 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003743 }
3744 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3745 SCS2.Second == ICK_Pointer_Conversion) {
3746 const ObjCObjectPointerType *FromPtr1
3747 = FromType1->getAs<ObjCObjectPointerType>();
3748 const ObjCObjectPointerType *FromPtr2
3749 = FromType2->getAs<ObjCObjectPointerType>();
3750 const ObjCObjectPointerType *ToPtr1
3751 = ToType1->getAs<ObjCObjectPointerType>();
3752 const ObjCObjectPointerType *ToPtr2
3753 = ToType2->getAs<ObjCObjectPointerType>();
3754
3755 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3756 // Apply the same conversion ranking rules for Objective-C pointer types
3757 // that we do for C++ pointers to class types. However, we employ the
3758 // Objective-C pseudo-subtyping relationship used for assignment of
3759 // Objective-C pointer types.
3760 bool FromAssignLeft
3761 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3762 bool FromAssignRight
3763 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3764 bool ToAssignLeft
3765 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3766 bool ToAssignRight
3767 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3768
3769 // A conversion to an a non-id object pointer type or qualified 'id'
3770 // type is better than a conversion to 'id'.
3771 if (ToPtr1->isObjCIdType() &&
3772 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3773 return ImplicitConversionSequence::Worse;
3774 if (ToPtr2->isObjCIdType() &&
3775 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3776 return ImplicitConversionSequence::Better;
3777
3778 // A conversion to a non-id object pointer type is better than a
3779 // conversion to a qualified 'id' type
3780 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3781 return ImplicitConversionSequence::Worse;
3782 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3783 return ImplicitConversionSequence::Better;
3784
3785 // A conversion to an a non-Class object pointer type or qualified 'Class'
3786 // type is better than a conversion to 'Class'.
3787 if (ToPtr1->isObjCClassType() &&
3788 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3789 return ImplicitConversionSequence::Worse;
3790 if (ToPtr2->isObjCClassType() &&
3791 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3792 return ImplicitConversionSequence::Better;
3793
3794 // A conversion to a non-Class object pointer type is better than a
3795 // conversion to a qualified 'Class' type.
3796 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3797 return ImplicitConversionSequence::Worse;
3798 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3799 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Douglas Gregor395cc372011-01-31 18:51:41 +00003801 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3802 if (S.Context.hasSameType(FromType1, FromType2) &&
3803 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3804 (ToAssignLeft != ToAssignRight))
3805 return ToAssignLeft? ImplicitConversionSequence::Worse
3806 : ImplicitConversionSequence::Better;
3807
3808 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3809 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3810 (FromAssignLeft != FromAssignRight))
3811 return FromAssignLeft? ImplicitConversionSequence::Better
3812 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003813 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003814 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003815
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003816 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003817 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3818 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3819 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003820 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003821 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003822 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003823 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003824 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003825 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003826 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003827 ToType2->getAs<MemberPointerType>();
3828 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3829 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3830 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3831 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3832 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3833 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3834 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3835 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003836 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003837 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003838 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003839 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003840 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003841 return ImplicitConversionSequence::Better;
3842 }
3843 // conversion of B::* to C::* is better than conversion of A::* to C::*
3844 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003845 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003846 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003847 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003848 return ImplicitConversionSequence::Worse;
3849 }
3850 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003851
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003852 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003853 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003854 // -- binding of an expression of type C to a reference of type
3855 // B& is better than binding an expression of type C to a
3856 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003857 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3858 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3859 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003860 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003861 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003862 return ImplicitConversionSequence::Worse;
3863 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003864
Douglas Gregor225c41e2008-11-03 19:09:14 +00003865 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003866 // -- binding of an expression of type B to a reference of type
3867 // A& is better than binding an expression of type C to a
3868 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003869 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3870 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3871 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003872 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003873 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003874 return ImplicitConversionSequence::Worse;
3875 }
3876 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003877
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003878 return ImplicitConversionSequence::Indistinguishable;
3879}
3880
Douglas Gregorabe183d2010-04-13 16:31:36 +00003881/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3882/// determine whether they are reference-related,
3883/// reference-compatible, reference-compatible with added
3884/// qualification, or incompatible, for use in C++ initialization by
3885/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3886/// type, and the first type (T1) is the pointee type of the reference
3887/// type being initialized.
3888Sema::ReferenceCompareResult
3889Sema::CompareReferenceRelationship(SourceLocation Loc,
3890 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003891 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003892 bool &ObjCConversion,
3893 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003894 assert(!OrigT1->isReferenceType() &&
3895 "T1 must be the pointee type of the reference type");
3896 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3897
3898 QualType T1 = Context.getCanonicalType(OrigT1);
3899 QualType T2 = Context.getCanonicalType(OrigT2);
3900 Qualifiers T1Quals, T2Quals;
3901 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3902 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3903
3904 // C++ [dcl.init.ref]p4:
3905 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3906 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3907 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003908 DerivedToBase = false;
3909 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003910 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003911 if (UnqualT1 == UnqualT2) {
3912 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003913 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003914 IsDerivedFrom(UnqualT2, UnqualT1))
3915 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003916 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3917 UnqualT2->isObjCObjectOrInterfaceType() &&
3918 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3919 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003920 else
3921 return Ref_Incompatible;
3922
3923 // At this point, we know that T1 and T2 are reference-related (at
3924 // least).
3925
3926 // If the type is an array type, promote the element qualifiers to the type
3927 // for comparison.
3928 if (isa<ArrayType>(T1) && T1Quals)
3929 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3930 if (isa<ArrayType>(T2) && T2Quals)
3931 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3932
3933 // C++ [dcl.init.ref]p4:
3934 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3935 // reference-related to T2 and cv1 is the same cv-qualification
3936 // as, or greater cv-qualification than, cv2. For purposes of
3937 // overload resolution, cases for which cv1 is greater
3938 // cv-qualification than cv2 are identified as
3939 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003940 //
3941 // Note that we also require equivalence of Objective-C GC and address-space
3942 // qualifiers when performing these computations, so that e.g., an int in
3943 // address space 1 is not reference-compatible with an int in address
3944 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003945 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3946 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3947 T1Quals.removeObjCLifetime();
3948 T2Quals.removeObjCLifetime();
3949 ObjCLifetimeConversion = true;
3950 }
3951
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003952 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003953 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003954 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003955 return Ref_Compatible_With_Added_Qualification;
3956 else
3957 return Ref_Related;
3958}
3959
Douglas Gregor604eb652010-08-11 02:15:33 +00003960/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003961/// with DeclType. Return true if something definite is found.
3962static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003963FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3964 QualType DeclType, SourceLocation DeclLoc,
3965 Expr *Init, QualType T2, bool AllowRvalues,
3966 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003967 assert(T2->isRecordType() && "Can only find conversions of record types.");
3968 CXXRecordDecl *T2RecordDecl
3969 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3970
3971 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003972 std::pair<CXXRecordDecl::conversion_iterator,
3973 CXXRecordDecl::conversion_iterator>
3974 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3975 for (CXXRecordDecl::conversion_iterator
3976 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003977 NamedDecl *D = *I;
3978 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3979 if (isa<UsingShadowDecl>(D))
3980 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3981
3982 FunctionTemplateDecl *ConvTemplate
3983 = dyn_cast<FunctionTemplateDecl>(D);
3984 CXXConversionDecl *Conv;
3985 if (ConvTemplate)
3986 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3987 else
3988 Conv = cast<CXXConversionDecl>(D);
3989
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003990 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003991 // explicit conversions, skip it.
3992 if (!AllowExplicit && Conv->isExplicit())
3993 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003994
Douglas Gregor604eb652010-08-11 02:15:33 +00003995 if (AllowRvalues) {
3996 bool DerivedToBase = false;
3997 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003998 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003999
4000 // If we are initializing an rvalue reference, don't permit conversion
4001 // functions that return lvalues.
4002 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
4003 const ReferenceType *RefType
4004 = Conv->getConversionType()->getAs<LValueReferenceType>();
4005 if (RefType && !RefType->getPointeeType()->isFunctionType())
4006 continue;
4007 }
4008
Douglas Gregor604eb652010-08-11 02:15:33 +00004009 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004010 S.CompareReferenceRelationship(
4011 DeclLoc,
4012 Conv->getConversionType().getNonReferenceType()
4013 .getUnqualifiedType(),
4014 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004015 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004016 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004017 continue;
4018 } else {
4019 // If the conversion function doesn't return a reference type,
4020 // it can't be considered for this conversion. An rvalue reference
4021 // is only acceptable if its referencee is a function type.
4022
4023 const ReferenceType *RefType =
4024 Conv->getConversionType()->getAs<ReferenceType>();
4025 if (!RefType ||
4026 (!RefType->isLValueReferenceType() &&
4027 !RefType->getPointeeType()->isFunctionType()))
4028 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004029 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004030
Douglas Gregor604eb652010-08-11 02:15:33 +00004031 if (ConvTemplate)
4032 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004033 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004034 else
4035 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004036 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004037 }
4038
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004039 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4040
Sebastian Redl4680bf22010-06-30 18:13:39 +00004041 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004042 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004043 case OR_Success:
4044 // C++ [over.ics.ref]p1:
4045 //
4046 // [...] If the parameter binds directly to the result of
4047 // applying a conversion function to the argument
4048 // expression, the implicit conversion sequence is a
4049 // user-defined conversion sequence (13.3.3.1.2), with the
4050 // second standard conversion sequence either an identity
4051 // conversion or, if the conversion function returns an
4052 // entity of a type that is a derived class of the parameter
4053 // type, a derived-to-base Conversion.
4054 if (!Best->FinalConversion.DirectBinding)
4055 return false;
4056
4057 ICS.setUserDefined();
4058 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4059 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004060 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004061 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004062 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004063 ICS.UserDefined.EllipsisConversion = false;
4064 assert(ICS.UserDefined.After.ReferenceBinding &&
4065 ICS.UserDefined.After.DirectBinding &&
4066 "Expected a direct reference binding!");
4067 return true;
4068
4069 case OR_Ambiguous:
4070 ICS.setAmbiguous();
4071 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4072 Cand != CandidateSet.end(); ++Cand)
4073 if (Cand->Viable)
4074 ICS.Ambiguous.addConversion(Cand->Function);
4075 return true;
4076
4077 case OR_No_Viable_Function:
4078 case OR_Deleted:
4079 // There was no suitable conversion, or we found a deleted
4080 // conversion; continue with other checks.
4081 return false;
4082 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004083
David Blaikie7530c032012-01-17 06:56:22 +00004084 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004085}
4086
Douglas Gregorabe183d2010-04-13 16:31:36 +00004087/// \brief Compute an implicit conversion sequence for reference
4088/// initialization.
4089static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004090TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004091 SourceLocation DeclLoc,
4092 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004093 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004094 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4095
4096 // Most paths end in a failed conversion.
4097 ImplicitConversionSequence ICS;
4098 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4099
4100 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4101 QualType T2 = Init->getType();
4102
4103 // If the initializer is the address of an overloaded function, try
4104 // to resolve the overloaded function. If all goes well, T2 is the
4105 // type of the resulting function.
4106 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4107 DeclAccessPair Found;
4108 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4109 false, Found))
4110 T2 = Fn->getType();
4111 }
4112
4113 // Compute some basic properties of the types and the initializer.
4114 bool isRValRef = DeclType->isRValueReferenceType();
4115 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004116 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004117 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004118 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004119 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004120 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004121 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004122
Douglas Gregorabe183d2010-04-13 16:31:36 +00004123
Sebastian Redl4680bf22010-06-30 18:13:39 +00004124 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004125 // A reference to type "cv1 T1" is initialized by an expression
4126 // of type "cv2 T2" as follows:
4127
Sebastian Redl4680bf22010-06-30 18:13:39 +00004128 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004129 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004130 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4131 // reference-compatible with "cv2 T2," or
4132 //
4133 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4134 if (InitCategory.isLValue() &&
4135 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004136 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004137 // When a parameter of reference type binds directly (8.5.3)
4138 // to an argument expression, the implicit conversion sequence
4139 // is the identity conversion, unless the argument expression
4140 // has a type that is a derived class of the parameter type,
4141 // in which case the implicit conversion sequence is a
4142 // derived-to-base Conversion (13.3.3.1).
4143 ICS.setStandard();
4144 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004145 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4146 : ObjCConversion? ICK_Compatible_Conversion
4147 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004148 ICS.Standard.Third = ICK_Identity;
4149 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4150 ICS.Standard.setToType(0, T2);
4151 ICS.Standard.setToType(1, T1);
4152 ICS.Standard.setToType(2, T1);
4153 ICS.Standard.ReferenceBinding = true;
4154 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004155 ICS.Standard.IsLvalueReference = !isRValRef;
4156 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4157 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004158 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004159 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004160 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004161
Sebastian Redl4680bf22010-06-30 18:13:39 +00004162 // Nothing more to do: the inaccessibility/ambiguity check for
4163 // derived-to-base conversions is suppressed when we're
4164 // computing the implicit conversion sequence (C++
4165 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004166 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004167 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004168
Sebastian Redl4680bf22010-06-30 18:13:39 +00004169 // -- has a class type (i.e., T2 is a class type), where T1 is
4170 // not reference-related to T2, and can be implicitly
4171 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4172 // is reference-compatible with "cv3 T3" 92) (this
4173 // conversion is selected by enumerating the applicable
4174 // conversion functions (13.3.1.6) and choosing the best
4175 // one through overload resolution (13.3)),
4176 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004177 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004178 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004179 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4180 Init, T2, /*AllowRvalues=*/false,
4181 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004182 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004183 }
4184 }
4185
Sebastian Redl4680bf22010-06-30 18:13:39 +00004186 // -- Otherwise, the reference shall be an lvalue reference to a
4187 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004188 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004189 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004190 // We actually handle one oddity of C++ [over.ics.ref] at this
4191 // point, which is that, due to p2 (which short-circuits reference
4192 // binding by only attempting a simple conversion for non-direct
4193 // bindings) and p3's strange wording, we allow a const volatile
4194 // reference to bind to an rvalue. Hence the check for the presence
4195 // of "const" rather than checking for "const" being the only
4196 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004197 // This is also the point where rvalue references and lvalue inits no longer
4198 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004199 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004200 return ICS;
4201
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004202 // -- If the initializer expression
4203 //
4204 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004205 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004206 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4207 (InitCategory.isXValue() ||
4208 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4209 (InitCategory.isLValue() && T2->isFunctionType()))) {
4210 ICS.setStandard();
4211 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004212 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004213 : ObjCConversion? ICK_Compatible_Conversion
4214 : ICK_Identity;
4215 ICS.Standard.Third = ICK_Identity;
4216 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4217 ICS.Standard.setToType(0, T2);
4218 ICS.Standard.setToType(1, T1);
4219 ICS.Standard.setToType(2, T1);
4220 ICS.Standard.ReferenceBinding = true;
4221 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4222 // binding unless we're binding to a class prvalue.
4223 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4224 // allow the use of rvalue references in C++98/03 for the benefit of
4225 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004226 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004227 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004228 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004229 ICS.Standard.IsLvalueReference = !isRValRef;
4230 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004231 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004232 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004233 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004234 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004235 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004236 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004237
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004238 // -- has a class type (i.e., T2 is a class type), where T1 is not
4239 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004240 // an xvalue, class prvalue, or function lvalue of type
4241 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004242 // "cv3 T3",
4243 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004244 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004245 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004246 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004247 // class subobject).
4248 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004249 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004250 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4251 Init, T2, /*AllowRvalues=*/true,
4252 AllowExplicit)) {
4253 // In the second case, if the reference is an rvalue reference
4254 // and the second standard conversion sequence of the
4255 // user-defined conversion sequence includes an lvalue-to-rvalue
4256 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004257 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004258 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4259 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4260
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004261 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004262 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004263
Douglas Gregorabe183d2010-04-13 16:31:36 +00004264 // -- Otherwise, a temporary of type "cv1 T1" is created and
4265 // initialized from the initializer expression using the
4266 // rules for a non-reference copy initialization (8.5). The
4267 // reference is then bound to the temporary. If T1 is
4268 // reference-related to T2, cv1 must be the same
4269 // cv-qualification as, or greater cv-qualification than,
4270 // cv2; otherwise, the program is ill-formed.
4271 if (RefRelationship == Sema::Ref_Related) {
4272 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4273 // we would be reference-compatible or reference-compatible with
4274 // added qualification. But that wasn't the case, so the reference
4275 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004276 //
4277 // Note that we only want to check address spaces and cvr-qualifiers here.
4278 // ObjC GC and lifetime qualifiers aren't important.
4279 Qualifiers T1Quals = T1.getQualifiers();
4280 Qualifiers T2Quals = T2.getQualifiers();
4281 T1Quals.removeObjCGCAttr();
4282 T1Quals.removeObjCLifetime();
4283 T2Quals.removeObjCGCAttr();
4284 T2Quals.removeObjCLifetime();
4285 if (!T1Quals.compatiblyIncludes(T2Quals))
4286 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004287 }
4288
4289 // If at least one of the types is a class type, the types are not
4290 // related, and we aren't allowed any user conversions, the
4291 // reference binding fails. This case is important for breaking
4292 // recursion, since TryImplicitConversion below will attempt to
4293 // create a temporary through the use of a copy constructor.
4294 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4295 (T1->isRecordType() || T2->isRecordType()))
4296 return ICS;
4297
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004298 // If T1 is reference-related to T2 and the reference is an rvalue
4299 // reference, the initializer expression shall not be an lvalue.
4300 if (RefRelationship >= Sema::Ref_Related &&
4301 isRValRef && Init->Classify(S.Context).isLValue())
4302 return ICS;
4303
Douglas Gregorabe183d2010-04-13 16:31:36 +00004304 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004305 // When a parameter of reference type is not bound directly to
4306 // an argument expression, the conversion sequence is the one
4307 // required to convert the argument expression to the
4308 // underlying type of the reference according to
4309 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4310 // to copy-initializing a temporary of the underlying type with
4311 // the argument expression. Any difference in top-level
4312 // cv-qualification is subsumed by the initialization itself
4313 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004314 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4315 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004316 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004317 /*CStyle=*/false,
4318 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004319
4320 // Of course, that's still a reference binding.
4321 if (ICS.isStandard()) {
4322 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004323 ICS.Standard.IsLvalueReference = !isRValRef;
4324 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4325 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004326 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004327 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004328 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004329 // Don't allow rvalue references to bind to lvalues.
4330 if (DeclType->isRValueReferenceType()) {
4331 if (const ReferenceType *RefType
4332 = ICS.UserDefined.ConversionFunction->getResultType()
4333 ->getAs<LValueReferenceType>()) {
4334 if (!RefType->getPointeeType()->isFunctionType()) {
4335 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4336 DeclType);
4337 return ICS;
4338 }
4339 }
4340 }
4341
Douglas Gregorabe183d2010-04-13 16:31:36 +00004342 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004343 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4344 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4345 ICS.UserDefined.After.BindsToRvalue = true;
4346 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4347 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004348 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004349
Douglas Gregorabe183d2010-04-13 16:31:36 +00004350 return ICS;
4351}
4352
Sebastian Redl5405b812011-10-16 18:19:34 +00004353static ImplicitConversionSequence
4354TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4355 bool SuppressUserConversions,
4356 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004357 bool AllowObjCWritebackConversion,
4358 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004359
4360/// TryListConversion - Try to copy-initialize a value of type ToType from the
4361/// initializer list From.
4362static ImplicitConversionSequence
4363TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4364 bool SuppressUserConversions,
4365 bool InOverloadResolution,
4366 bool AllowObjCWritebackConversion) {
4367 // C++11 [over.ics.list]p1:
4368 // When an argument is an initializer list, it is not an expression and
4369 // special rules apply for converting it to a parameter type.
4370
4371 ImplicitConversionSequence Result;
4372 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004373 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004374
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004375 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004376 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004377 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004378 return Result;
4379
Sebastian Redl5405b812011-10-16 18:19:34 +00004380 // C++11 [over.ics.list]p2:
4381 // If the parameter type is std::initializer_list<X> or "array of X" and
4382 // all the elements can be implicitly converted to X, the implicit
4383 // conversion sequence is the worst conversion necessary to convert an
4384 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004385 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004386 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004387 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004388 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004389 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004390 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004391 if (!X.isNull()) {
4392 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4393 Expr *Init = From->getInit(i);
4394 ImplicitConversionSequence ICS =
4395 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4396 InOverloadResolution,
4397 AllowObjCWritebackConversion);
4398 // If a single element isn't convertible, fail.
4399 if (ICS.isBad()) {
4400 Result = ICS;
4401 break;
4402 }
4403 // Otherwise, look for the worst conversion.
4404 if (Result.isBad() ||
4405 CompareImplicitConversionSequences(S, ICS, Result) ==
4406 ImplicitConversionSequence::Worse)
4407 Result = ICS;
4408 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004409
4410 // For an empty list, we won't have computed any conversion sequence.
4411 // Introduce the identity conversion sequence.
4412 if (From->getNumInits() == 0) {
4413 Result.setStandard();
4414 Result.Standard.setAsIdentityConversion();
4415 Result.Standard.setFromType(ToType);
4416 Result.Standard.setAllToTypes(ToType);
4417 }
4418
Sebastian Redlfe592282012-01-17 22:49:48 +00004419 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004420 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004421 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004422 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004423
4424 // C++11 [over.ics.list]p3:
4425 // Otherwise, if the parameter is a non-aggregate class X and overload
4426 // resolution chooses a single best constructor [...] the implicit
4427 // conversion sequence is a user-defined conversion sequence. If multiple
4428 // constructors are viable but none is better than the others, the
4429 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004430 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4431 // This function can deal with initializer lists.
4432 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4433 /*AllowExplicit=*/false,
4434 InOverloadResolution, /*CStyle=*/false,
4435 AllowObjCWritebackConversion);
4436 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004437 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004438 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004439
4440 // C++11 [over.ics.list]p4:
4441 // Otherwise, if the parameter has an aggregate type which can be
4442 // initialized from the initializer list [...] the implicit conversion
4443 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004444 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004445 // Type is an aggregate, argument is an init list. At this point it comes
4446 // down to checking whether the initialization works.
4447 // FIXME: Find out whether this parameter is consumed or not.
4448 InitializedEntity Entity =
4449 InitializedEntity::InitializeParameter(S.Context, ToType,
4450 /*Consumed=*/false);
4451 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4452 Result.setUserDefined();
4453 Result.UserDefined.Before.setAsIdentityConversion();
4454 // Initializer lists don't have a type.
4455 Result.UserDefined.Before.setFromType(QualType());
4456 Result.UserDefined.Before.setAllToTypes(QualType());
4457
4458 Result.UserDefined.After.setAsIdentityConversion();
4459 Result.UserDefined.After.setFromType(ToType);
4460 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004461 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004462 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004463 return Result;
4464 }
4465
4466 // C++11 [over.ics.list]p5:
4467 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004468 if (ToType->isReferenceType()) {
4469 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4470 // mention initializer lists in any way. So we go by what list-
4471 // initialization would do and try to extrapolate from that.
4472
4473 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4474
4475 // If the initializer list has a single element that is reference-related
4476 // to the parameter type, we initialize the reference from that.
4477 if (From->getNumInits() == 1) {
4478 Expr *Init = From->getInit(0);
4479
4480 QualType T2 = Init->getType();
4481
4482 // If the initializer is the address of an overloaded function, try
4483 // to resolve the overloaded function. If all goes well, T2 is the
4484 // type of the resulting function.
4485 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4486 DeclAccessPair Found;
4487 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4488 Init, ToType, false, Found))
4489 T2 = Fn->getType();
4490 }
4491
4492 // Compute some basic properties of the types and the initializer.
4493 bool dummy1 = false;
4494 bool dummy2 = false;
4495 bool dummy3 = false;
4496 Sema::ReferenceCompareResult RefRelationship
4497 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4498 dummy2, dummy3);
4499
4500 if (RefRelationship >= Sema::Ref_Related)
4501 return TryReferenceInit(S, Init, ToType,
4502 /*FIXME:*/From->getLocStart(),
4503 SuppressUserConversions,
4504 /*AllowExplicit=*/false);
4505 }
4506
4507 // Otherwise, we bind the reference to a temporary created from the
4508 // initializer list.
4509 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4510 InOverloadResolution,
4511 AllowObjCWritebackConversion);
4512 if (Result.isFailure())
4513 return Result;
4514 assert(!Result.isEllipsis() &&
4515 "Sub-initialization cannot result in ellipsis conversion.");
4516
4517 // Can we even bind to a temporary?
4518 if (ToType->isRValueReferenceType() ||
4519 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4520 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4521 Result.UserDefined.After;
4522 SCS.ReferenceBinding = true;
4523 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4524 SCS.BindsToRvalue = true;
4525 SCS.BindsToFunctionLvalue = false;
4526 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4527 SCS.ObjCLifetimeConversionBinding = false;
4528 } else
4529 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4530 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004531 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004532 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004533
4534 // C++11 [over.ics.list]p6:
4535 // Otherwise, if the parameter type is not a class:
4536 if (!ToType->isRecordType()) {
4537 // - if the initializer list has one element, the implicit conversion
4538 // sequence is the one required to convert the element to the
4539 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004540 unsigned NumInits = From->getNumInits();
4541 if (NumInits == 1)
4542 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4543 SuppressUserConversions,
4544 InOverloadResolution,
4545 AllowObjCWritebackConversion);
4546 // - if the initializer list has no elements, the implicit conversion
4547 // sequence is the identity conversion.
4548 else if (NumInits == 0) {
4549 Result.setStandard();
4550 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004551 Result.Standard.setFromType(ToType);
4552 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004553 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004554 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004555 return Result;
4556 }
4557
4558 // C++11 [over.ics.list]p7:
4559 // In all cases other than those enumerated above, no conversion is possible
4560 return Result;
4561}
4562
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004563/// TryCopyInitialization - Try to copy-initialize a value of type
4564/// ToType from the expression From. Return the implicit conversion
4565/// sequence required to pass this argument, which may be a bad
4566/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004567/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004568/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004569static ImplicitConversionSequence
4570TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004571 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004572 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004573 bool AllowObjCWritebackConversion,
4574 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004575 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4576 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4577 InOverloadResolution,AllowObjCWritebackConversion);
4578
Douglas Gregorabe183d2010-04-13 16:31:36 +00004579 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004580 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004581 /*FIXME:*/From->getLocStart(),
4582 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004583 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004584
John McCall120d63c2010-08-24 20:38:10 +00004585 return TryImplicitConversion(S, From, ToType,
4586 SuppressUserConversions,
4587 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004588 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004589 /*CStyle=*/false,
4590 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004591}
4592
Anna Zaksf3546ee2011-07-28 19:46:48 +00004593static bool TryCopyInitialization(const CanQualType FromQTy,
4594 const CanQualType ToQTy,
4595 Sema &S,
4596 SourceLocation Loc,
4597 ExprValueKind FromVK) {
4598 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4599 ImplicitConversionSequence ICS =
4600 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4601
4602 return !ICS.isBad();
4603}
4604
Douglas Gregor96176b32008-11-18 23:14:02 +00004605/// TryObjectArgumentInitialization - Try to initialize the object
4606/// parameter of the given member function (@c Method) from the
4607/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004608static ImplicitConversionSequence
4609TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004610 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004611 CXXMethodDecl *Method,
4612 CXXRecordDecl *ActingContext) {
4613 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004614 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4615 // const volatile object.
4616 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4617 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004618 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004619
4620 // Set up the conversion sequence as a "bad" conversion, to allow us
4621 // to exit early.
4622 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004623
4624 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004625 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004626 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004627 FromType = PT->getPointeeType();
4628
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004629 // When we had a pointer, it's implicitly dereferenced, so we
4630 // better have an lvalue.
4631 assert(FromClassification.isLValue());
4632 }
4633
Anders Carlssona552f7c2009-05-01 18:34:30 +00004634 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004635
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004636 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004638 // parameter is
4639 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004640 // - "lvalue reference to cv X" for functions declared without a
4641 // ref-qualifier or with the & ref-qualifier
4642 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004643 // ref-qualifier
4644 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004645 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004646 // cv-qualification on the member function declaration.
4647 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004648 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004649 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004650 // (C++ [over.match.funcs]p5). We perform a simplified version of
4651 // reference binding here, that allows class rvalues to bind to
4652 // non-constant references.
4653
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004654 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004655 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004656 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004657 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004658 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004659 ICS.setBad(BadConversionSequence::bad_qualifiers,
4660 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004661 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004662 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004663
4664 // Check that we have either the same type or a derived type. It
4665 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004666 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004667 ImplicitConversionKind SecondKind;
4668 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4669 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004670 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004671 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004672 else {
John McCallb1bdc622010-02-25 01:37:24 +00004673 ICS.setBad(BadConversionSequence::unrelated_class,
4674 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004675 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004676 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004677
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004678 // Check the ref-qualifier.
4679 switch (Method->getRefQualifier()) {
4680 case RQ_None:
4681 // Do nothing; we don't care about lvalueness or rvalueness.
4682 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004683
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004684 case RQ_LValue:
4685 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4686 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004687 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004688 ImplicitParamType);
4689 return ICS;
4690 }
4691 break;
4692
4693 case RQ_RValue:
4694 if (!FromClassification.isRValue()) {
4695 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004696 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004697 ImplicitParamType);
4698 return ICS;
4699 }
4700 break;
4701 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004702
Douglas Gregor96176b32008-11-18 23:14:02 +00004703 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004704 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004705 ICS.Standard.setAsIdentityConversion();
4706 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004707 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004708 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004709 ICS.Standard.ReferenceBinding = true;
4710 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004712 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004713 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4714 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4715 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004716 return ICS;
4717}
4718
4719/// PerformObjectArgumentInitialization - Perform initialization of
4720/// the implicit object parameter for the given Method with the given
4721/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004722ExprResult
4723Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004724 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004725 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004726 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004727 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004728 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004729 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004730
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004731 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004732 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004733 FromRecordType = PT->getPointeeType();
4734 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004735 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004736 } else {
4737 FromRecordType = From->getType();
4738 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004739 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004740 }
4741
John McCall701c89e2009-12-03 04:06:58 +00004742 // Note that we always use the true parent context when performing
4743 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004744 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004745 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4746 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004747 if (ICS.isBad()) {
4748 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4749 Qualifiers FromQs = FromRecordType.getQualifiers();
4750 Qualifiers ToQs = DestType.getQualifiers();
4751 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4752 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004753 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004754 diag::err_member_function_call_bad_cvr)
4755 << Method->getDeclName() << FromRecordType << (CVR - 1)
4756 << From->getSourceRange();
4757 Diag(Method->getLocation(), diag::note_previous_decl)
4758 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004759 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004760 }
4761 }
4762
Daniel Dunbar96a00142012-03-09 18:35:03 +00004763 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004764 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004765 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004766 }
Mike Stump1eb44332009-09-09 15:08:12 +00004767
John Wiegley429bb272011-04-08 18:41:53 +00004768 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4769 ExprResult FromRes =
4770 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4771 if (FromRes.isInvalid())
4772 return ExprError();
4773 From = FromRes.take();
4774 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004775
Douglas Gregor5fccd362010-03-03 23:55:11 +00004776 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004777 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004778 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004779 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004780}
4781
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004782/// TryContextuallyConvertToBool - Attempt to contextually convert the
4783/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004784static ImplicitConversionSequence
4785TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004786 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004787 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004788 // FIXME: Are these flags correct?
4789 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004790 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004791 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004792 /*CStyle=*/false,
4793 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004794}
4795
4796/// PerformContextuallyConvertToBool - Perform a contextual conversion
4797/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004798ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004799 if (checkPlaceholderForOverload(*this, From))
4800 return ExprError();
4801
John McCall120d63c2010-08-24 20:38:10 +00004802 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004803 if (!ICS.isBad())
4804 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004805
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004806 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004807 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004808 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004809 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004810 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004811}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004812
Richard Smith8ef7b202012-01-18 23:55:52 +00004813/// Check that the specified conversion is permitted in a converted constant
4814/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4815/// is acceptable.
4816static bool CheckConvertedConstantConversions(Sema &S,
4817 StandardConversionSequence &SCS) {
4818 // Since we know that the target type is an integral or unscoped enumeration
4819 // type, most conversion kinds are impossible. All possible First and Third
4820 // conversions are fine.
4821 switch (SCS.Second) {
4822 case ICK_Identity:
4823 case ICK_Integral_Promotion:
4824 case ICK_Integral_Conversion:
4825 return true;
4826
4827 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004828 // Conversion from an integral or unscoped enumeration type to bool is
4829 // classified as ICK_Boolean_Conversion, but it's also an integral
4830 // conversion, so it's permitted in a converted constant expression.
4831 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4832 SCS.getToType(2)->isBooleanType();
4833
Richard Smith8ef7b202012-01-18 23:55:52 +00004834 case ICK_Floating_Integral:
4835 case ICK_Complex_Real:
4836 return false;
4837
4838 case ICK_Lvalue_To_Rvalue:
4839 case ICK_Array_To_Pointer:
4840 case ICK_Function_To_Pointer:
4841 case ICK_NoReturn_Adjustment:
4842 case ICK_Qualification:
4843 case ICK_Compatible_Conversion:
4844 case ICK_Vector_Conversion:
4845 case ICK_Vector_Splat:
4846 case ICK_Derived_To_Base:
4847 case ICK_Pointer_Conversion:
4848 case ICK_Pointer_Member:
4849 case ICK_Block_Pointer_Conversion:
4850 case ICK_Writeback_Conversion:
4851 case ICK_Floating_Promotion:
4852 case ICK_Complex_Promotion:
4853 case ICK_Complex_Conversion:
4854 case ICK_Floating_Conversion:
4855 case ICK_TransparentUnionConversion:
4856 llvm_unreachable("unexpected second conversion kind");
4857
4858 case ICK_Num_Conversion_Kinds:
4859 break;
4860 }
4861
4862 llvm_unreachable("unknown conversion kind");
4863}
4864
4865/// CheckConvertedConstantExpression - Check that the expression From is a
4866/// converted constant expression of type T, perform the conversion and produce
4867/// the converted expression, per C++11 [expr.const]p3.
4868ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4869 llvm::APSInt &Value,
4870 CCEKind CCE) {
4871 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4872 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4873
4874 if (checkPlaceholderForOverload(*this, From))
4875 return ExprError();
4876
4877 // C++11 [expr.const]p3 with proposed wording fixes:
4878 // A converted constant expression of type T is a core constant expression,
4879 // implicitly converted to a prvalue of type T, where the converted
4880 // expression is a literal constant expression and the implicit conversion
4881 // sequence contains only user-defined conversions, lvalue-to-rvalue
4882 // conversions, integral promotions, and integral conversions other than
4883 // narrowing conversions.
4884 ImplicitConversionSequence ICS =
4885 TryImplicitConversion(From, T,
4886 /*SuppressUserConversions=*/false,
4887 /*AllowExplicit=*/false,
4888 /*InOverloadResolution=*/false,
4889 /*CStyle=*/false,
4890 /*AllowObjcWritebackConversion=*/false);
4891 StandardConversionSequence *SCS = 0;
4892 switch (ICS.getKind()) {
4893 case ImplicitConversionSequence::StandardConversion:
4894 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004895 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004896 diag::err_typecheck_converted_constant_expression_disallowed)
4897 << From->getType() << From->getSourceRange() << T;
4898 SCS = &ICS.Standard;
4899 break;
4900 case ImplicitConversionSequence::UserDefinedConversion:
4901 // We are converting from class type to an integral or enumeration type, so
4902 // the Before sequence must be trivial.
4903 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004904 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004905 diag::err_typecheck_converted_constant_expression_disallowed)
4906 << From->getType() << From->getSourceRange() << T;
4907 SCS = &ICS.UserDefined.After;
4908 break;
4909 case ImplicitConversionSequence::AmbiguousConversion:
4910 case ImplicitConversionSequence::BadConversion:
4911 if (!DiagnoseMultipleUserDefinedConversion(From, T))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004912 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004913 diag::err_typecheck_converted_constant_expression)
4914 << From->getType() << From->getSourceRange() << T;
4915 return ExprError();
4916
4917 case ImplicitConversionSequence::EllipsisConversion:
4918 llvm_unreachable("ellipsis conversion in converted constant expression");
4919 }
4920
4921 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4922 if (Result.isInvalid())
4923 return Result;
4924
4925 // Check for a narrowing implicit conversion.
4926 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004927 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004928 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4929 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004930 case NK_Variable_Narrowing:
4931 // Implicit conversion to a narrower type, and the value is not a constant
4932 // expression. We'll diagnose this in a moment.
4933 case NK_Not_Narrowing:
4934 break;
4935
4936 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004937 Diag(From->getLocStart(),
4938 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4939 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004940 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004941 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004942 break;
4943
4944 case NK_Type_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004945 Diag(From->getLocStart(),
4946 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4947 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004948 << CCE << /*Constant*/0 << From->getType() << T;
4949 break;
4950 }
4951
4952 // Check the expression is a constant expression.
4953 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4954 Expr::EvalResult Eval;
4955 Eval.Diag = &Notes;
4956
4957 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4958 // The expression can't be folded, so we can't keep it at this position in
4959 // the AST.
4960 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004961 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004962 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004963
4964 if (Notes.empty()) {
4965 // It's a constant expression.
4966 return Result;
4967 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004968 }
4969
4970 // It's not a constant expression. Produce an appropriate diagnostic.
4971 if (Notes.size() == 1 &&
4972 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4973 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4974 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004975 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004976 << CCE << From->getSourceRange();
4977 for (unsigned I = 0; I < Notes.size(); ++I)
4978 Diag(Notes[I].first, Notes[I].second);
4979 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004980 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004981}
4982
John McCall0bcc9bc2011-09-09 06:11:02 +00004983/// dropPointerConversions - If the given standard conversion sequence
4984/// involves any pointer conversions, remove them. This may change
4985/// the result type of the conversion sequence.
4986static void dropPointerConversion(StandardConversionSequence &SCS) {
4987 if (SCS.Second == ICK_Pointer_Conversion) {
4988 SCS.Second = ICK_Identity;
4989 SCS.Third = ICK_Identity;
4990 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4991 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004992}
John McCall120d63c2010-08-24 20:38:10 +00004993
John McCall0bcc9bc2011-09-09 06:11:02 +00004994/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4995/// convert the expression From to an Objective-C pointer type.
4996static ImplicitConversionSequence
4997TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4998 // Do an implicit conversion to 'id'.
4999 QualType Ty = S.Context.getObjCIdType();
5000 ImplicitConversionSequence ICS
5001 = TryImplicitConversion(S, From, Ty,
5002 // FIXME: Are these flags correct?
5003 /*SuppressUserConversions=*/false,
5004 /*AllowExplicit=*/true,
5005 /*InOverloadResolution=*/false,
5006 /*CStyle=*/false,
5007 /*AllowObjCWritebackConversion=*/false);
5008
5009 // Strip off any final conversions to 'id'.
5010 switch (ICS.getKind()) {
5011 case ImplicitConversionSequence::BadConversion:
5012 case ImplicitConversionSequence::AmbiguousConversion:
5013 case ImplicitConversionSequence::EllipsisConversion:
5014 break;
5015
5016 case ImplicitConversionSequence::UserDefinedConversion:
5017 dropPointerConversion(ICS.UserDefined.After);
5018 break;
5019
5020 case ImplicitConversionSequence::StandardConversion:
5021 dropPointerConversion(ICS.Standard);
5022 break;
5023 }
5024
5025 return ICS;
5026}
5027
5028/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5029/// conversion of the expression From to an Objective-C pointer type.
5030ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005031 if (checkPlaceholderForOverload(*this, From))
5032 return ExprError();
5033
John McCallc12c5bb2010-05-15 11:32:37 +00005034 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005035 ImplicitConversionSequence ICS =
5036 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005037 if (!ICS.isBad())
5038 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005039 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005040}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005041
Richard Smithf39aec12012-02-04 07:07:42 +00005042/// Determine whether the provided type is an integral type, or an enumeration
5043/// type of a permitted flavor.
5044static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5045 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5046 : T->isIntegralOrUnscopedEnumerationType();
5047}
5048
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005049/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005050/// enumeration type.
5051///
5052/// This routine will attempt to convert an expression of class type to an
5053/// integral or enumeration type, if that class type only has a single
5054/// conversion to an integral or enumeration type.
5055///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005056/// \param Loc The source location of the construct that requires the
5057/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005058///
James Dennett40ae6662012-06-22 08:52:37 +00005059/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005060///
James Dennett40ae6662012-06-22 08:52:37 +00005061/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005062///
Richard Smithf39aec12012-02-04 07:07:42 +00005063/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5064/// enumerations should be considered.
5065///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005066/// \returns The expression, converted to an integral or enumeration type if
5067/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005068ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005069Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005070 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005071 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005072 // We can't perform any more checking for type-dependent expressions.
5073 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005074 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005075
Eli Friedmanceccab92012-01-26 00:26:18 +00005076 // Process placeholders immediately.
5077 if (From->hasPlaceholderType()) {
5078 ExprResult result = CheckPlaceholderExpr(From);
5079 if (result.isInvalid()) return result;
5080 From = result.take();
5081 }
5082
Douglas Gregorc30614b2010-06-29 23:17:37 +00005083 // If the expression already has integral or enumeration type, we're golden.
5084 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005085 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005086 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005087
5088 // FIXME: Check for missing '()' if T is a function type?
5089
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005090 // 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 +00005091 // expression of integral or enumeration type.
5092 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005093 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005094 if (!Diagnoser.Suppress)
5095 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005096 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005097 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005098
Douglas Gregorc30614b2010-06-29 23:17:37 +00005099 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005100 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005101 ICEConvertDiagnoser &Diagnoser;
5102 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005103
Douglas Gregorab41fe92012-05-04 22:38:52 +00005104 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5105 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005106
5107 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005108 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005109 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005110 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005111
5112 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005113 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005114
Douglas Gregorc30614b2010-06-29 23:17:37 +00005115 // Look for a conversion to an integral or enumeration type.
5116 UnresolvedSet<4> ViableConversions;
5117 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005118 std::pair<CXXRecordDecl::conversion_iterator,
5119 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005120 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005121
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005122 bool HadMultipleCandidates
5123 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005124
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005125 for (CXXRecordDecl::conversion_iterator
5126 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005127 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005128 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5129 if (isIntegralOrEnumerationType(
5130 Conversion->getConversionType().getNonReferenceType(),
5131 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005132 if (Conversion->isExplicit())
5133 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5134 else
5135 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5136 }
Richard Smithf39aec12012-02-04 07:07:42 +00005137 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005138 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005139
Douglas Gregorc30614b2010-06-29 23:17:37 +00005140 switch (ViableConversions.size()) {
5141 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005142 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005143 DeclAccessPair Found = ExplicitConversions[0];
5144 CXXConversionDecl *Conversion
5145 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005146
Douglas Gregorc30614b2010-06-29 23:17:37 +00005147 // The user probably meant to invoke the given explicit
5148 // conversion; use it.
5149 QualType ConvTy
5150 = Conversion->getConversionType().getNonReferenceType();
5151 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005152 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005153
Douglas Gregorab41fe92012-05-04 22:38:52 +00005154 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005155 << FixItHint::CreateInsertion(From->getLocStart(),
5156 "static_cast<" + TypeStr + ">(")
5157 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5158 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005159 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005160
5161 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005162 // explicit conversion function.
5163 if (isSFINAEContext())
5164 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005165
Douglas Gregorc30614b2010-06-29 23:17:37 +00005166 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005167 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5168 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005169 if (Result.isInvalid())
5170 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005171 // Record usage of conversion in an implicit cast.
5172 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5173 CK_UserDefinedConversion,
5174 Result.get(), 0,
5175 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005176 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005177
Douglas Gregorc30614b2010-06-29 23:17:37 +00005178 // We'll complain below about a non-integral condition type.
5179 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005180
Douglas Gregorc30614b2010-06-29 23:17:37 +00005181 case 1: {
5182 // Apply this conversion.
5183 DeclAccessPair Found = ViableConversions[0];
5184 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005185
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005186 CXXConversionDecl *Conversion
5187 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5188 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005190 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005191 if (isSFINAEContext())
5192 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005193
Douglas Gregorab41fe92012-05-04 22:38:52 +00005194 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5195 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005196 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005197
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005198 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5199 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005200 if (Result.isInvalid())
5201 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005202 // Record usage of conversion in an implicit cast.
5203 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5204 CK_UserDefinedConversion,
5205 Result.get(), 0,
5206 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005207 break;
5208 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005209
Douglas Gregorc30614b2010-06-29 23:17:37 +00005210 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005211 if (Diagnoser.Suppress)
5212 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005213
Douglas Gregorab41fe92012-05-04 22:38:52 +00005214 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005215 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5216 CXXConversionDecl *Conv
5217 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5218 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005219 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005220 }
John McCall9ae2f072010-08-23 23:25:46 +00005221 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005222 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005223
Richard Smith282e7e62012-02-04 09:53:13 +00005224 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005225 !Diagnoser.Suppress) {
5226 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5227 << From->getSourceRange();
5228 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005229
Eli Friedmanceccab92012-01-26 00:26:18 +00005230 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005231}
5232
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005233/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005234/// candidate functions, using the given function call arguments. If
5235/// @p SuppressUserConversions, then don't allow user-defined
5236/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005237///
James Dennett699c9042012-06-15 07:13:21 +00005238/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005239/// based on an incomplete set of function arguments. This feature is used by
5240/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005241void
5242Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005243 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005244 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005245 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005246 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005247 bool PartialOverloading,
5248 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005249 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005250 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005251 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005252 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005253 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005254
Douglas Gregor88a35142008-12-22 05:46:06 +00005255 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005256 if (!isa<CXXConstructorDecl>(Method)) {
5257 // If we get here, it's because we're calling a member function
5258 // that is named without a member access expression (e.g.,
5259 // "this->f") that was either written explicitly or created
5260 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005261 // function, e.g., X::f(). We use an empty type for the implied
5262 // object argument (C++ [over.call.func]p3), and the acting context
5263 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005264 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005265 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005266 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005267 return;
5268 }
5269 // We treat a constructor like a non-member function, since its object
5270 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005271 }
5272
Douglas Gregorfd476482009-11-13 23:59:09 +00005273 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005274 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005275
Douglas Gregor7edfb692009-11-23 12:27:39 +00005276 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005277 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005278
Douglas Gregor66724ea2009-11-14 01:20:54 +00005279 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5280 // C++ [class.copy]p3:
5281 // A member function template is never instantiated to perform the copy
5282 // of a class object to an object of its class type.
5283 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005284 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005285 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005286 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5287 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005288 return;
5289 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005290
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005291 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005292 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005293 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005294 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005295 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005296 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005297 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005298 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005299
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005300 unsigned NumArgsInProto = Proto->getNumArgs();
5301
5302 // (C++ 13.3.2p2): A candidate function having fewer than m
5303 // parameters is viable only if it has an ellipsis in its parameter
5304 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005305 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005306 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005307 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005308 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005309 return;
5310 }
5311
5312 // (C++ 13.3.2p2): A candidate function having more than m parameters
5313 // is viable only if the (m+1)st parameter has a default argument
5314 // (8.3.6). For the purposes of overload resolution, the
5315 // parameter list is truncated on the right, so that there are
5316 // exactly m parameters.
5317 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005318 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005319 // Not enough arguments.
5320 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005321 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005322 return;
5323 }
5324
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005325 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005326 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005327 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5328 if (CheckCUDATarget(Caller, Function)) {
5329 Candidate.Viable = false;
5330 Candidate.FailureKind = ovl_fail_bad_target;
5331 return;
5332 }
5333
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005334 // Determine the implicit conversion sequences for each of the
5335 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005336 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005337 if (ArgIdx < NumArgsInProto) {
5338 // (C++ 13.3.2p3): for F to be a viable function, there shall
5339 // exist for each argument an implicit conversion sequence
5340 // (13.3.3.1) that converts that argument to the corresponding
5341 // parameter of F.
5342 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005343 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005344 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005345 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005346 /*InOverloadResolution=*/true,
5347 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005348 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005349 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005350 if (Candidate.Conversions[ArgIdx].isBad()) {
5351 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005352 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005353 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005354 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005355 } else {
5356 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5357 // argument for which there is no corresponding parameter is
5358 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005359 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005360 }
5361 }
5362}
5363
Douglas Gregor063daf62009-03-13 18:40:31 +00005364/// \brief Add all of the function declarations in the given function set to
5365/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005366void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005367 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005368 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005369 bool SuppressUserConversions,
5370 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005371 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005372 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5373 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005374 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005375 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005376 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005377 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005378 Args.slice(1), CandidateSet,
5379 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005380 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005381 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005382 SuppressUserConversions);
5383 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005384 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005385 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5386 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005387 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005388 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005389 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005390 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005391 Args[0]->Classify(Context), Args.slice(1),
5392 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005393 else
John McCall9aa472c2010-03-19 07:35:19 +00005394 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005395 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005396 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005397 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005398 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005399}
5400
John McCall314be4e2009-11-17 07:50:12 +00005401/// AddMethodCandidate - Adds a named decl (which is some kind of
5402/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005403void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005404 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005405 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005406 Expr **Args, unsigned NumArgs,
5407 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005408 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005409 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005410 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005411
5412 if (isa<UsingShadowDecl>(Decl))
5413 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005414
John McCall314be4e2009-11-17 07:50:12 +00005415 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5416 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5417 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005418 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5419 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005420 ObjectType, ObjectClassification,
5421 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005422 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005423 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005424 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005425 ObjectType, ObjectClassification,
5426 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005427 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005428 }
5429}
5430
Douglas Gregor96176b32008-11-18 23:14:02 +00005431/// AddMethodCandidate - Adds the given C++ member function to the set
5432/// of candidate functions, using the given function call arguments
5433/// and the object argument (@c Object). For example, in a call
5434/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5435/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5436/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005437/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005438void
John McCall9aa472c2010-03-19 07:35:19 +00005439Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005440 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005441 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005442 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005443 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005444 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005445 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005446 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005447 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005448 assert(!isa<CXXConstructorDecl>(Method) &&
5449 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005450
Douglas Gregor3f396022009-09-28 04:47:19 +00005451 if (!CandidateSet.isNewCandidate(Method))
5452 return;
5453
Douglas Gregor7edfb692009-11-23 12:27:39 +00005454 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005455 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005456
Douglas Gregor96176b32008-11-18 23:14:02 +00005457 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005458 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005459 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005460 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005461 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005462 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005463 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005464
5465 unsigned NumArgsInProto = Proto->getNumArgs();
5466
5467 // (C++ 13.3.2p2): A candidate function having fewer than m
5468 // parameters is viable only if it has an ellipsis in its parameter
5469 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005470 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005471 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005472 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005473 return;
5474 }
5475
5476 // (C++ 13.3.2p2): A candidate function having more than m parameters
5477 // is viable only if the (m+1)st parameter has a default argument
5478 // (8.3.6). For the purposes of overload resolution, the
5479 // parameter list is truncated on the right, so that there are
5480 // exactly m parameters.
5481 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005482 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005483 // Not enough arguments.
5484 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005485 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005486 return;
5487 }
5488
5489 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005490
John McCall701c89e2009-12-03 04:06:58 +00005491 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005492 // The implicit object argument is ignored.
5493 Candidate.IgnoreObjectArgument = true;
5494 else {
5495 // Determine the implicit conversion sequence for the object
5496 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005497 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005498 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5499 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005500 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005501 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005502 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005503 return;
5504 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005505 }
5506
5507 // Determine the implicit conversion sequences for each of the
5508 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005509 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005510 if (ArgIdx < NumArgsInProto) {
5511 // (C++ 13.3.2p3): for F to be a viable function, there shall
5512 // exist for each argument an implicit conversion sequence
5513 // (13.3.3.1) that converts that argument to the corresponding
5514 // parameter of F.
5515 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005516 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005517 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005518 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005519 /*InOverloadResolution=*/true,
5520 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005521 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005522 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005523 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005524 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005525 break;
5526 }
5527 } else {
5528 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5529 // argument for which there is no corresponding parameter is
5530 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005531 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005532 }
5533 }
5534}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005535
Douglas Gregor6b906862009-08-21 00:16:32 +00005536/// \brief Add a C++ member function template as a candidate to the candidate
5537/// set, using template argument deduction to produce an appropriate member
5538/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005539void
Douglas Gregor6b906862009-08-21 00:16:32 +00005540Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005541 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005542 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005543 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005544 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005545 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005546 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005547 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005548 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005549 if (!CandidateSet.isNewCandidate(MethodTmpl))
5550 return;
5551
Douglas Gregor6b906862009-08-21 00:16:32 +00005552 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005553 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005554 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005555 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005556 // candidate functions in the usual way.113) A given name can refer to one
5557 // or more function templates and also to a set of overloaded non-template
5558 // functions. In such a case, the candidate functions generated from each
5559 // function template are combined with the set of non-template candidate
5560 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005561 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005562 FunctionDecl *Specialization = 0;
5563 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005564 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5565 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005566 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005567 Candidate.FoundDecl = FoundDecl;
5568 Candidate.Function = MethodTmpl->getTemplatedDecl();
5569 Candidate.Viable = false;
5570 Candidate.FailureKind = ovl_fail_bad_deduction;
5571 Candidate.IsSurrogate = false;
5572 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005573 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005574 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005575 Info);
5576 return;
5577 }
Mike Stump1eb44332009-09-09 15:08:12 +00005578
Douglas Gregor6b906862009-08-21 00:16:32 +00005579 // Add the function template specialization produced by template argument
5580 // deduction as a candidate.
5581 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005582 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005583 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005584 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005585 ActingContext, ObjectType, ObjectClassification, Args,
5586 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005587}
5588
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005589/// \brief Add a C++ function template specialization as a candidate
5590/// in the candidate set, using template argument deduction to produce
5591/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005592void
Douglas Gregore53060f2009-06-25 22:08:12 +00005593Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005594 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005595 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005596 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005597 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005598 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005599 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5600 return;
5601
Douglas Gregore53060f2009-06-25 22:08:12 +00005602 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005603 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005604 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005605 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005606 // candidate functions in the usual way.113) A given name can refer to one
5607 // or more function templates and also to a set of overloaded non-template
5608 // functions. In such a case, the candidate functions generated from each
5609 // function template are combined with the set of non-template candidate
5610 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005611 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005612 FunctionDecl *Specialization = 0;
5613 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005614 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5615 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005616 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005617 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005618 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5619 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005620 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005621 Candidate.IsSurrogate = false;
5622 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005623 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005624 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005625 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005626 return;
5627 }
Mike Stump1eb44332009-09-09 15:08:12 +00005628
Douglas Gregore53060f2009-06-25 22:08:12 +00005629 // Add the function template specialization produced by template argument
5630 // deduction as a candidate.
5631 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005632 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005633 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005634}
Mike Stump1eb44332009-09-09 15:08:12 +00005635
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005636/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005637/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005638/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005639/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005640/// (which may or may not be the same type as the type that the
5641/// conversion function produces).
5642void
5643Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005644 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005645 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005646 Expr *From, QualType ToType,
5647 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005648 assert(!Conversion->getDescribedFunctionTemplate() &&
5649 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005650 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005651 if (!CandidateSet.isNewCandidate(Conversion))
5652 return;
5653
Douglas Gregor7edfb692009-11-23 12:27:39 +00005654 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005655 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005656
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005657 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005658 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005659 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005660 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005661 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005662 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005663 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005664 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005665 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005666 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005667 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005668
Douglas Gregorbca39322010-08-19 15:37:02 +00005669 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005670 // For conversion functions, the function is considered to be a member of
5671 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005672 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005673 //
5674 // Determine the implicit conversion sequence for the implicit
5675 // object parameter.
5676 QualType ImplicitParamType = From->getType();
5677 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5678 ImplicitParamType = FromPtrType->getPointeeType();
5679 CXXRecordDecl *ConversionContext
5680 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005681
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005682 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005683 = TryObjectArgumentInitialization(*this, From->getType(),
5684 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005685 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005686
John McCall1d318332010-01-12 00:44:57 +00005687 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005688 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005689 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005690 return;
5691 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005692
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005693 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005694 // derived to base as such conversions are given Conversion Rank. They only
5695 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5696 QualType FromCanon
5697 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5698 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5699 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5700 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005701 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005702 return;
5703 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005704
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005705 // To determine what the conversion from the result of calling the
5706 // conversion function to the type we're eventually trying to
5707 // convert to (ToType), we need to synthesize a call to the
5708 // conversion function and attempt copy initialization from it. This
5709 // makes sure that we get the right semantics with respect to
5710 // lvalues/rvalues and the type. Fortunately, we can allocate this
5711 // call on the stack and we don't need its arguments to be
5712 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005713 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005714 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005715 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5716 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005717 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005718 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005719
Richard Smith87c1f1f2011-07-13 22:53:21 +00005720 QualType ConversionType = Conversion->getConversionType();
5721 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005722 Candidate.Viable = false;
5723 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5724 return;
5725 }
5726
Richard Smith87c1f1f2011-07-13 22:53:21 +00005727 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005728
Mike Stump1eb44332009-09-09 15:08:12 +00005729 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005730 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5731 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005732 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005733 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005734 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005735 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005736 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005737 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005738 /*InOverloadResolution=*/false,
5739 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005740
John McCall1d318332010-01-12 00:44:57 +00005741 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005742 case ImplicitConversionSequence::StandardConversion:
5743 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005744
Douglas Gregorc520c842010-04-12 23:42:09 +00005745 // C++ [over.ics.user]p3:
5746 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005747 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005748 // shall have exact match rank.
5749 if (Conversion->getPrimaryTemplate() &&
5750 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5751 Candidate.Viable = false;
5752 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5753 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005754
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005755 // C++0x [dcl.init.ref]p5:
5756 // In the second case, if the reference is an rvalue reference and
5757 // the second standard conversion sequence of the user-defined
5758 // conversion sequence includes an lvalue-to-rvalue conversion, the
5759 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005760 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005761 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5762 Candidate.Viable = false;
5763 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5764 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005765 break;
5766
5767 case ImplicitConversionSequence::BadConversion:
5768 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005769 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005770 break;
5771
5772 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005773 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005774 "Can only end up with a standard conversion sequence or failure");
5775 }
5776}
5777
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005778/// \brief Adds a conversion function template specialization
5779/// candidate to the overload set, using template argument deduction
5780/// to deduce the template arguments of the conversion function
5781/// template from the type that we are converting to (C++
5782/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005783void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005784Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005785 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005786 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005787 Expr *From, QualType ToType,
5788 OverloadCandidateSet &CandidateSet) {
5789 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5790 "Only conversion function templates permitted here");
5791
Douglas Gregor3f396022009-09-28 04:47:19 +00005792 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5793 return;
5794
Craig Topper93e45992012-09-19 02:26:47 +00005795 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005796 CXXConversionDecl *Specialization = 0;
5797 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005798 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005799 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005800 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005801 Candidate.FoundDecl = FoundDecl;
5802 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5803 Candidate.Viable = false;
5804 Candidate.FailureKind = ovl_fail_bad_deduction;
5805 Candidate.IsSurrogate = false;
5806 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005807 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005808 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005809 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005810 return;
5811 }
Mike Stump1eb44332009-09-09 15:08:12 +00005812
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005813 // Add the conversion function template specialization produced by
5814 // template argument deduction as a candidate.
5815 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005816 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005817 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005818}
5819
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005820/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5821/// converts the given @c Object to a function pointer via the
5822/// conversion function @c Conversion, and then attempts to call it
5823/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5824/// the type of function that we'll eventually be calling.
5825void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005826 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005827 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005828 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005829 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005830 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005831 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005832 if (!CandidateSet.isNewCandidate(Conversion))
5833 return;
5834
Douglas Gregor7edfb692009-11-23 12:27:39 +00005835 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005836 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005837
Ahmed Charles13a140c2012-02-25 11:00:22 +00005838 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005839 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005840 Candidate.Function = 0;
5841 Candidate.Surrogate = Conversion;
5842 Candidate.Viable = true;
5843 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005844 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005845 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005846
5847 // Determine the implicit conversion sequence for the implicit
5848 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005849 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005850 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005851 Object->Classify(Context),
5852 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005853 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005854 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005855 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005856 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005857 return;
5858 }
5859
5860 // The first conversion is actually a user-defined conversion whose
5861 // first conversion is ObjectInit's standard conversion (which is
5862 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005863 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005864 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005865 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005866 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005867 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005868 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005869 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005870 = Candidate.Conversions[0].UserDefined.Before;
5871 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5872
Mike Stump1eb44332009-09-09 15:08:12 +00005873 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005874 unsigned NumArgsInProto = Proto->getNumArgs();
5875
5876 // (C++ 13.3.2p2): A candidate function having fewer than m
5877 // parameters is viable only if it has an ellipsis in its parameter
5878 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005879 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005880 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005881 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005882 return;
5883 }
5884
5885 // Function types don't have any default arguments, so just check if
5886 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005887 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005888 // Not enough arguments.
5889 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005890 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005891 return;
5892 }
5893
5894 // Determine the implicit conversion sequences for each of the
5895 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005896 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005897 if (ArgIdx < NumArgsInProto) {
5898 // (C++ 13.3.2p3): for F to be a viable function, there shall
5899 // exist for each argument an implicit conversion sequence
5900 // (13.3.3.1) that converts that argument to the corresponding
5901 // parameter of F.
5902 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005903 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005904 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005905 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005906 /*InOverloadResolution=*/false,
5907 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005908 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005909 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005910 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005911 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005912 break;
5913 }
5914 } else {
5915 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5916 // argument for which there is no corresponding parameter is
5917 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005918 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005919 }
5920 }
5921}
5922
Douglas Gregor063daf62009-03-13 18:40:31 +00005923/// \brief Add overload candidates for overloaded operators that are
5924/// member functions.
5925///
5926/// Add the overloaded operator candidates that are member functions
5927/// for the operator Op that was used in an operator expression such
5928/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5929/// CandidateSet will store the added overload candidates. (C++
5930/// [over.match.oper]).
5931void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5932 SourceLocation OpLoc,
5933 Expr **Args, unsigned NumArgs,
5934 OverloadCandidateSet& CandidateSet,
5935 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005936 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5937
5938 // C++ [over.match.oper]p3:
5939 // For a unary operator @ with an operand of a type whose
5940 // cv-unqualified version is T1, and for a binary operator @ with
5941 // a left operand of a type whose cv-unqualified version is T1 and
5942 // a right operand of a type whose cv-unqualified version is T2,
5943 // three sets of candidate functions, designated member
5944 // candidates, non-member candidates and built-in candidates, are
5945 // constructed as follows:
5946 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005947
5948 // -- If T1 is a class type, the set of member candidates is the
5949 // result of the qualified lookup of T1::operator@
5950 // (13.3.1.1.1); otherwise, the set of member candidates is
5951 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005952 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005953 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005954 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005955 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005956
John McCalla24dc2e2009-11-17 02:14:36 +00005957 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5958 LookupQualifiedName(Operators, T1Rec->getDecl());
5959 Operators.suppressDiagnostics();
5960
Mike Stump1eb44332009-09-09 15:08:12 +00005961 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005962 OperEnd = Operators.end();
5963 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005964 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005965 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005966 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005967 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005968 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005969 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005970}
5971
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005972/// AddBuiltinCandidate - Add a candidate for a built-in
5973/// operator. ResultTy and ParamTys are the result and parameter types
5974/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005975/// arguments being passed to the candidate. IsAssignmentOperator
5976/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005977/// operator. NumContextualBoolArguments is the number of arguments
5978/// (at the beginning of the argument list) that will be contextually
5979/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005980void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005981 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005982 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005983 bool IsAssignmentOperator,
5984 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005985 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005986 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005987
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005988 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005989 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005990 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005991 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005992 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005993 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005994 Candidate.BuiltinTypes.ResultTy = ResultTy;
5995 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5996 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5997
5998 // Determine the implicit conversion sequences for each of the
5999 // arguments.
6000 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00006001 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006002 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006003 // C++ [over.match.oper]p4:
6004 // For the built-in assignment operators, conversions of the
6005 // left operand are restricted as follows:
6006 // -- no temporaries are introduced to hold the left operand, and
6007 // -- no user-defined conversions are applied to the left
6008 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006009 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006010 //
6011 // We block these conversions by turning off user-defined
6012 // conversions, since that is the only way that initialization of
6013 // a reference to a non-class type can occur from something that
6014 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006015 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006016 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006017 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006018 Candidate.Conversions[ArgIdx]
6019 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006020 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006021 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006022 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006023 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006024 /*InOverloadResolution=*/false,
6025 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006026 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006027 }
John McCall1d318332010-01-12 00:44:57 +00006028 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006029 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006030 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006031 break;
6032 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006033 }
6034}
6035
6036/// BuiltinCandidateTypeSet - A set of types that will be used for the
6037/// candidate operator functions for built-in operators (C++
6038/// [over.built]). The types are separated into pointer types and
6039/// enumeration types.
6040class BuiltinCandidateTypeSet {
6041 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006042 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006043
6044 /// PointerTypes - The set of pointer types that will be used in the
6045 /// built-in candidates.
6046 TypeSet PointerTypes;
6047
Sebastian Redl78eb8742009-04-19 21:53:20 +00006048 /// MemberPointerTypes - The set of member pointer types that will be
6049 /// used in the built-in candidates.
6050 TypeSet MemberPointerTypes;
6051
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006052 /// EnumerationTypes - The set of enumeration types that will be
6053 /// used in the built-in candidates.
6054 TypeSet EnumerationTypes;
6055
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006056 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006057 /// candidates.
6058 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006059
6060 /// \brief A flag indicating non-record types are viable candidates
6061 bool HasNonRecordTypes;
6062
6063 /// \brief A flag indicating whether either arithmetic or enumeration types
6064 /// were present in the candidate set.
6065 bool HasArithmeticOrEnumeralTypes;
6066
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006067 /// \brief A flag indicating whether the nullptr type was present in the
6068 /// candidate set.
6069 bool HasNullPtrType;
6070
Douglas Gregor5842ba92009-08-24 15:23:48 +00006071 /// Sema - The semantic analysis instance where we are building the
6072 /// candidate type set.
6073 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006074
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006075 /// Context - The AST context in which we will build the type sets.
6076 ASTContext &Context;
6077
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006078 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6079 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006080 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006081
6082public:
6083 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006084 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006085
Mike Stump1eb44332009-09-09 15:08:12 +00006086 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006087 : HasNonRecordTypes(false),
6088 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006089 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006090 SemaRef(SemaRef),
6091 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006092
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006093 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006094 SourceLocation Loc,
6095 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006096 bool AllowExplicitConversions,
6097 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006098
6099 /// pointer_begin - First pointer type found;
6100 iterator pointer_begin() { return PointerTypes.begin(); }
6101
Sebastian Redl78eb8742009-04-19 21:53:20 +00006102 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006103 iterator pointer_end() { return PointerTypes.end(); }
6104
Sebastian Redl78eb8742009-04-19 21:53:20 +00006105 /// member_pointer_begin - First member pointer type found;
6106 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6107
6108 /// member_pointer_end - Past the last member pointer type found;
6109 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6110
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006111 /// enumeration_begin - First enumeration type found;
6112 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6113
Sebastian Redl78eb8742009-04-19 21:53:20 +00006114 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006115 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006116
Douglas Gregor26bcf672010-05-19 03:21:00 +00006117 iterator vector_begin() { return VectorTypes.begin(); }
6118 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006119
6120 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6121 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006122 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006123};
6124
Sebastian Redl78eb8742009-04-19 21:53:20 +00006125/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006126/// the set of pointer types along with any more-qualified variants of
6127/// that type. For example, if @p Ty is "int const *", this routine
6128/// will add "int const *", "int const volatile *", "int const
6129/// restrict *", and "int const volatile restrict *" to the set of
6130/// pointer types. Returns true if the add of @p Ty itself succeeded,
6131/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006132///
6133/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006134bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006135BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6136 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006137
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006138 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006139 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006140 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006141
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006142 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006143 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006144 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006145 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006146 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6147 PointeeTy = PTy->getPointeeType();
6148 buildObjCPtr = true;
6149 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006150 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006151 }
6152
Sebastian Redla9efada2009-11-18 20:39:26 +00006153 // Don't add qualified variants of arrays. For one, they're not allowed
6154 // (the qualifier would sink to the element type), and for another, the
6155 // only overload situation where it matters is subscript or pointer +- int,
6156 // and those shouldn't have qualifier variants anyway.
6157 if (PointeeTy->isArrayType())
6158 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006159
John McCall0953e762009-09-24 19:53:00 +00006160 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006161 bool hasVolatile = VisibleQuals.hasVolatile();
6162 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006163
John McCall0953e762009-09-24 19:53:00 +00006164 // Iterate through all strict supersets of BaseCVR.
6165 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6166 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006167 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006168 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006169
6170 // Skip over restrict if no restrict found anywhere in the types, or if
6171 // the type cannot be restrict-qualified.
6172 if ((CVR & Qualifiers::Restrict) &&
6173 (!hasRestrict ||
6174 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6175 continue;
6176
6177 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006178 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006179
6180 // Build qualified pointer type.
6181 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006182 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006183 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006184 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006185 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6186
6187 // Insert qualified pointer type.
6188 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006189 }
6190
6191 return true;
6192}
6193
Sebastian Redl78eb8742009-04-19 21:53:20 +00006194/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6195/// to the set of pointer types along with any more-qualified variants of
6196/// that type. For example, if @p Ty is "int const *", this routine
6197/// will add "int const *", "int const volatile *", "int const
6198/// restrict *", and "int const volatile restrict *" to the set of
6199/// pointer types. Returns true if the add of @p Ty itself succeeded,
6200/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006201///
6202/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006203bool
6204BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6205 QualType Ty) {
6206 // Insert this type.
6207 if (!MemberPointerTypes.insert(Ty))
6208 return false;
6209
John McCall0953e762009-09-24 19:53:00 +00006210 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6211 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006212
John McCall0953e762009-09-24 19:53:00 +00006213 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006214 // Don't add qualified variants of arrays. For one, they're not allowed
6215 // (the qualifier would sink to the element type), and for another, the
6216 // only overload situation where it matters is subscript or pointer +- int,
6217 // and those shouldn't have qualifier variants anyway.
6218 if (PointeeTy->isArrayType())
6219 return true;
John McCall0953e762009-09-24 19:53:00 +00006220 const Type *ClassTy = PointerTy->getClass();
6221
6222 // Iterate through all strict supersets of the pointee type's CVR
6223 // qualifiers.
6224 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6225 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6226 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006227
John McCall0953e762009-09-24 19:53:00 +00006228 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006229 MemberPointerTypes.insert(
6230 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006231 }
6232
6233 return true;
6234}
6235
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006236/// AddTypesConvertedFrom - Add each of the types to which the type @p
6237/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006238/// primarily interested in pointer types and enumeration types. We also
6239/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006240/// AllowUserConversions is true if we should look at the conversion
6241/// functions of a class type, and AllowExplicitConversions if we
6242/// should also include the explicit conversion functions of a class
6243/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006244void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006245BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006246 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006247 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006248 bool AllowExplicitConversions,
6249 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006250 // Only deal with canonical types.
6251 Ty = Context.getCanonicalType(Ty);
6252
6253 // Look through reference types; they aren't part of the type of an
6254 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006255 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006256 Ty = RefTy->getPointeeType();
6257
John McCall3b657512011-01-19 10:06:00 +00006258 // If we're dealing with an array type, decay to the pointer.
6259 if (Ty->isArrayType())
6260 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6261
6262 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006263 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006264
Chandler Carruth6a577462010-12-13 01:44:01 +00006265 // Flag if we ever add a non-record type.
6266 const RecordType *TyRec = Ty->getAs<RecordType>();
6267 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6268
Chandler Carruth6a577462010-12-13 01:44:01 +00006269 // Flag if we encounter an arithmetic type.
6270 HasArithmeticOrEnumeralTypes =
6271 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6272
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006273 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6274 PointerTypes.insert(Ty);
6275 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006276 // Insert our type, and its more-qualified variants, into the set
6277 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006278 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006279 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006280 } else if (Ty->isMemberPointerType()) {
6281 // Member pointers are far easier, since the pointee can't be converted.
6282 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6283 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006284 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006285 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006286 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006287 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006288 // We treat vector types as arithmetic types in many contexts as an
6289 // extension.
6290 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006291 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006292 } else if (Ty->isNullPtrType()) {
6293 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006294 } else if (AllowUserConversions && TyRec) {
6295 // No conversion functions in incomplete types.
6296 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6297 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006298
Chandler Carruth6a577462010-12-13 01:44:01 +00006299 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006300 std::pair<CXXRecordDecl::conversion_iterator,
6301 CXXRecordDecl::conversion_iterator>
6302 Conversions = ClassDecl->getVisibleConversionFunctions();
6303 for (CXXRecordDecl::conversion_iterator
6304 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006305 NamedDecl *D = I.getDecl();
6306 if (isa<UsingShadowDecl>(D))
6307 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006308
Chandler Carruth6a577462010-12-13 01:44:01 +00006309 // Skip conversion function templates; they don't tell us anything
6310 // about which builtin types we can convert to.
6311 if (isa<FunctionTemplateDecl>(D))
6312 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006313
Chandler Carruth6a577462010-12-13 01:44:01 +00006314 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6315 if (AllowExplicitConversions || !Conv->isExplicit()) {
6316 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6317 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006318 }
6319 }
6320 }
6321}
6322
Douglas Gregor19b7b152009-08-24 13:43:27 +00006323/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6324/// the volatile- and non-volatile-qualified assignment operators for the
6325/// given type to the candidate set.
6326static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6327 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006328 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006329 unsigned NumArgs,
6330 OverloadCandidateSet &CandidateSet) {
6331 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006332
Douglas Gregor19b7b152009-08-24 13:43:27 +00006333 // T& operator=(T&, T)
6334 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6335 ParamTypes[1] = T;
6336 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6337 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006338
Douglas Gregor19b7b152009-08-24 13:43:27 +00006339 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6340 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006341 ParamTypes[0]
6342 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006343 ParamTypes[1] = T;
6344 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006345 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006346 }
6347}
Mike Stump1eb44332009-09-09 15:08:12 +00006348
Sebastian Redl9994a342009-10-25 17:03:50 +00006349/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6350/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006351static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6352 Qualifiers VRQuals;
6353 const RecordType *TyRec;
6354 if (const MemberPointerType *RHSMPType =
6355 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006356 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006357 else
6358 TyRec = ArgExpr->getType()->getAs<RecordType>();
6359 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006360 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006361 VRQuals.addVolatile();
6362 VRQuals.addRestrict();
6363 return VRQuals;
6364 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006365
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006366 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006367 if (!ClassDecl->hasDefinition())
6368 return VRQuals;
6369
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006370 std::pair<CXXRecordDecl::conversion_iterator,
6371 CXXRecordDecl::conversion_iterator>
6372 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006373
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006374 for (CXXRecordDecl::conversion_iterator
6375 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006376 NamedDecl *D = I.getDecl();
6377 if (isa<UsingShadowDecl>(D))
6378 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6379 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006380 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6381 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6382 CanTy = ResTypeRef->getPointeeType();
6383 // Need to go down the pointer/mempointer chain and add qualifiers
6384 // as see them.
6385 bool done = false;
6386 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006387 if (CanTy.isRestrictQualified())
6388 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006389 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6390 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006391 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006392 CanTy->getAs<MemberPointerType>())
6393 CanTy = ResTypeMPtr->getPointeeType();
6394 else
6395 done = true;
6396 if (CanTy.isVolatileQualified())
6397 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006398 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6399 return VRQuals;
6400 }
6401 }
6402 }
6403 return VRQuals;
6404}
John McCall00071ec2010-11-13 05:51:15 +00006405
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006406namespace {
John McCall00071ec2010-11-13 05:51:15 +00006407
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006408/// \brief Helper class to manage the addition of builtin operator overload
6409/// candidates. It provides shared state and utility methods used throughout
6410/// the process, as well as a helper method to add each group of builtin
6411/// operator overloads from the standard to a candidate set.
6412class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006413 // Common instance state available to all overload candidate addition methods.
6414 Sema &S;
6415 Expr **Args;
6416 unsigned NumArgs;
6417 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006418 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006419 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006420 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006421
Chandler Carruth6d695582010-12-12 10:35:00 +00006422 // Define some constants used to index and iterate over the arithemetic types
6423 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006424 // The "promoted arithmetic types" are the arithmetic
6425 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006426 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006427 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006428 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006429 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006430 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006431 LastPromotedArithmeticType = 11;
6432 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006433
Chandler Carruth6d695582010-12-12 10:35:00 +00006434 /// \brief Get the canonical type for a given arithmetic type index.
6435 CanQualType getArithmeticType(unsigned index) {
6436 assert(index < NumArithmeticTypes);
6437 static CanQualType ASTContext::* const
6438 ArithmeticTypes[NumArithmeticTypes] = {
6439 // Start of promoted types.
6440 &ASTContext::FloatTy,
6441 &ASTContext::DoubleTy,
6442 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006443
Chandler Carruth6d695582010-12-12 10:35:00 +00006444 // Start of integral types.
6445 &ASTContext::IntTy,
6446 &ASTContext::LongTy,
6447 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006448 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006449 &ASTContext::UnsignedIntTy,
6450 &ASTContext::UnsignedLongTy,
6451 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006452 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006453 // End of promoted types.
6454
6455 &ASTContext::BoolTy,
6456 &ASTContext::CharTy,
6457 &ASTContext::WCharTy,
6458 &ASTContext::Char16Ty,
6459 &ASTContext::Char32Ty,
6460 &ASTContext::SignedCharTy,
6461 &ASTContext::ShortTy,
6462 &ASTContext::UnsignedCharTy,
6463 &ASTContext::UnsignedShortTy,
6464 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006465 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006466 };
6467 return S.Context.*ArithmeticTypes[index];
6468 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006469
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006470 /// \brief Gets the canonical type resulting from the usual arithemetic
6471 /// converions for the given arithmetic types.
6472 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6473 // Accelerator table for performing the usual arithmetic conversions.
6474 // The rules are basically:
6475 // - if either is floating-point, use the wider floating-point
6476 // - if same signedness, use the higher rank
6477 // - if same size, use unsigned of the higher rank
6478 // - use the larger type
6479 // These rules, together with the axiom that higher ranks are
6480 // never smaller, are sufficient to precompute all of these results
6481 // *except* when dealing with signed types of higher rank.
6482 // (we could precompute SLL x UI for all known platforms, but it's
6483 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006484 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006485 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006486 Dep=-1,
6487 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006488 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006489 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006490 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006491/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6492/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6493/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6494/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6495/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6496/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6497/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6498/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6499/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6500/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6501/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006502 };
6503
6504 assert(L < LastPromotedArithmeticType);
6505 assert(R < LastPromotedArithmeticType);
6506 int Idx = ConversionsTable[L][R];
6507
6508 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006509 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006510
6511 // Slow path: we need to compare widths.
6512 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006513 CanQualType LT = getArithmeticType(L),
6514 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006515 unsigned LW = S.Context.getIntWidth(LT),
6516 RW = S.Context.getIntWidth(RT);
6517
6518 // If they're different widths, use the signed type.
6519 if (LW > RW) return LT;
6520 else if (LW < RW) return RT;
6521
6522 // Otherwise, use the unsigned type of the signed type's rank.
6523 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6524 assert(L == SLL || R == SLL);
6525 return S.Context.UnsignedLongLongTy;
6526 }
6527
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006528 /// \brief Helper method to factor out the common pattern of adding overloads
6529 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006530 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006531 bool HasVolatile,
6532 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006533 QualType ParamTypes[2] = {
6534 S.Context.getLValueReferenceType(CandidateTy),
6535 S.Context.IntTy
6536 };
6537
6538 // Non-volatile version.
6539 if (NumArgs == 1)
6540 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6541 else
6542 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6543
6544 // Use a heuristic to reduce number of builtin candidates in the set:
6545 // add volatile version only if there are conversions to a volatile type.
6546 if (HasVolatile) {
6547 ParamTypes[0] =
6548 S.Context.getLValueReferenceType(
6549 S.Context.getVolatileType(CandidateTy));
6550 if (NumArgs == 1)
6551 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6552 else
6553 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6554 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006555
6556 // Add restrict version only if there are conversions to a restrict type
6557 // and our candidate type is a non-restrict-qualified pointer.
6558 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6559 !CandidateTy.isRestrictQualified()) {
6560 ParamTypes[0]
6561 = S.Context.getLValueReferenceType(
6562 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6563 if (NumArgs == 1)
6564 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6565 else
6566 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6567
6568 if (HasVolatile) {
6569 ParamTypes[0]
6570 = S.Context.getLValueReferenceType(
6571 S.Context.getCVRQualifiedType(CandidateTy,
6572 (Qualifiers::Volatile |
6573 Qualifiers::Restrict)));
6574 if (NumArgs == 1)
6575 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6576 CandidateSet);
6577 else
6578 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6579 }
6580 }
6581
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006582 }
6583
6584public:
6585 BuiltinOperatorOverloadBuilder(
6586 Sema &S, Expr **Args, unsigned NumArgs,
6587 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006588 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006589 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006590 OverloadCandidateSet &CandidateSet)
6591 : S(S), Args(Args), NumArgs(NumArgs),
6592 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006593 HasArithmeticOrEnumeralCandidateType(
6594 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006595 CandidateTypes(CandidateTypes),
6596 CandidateSet(CandidateSet) {
6597 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006598 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006599 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006600 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006601 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006602 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006603 assert(getArithmeticType(FirstPromotedArithmeticType)
6604 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006605 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006606 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006607 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006608 "Invalid last promoted arithmetic type");
6609 }
6610
6611 // C++ [over.built]p3:
6612 //
6613 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6614 // is either volatile or empty, there exist candidate operator
6615 // functions of the form
6616 //
6617 // VQ T& operator++(VQ T&);
6618 // T operator++(VQ T&, int);
6619 //
6620 // C++ [over.built]p4:
6621 //
6622 // For every pair (T, VQ), where T is an arithmetic type other
6623 // than bool, and VQ is either volatile or empty, there exist
6624 // candidate operator functions of the form
6625 //
6626 // VQ T& operator--(VQ T&);
6627 // T operator--(VQ T&, int);
6628 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006629 if (!HasArithmeticOrEnumeralCandidateType)
6630 return;
6631
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006632 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6633 Arith < NumArithmeticTypes; ++Arith) {
6634 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006635 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006636 VisibleTypeConversionsQuals.hasVolatile(),
6637 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006638 }
6639 }
6640
6641 // C++ [over.built]p5:
6642 //
6643 // For every pair (T, VQ), where T is a cv-qualified or
6644 // cv-unqualified object type, and VQ is either volatile or
6645 // empty, there exist candidate operator functions of the form
6646 //
6647 // T*VQ& operator++(T*VQ&);
6648 // T*VQ& operator--(T*VQ&);
6649 // T* operator++(T*VQ&, int);
6650 // T* operator--(T*VQ&, int);
6651 void addPlusPlusMinusMinusPointerOverloads() {
6652 for (BuiltinCandidateTypeSet::iterator
6653 Ptr = CandidateTypes[0].pointer_begin(),
6654 PtrEnd = CandidateTypes[0].pointer_end();
6655 Ptr != PtrEnd; ++Ptr) {
6656 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006657 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006658 continue;
6659
6660 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006661 (!(*Ptr).isVolatileQualified() &&
6662 VisibleTypeConversionsQuals.hasVolatile()),
6663 (!(*Ptr).isRestrictQualified() &&
6664 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006665 }
6666 }
6667
6668 // C++ [over.built]p6:
6669 // For every cv-qualified or cv-unqualified object type T, there
6670 // exist candidate operator functions of the form
6671 //
6672 // T& operator*(T*);
6673 //
6674 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006675 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006676 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006677 // T& operator*(T*);
6678 void addUnaryStarPointerOverloads() {
6679 for (BuiltinCandidateTypeSet::iterator
6680 Ptr = CandidateTypes[0].pointer_begin(),
6681 PtrEnd = CandidateTypes[0].pointer_end();
6682 Ptr != PtrEnd; ++Ptr) {
6683 QualType ParamTy = *Ptr;
6684 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006685 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6686 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006687
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006688 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6689 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6690 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006691
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006692 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6693 &ParamTy, Args, 1, CandidateSet);
6694 }
6695 }
6696
6697 // C++ [over.built]p9:
6698 // For every promoted arithmetic type T, there exist candidate
6699 // operator functions of the form
6700 //
6701 // T operator+(T);
6702 // T operator-(T);
6703 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006704 if (!HasArithmeticOrEnumeralCandidateType)
6705 return;
6706
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006707 for (unsigned Arith = FirstPromotedArithmeticType;
6708 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006709 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006710 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6711 }
6712
6713 // Extension: We also add these operators for vector types.
6714 for (BuiltinCandidateTypeSet::iterator
6715 Vec = CandidateTypes[0].vector_begin(),
6716 VecEnd = CandidateTypes[0].vector_end();
6717 Vec != VecEnd; ++Vec) {
6718 QualType VecTy = *Vec;
6719 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6720 }
6721 }
6722
6723 // C++ [over.built]p8:
6724 // For every type T, there exist candidate operator functions of
6725 // the form
6726 //
6727 // T* operator+(T*);
6728 void addUnaryPlusPointerOverloads() {
6729 for (BuiltinCandidateTypeSet::iterator
6730 Ptr = CandidateTypes[0].pointer_begin(),
6731 PtrEnd = CandidateTypes[0].pointer_end();
6732 Ptr != PtrEnd; ++Ptr) {
6733 QualType ParamTy = *Ptr;
6734 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6735 }
6736 }
6737
6738 // C++ [over.built]p10:
6739 // For every promoted integral type T, there exist candidate
6740 // operator functions of the form
6741 //
6742 // T operator~(T);
6743 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006744 if (!HasArithmeticOrEnumeralCandidateType)
6745 return;
6746
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006747 for (unsigned Int = FirstPromotedIntegralType;
6748 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006749 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006750 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6751 }
6752
6753 // Extension: We also add this operator for vector types.
6754 for (BuiltinCandidateTypeSet::iterator
6755 Vec = CandidateTypes[0].vector_begin(),
6756 VecEnd = CandidateTypes[0].vector_end();
6757 Vec != VecEnd; ++Vec) {
6758 QualType VecTy = *Vec;
6759 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6760 }
6761 }
6762
6763 // C++ [over.match.oper]p16:
6764 // For every pointer to member type T, there exist candidate operator
6765 // functions of the form
6766 //
6767 // bool operator==(T,T);
6768 // bool operator!=(T,T);
6769 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6770 /// Set of (canonical) types that we've already handled.
6771 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6772
6773 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6774 for (BuiltinCandidateTypeSet::iterator
6775 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6776 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6777 MemPtr != MemPtrEnd;
6778 ++MemPtr) {
6779 // Don't add the same builtin candidate twice.
6780 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6781 continue;
6782
6783 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6784 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6785 CandidateSet);
6786 }
6787 }
6788 }
6789
6790 // C++ [over.built]p15:
6791 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006792 // For every T, where T is an enumeration type, a pointer type, or
6793 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006794 //
6795 // bool operator<(T, T);
6796 // bool operator>(T, T);
6797 // bool operator<=(T, T);
6798 // bool operator>=(T, T);
6799 // bool operator==(T, T);
6800 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006801 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006802 // C++ [over.match.oper]p3:
6803 // [...]the built-in candidates include all of the candidate operator
6804 // functions defined in 13.6 that, compared to the given operator, [...]
6805 // do not have the same parameter-type-list as any non-template non-member
6806 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006807 //
Eli Friedman97c67392012-09-18 21:52:24 +00006808 // Note that in practice, this only affects enumeration types because there
6809 // aren't any built-in candidates of record type, and a user-defined operator
6810 // must have an operand of record or enumeration type. Also, the only other
6811 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006812 // cannot be overloaded for enumeration types, so this is the only place
6813 // where we must suppress candidates like this.
6814 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6815 UserDefinedBinaryOperators;
6816
6817 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6818 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6819 CandidateTypes[ArgIdx].enumeration_end()) {
6820 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6821 CEnd = CandidateSet.end();
6822 C != CEnd; ++C) {
6823 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6824 continue;
6825
Eli Friedman97c67392012-09-18 21:52:24 +00006826 if (C->Function->isFunctionTemplateSpecialization())
6827 continue;
6828
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006829 QualType FirstParamType =
6830 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6831 QualType SecondParamType =
6832 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6833
6834 // Skip if either parameter isn't of enumeral type.
6835 if (!FirstParamType->isEnumeralType() ||
6836 !SecondParamType->isEnumeralType())
6837 continue;
6838
6839 // Add this operator to the set of known user-defined operators.
6840 UserDefinedBinaryOperators.insert(
6841 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6842 S.Context.getCanonicalType(SecondParamType)));
6843 }
6844 }
6845 }
6846
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006847 /// Set of (canonical) types that we've already handled.
6848 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6849
6850 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6851 for (BuiltinCandidateTypeSet::iterator
6852 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6853 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6854 Ptr != PtrEnd; ++Ptr) {
6855 // Don't add the same builtin candidate twice.
6856 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6857 continue;
6858
6859 QualType ParamTypes[2] = { *Ptr, *Ptr };
6860 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6861 CandidateSet);
6862 }
6863 for (BuiltinCandidateTypeSet::iterator
6864 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6865 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6866 Enum != EnumEnd; ++Enum) {
6867 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6868
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006869 // Don't add the same builtin candidate twice, or if a user defined
6870 // candidate exists.
6871 if (!AddedTypes.insert(CanonType) ||
6872 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6873 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006874 continue;
6875
6876 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006877 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6878 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006879 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006880
6881 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6882 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6883 if (AddedTypes.insert(NullPtrTy) &&
6884 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6885 NullPtrTy))) {
6886 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6887 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6888 CandidateSet);
6889 }
6890 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006891 }
6892 }
6893
6894 // C++ [over.built]p13:
6895 //
6896 // For every cv-qualified or cv-unqualified object type T
6897 // there exist candidate operator functions of the form
6898 //
6899 // T* operator+(T*, ptrdiff_t);
6900 // T& operator[](T*, ptrdiff_t); [BELOW]
6901 // T* operator-(T*, ptrdiff_t);
6902 // T* operator+(ptrdiff_t, T*);
6903 // T& operator[](ptrdiff_t, T*); [BELOW]
6904 //
6905 // C++ [over.built]p14:
6906 //
6907 // For every T, where T is a pointer to object type, there
6908 // exist candidate operator functions of the form
6909 //
6910 // ptrdiff_t operator-(T, T);
6911 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6912 /// Set of (canonical) types that we've already handled.
6913 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6914
6915 for (int Arg = 0; Arg < 2; ++Arg) {
6916 QualType AsymetricParamTypes[2] = {
6917 S.Context.getPointerDiffType(),
6918 S.Context.getPointerDiffType(),
6919 };
6920 for (BuiltinCandidateTypeSet::iterator
6921 Ptr = CandidateTypes[Arg].pointer_begin(),
6922 PtrEnd = CandidateTypes[Arg].pointer_end();
6923 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006924 QualType PointeeTy = (*Ptr)->getPointeeType();
6925 if (!PointeeTy->isObjectType())
6926 continue;
6927
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006928 AsymetricParamTypes[Arg] = *Ptr;
6929 if (Arg == 0 || Op == OO_Plus) {
6930 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6931 // T* operator+(ptrdiff_t, T*);
6932 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6933 CandidateSet);
6934 }
6935 if (Op == OO_Minus) {
6936 // ptrdiff_t operator-(T, T);
6937 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6938 continue;
6939
6940 QualType ParamTypes[2] = { *Ptr, *Ptr };
6941 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6942 Args, 2, CandidateSet);
6943 }
6944 }
6945 }
6946 }
6947
6948 // C++ [over.built]p12:
6949 //
6950 // For every pair of promoted arithmetic types L and R, there
6951 // exist candidate operator functions of the form
6952 //
6953 // LR operator*(L, R);
6954 // LR operator/(L, R);
6955 // LR operator+(L, R);
6956 // LR operator-(L, R);
6957 // bool operator<(L, R);
6958 // bool operator>(L, R);
6959 // bool operator<=(L, R);
6960 // bool operator>=(L, R);
6961 // bool operator==(L, R);
6962 // bool operator!=(L, R);
6963 //
6964 // where LR is the result of the usual arithmetic conversions
6965 // between types L and R.
6966 //
6967 // C++ [over.built]p24:
6968 //
6969 // For every pair of promoted arithmetic types L and R, there exist
6970 // candidate operator functions of the form
6971 //
6972 // LR operator?(bool, L, R);
6973 //
6974 // where LR is the result of the usual arithmetic conversions
6975 // between types L and R.
6976 // Our candidates ignore the first parameter.
6977 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006978 if (!HasArithmeticOrEnumeralCandidateType)
6979 return;
6980
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006981 for (unsigned Left = FirstPromotedArithmeticType;
6982 Left < LastPromotedArithmeticType; ++Left) {
6983 for (unsigned Right = FirstPromotedArithmeticType;
6984 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006985 QualType LandR[2] = { getArithmeticType(Left),
6986 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006987 QualType Result =
6988 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006989 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006990 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6991 }
6992 }
6993
6994 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6995 // conditional operator for vector types.
6996 for (BuiltinCandidateTypeSet::iterator
6997 Vec1 = CandidateTypes[0].vector_begin(),
6998 Vec1End = CandidateTypes[0].vector_end();
6999 Vec1 != Vec1End; ++Vec1) {
7000 for (BuiltinCandidateTypeSet::iterator
7001 Vec2 = CandidateTypes[1].vector_begin(),
7002 Vec2End = CandidateTypes[1].vector_end();
7003 Vec2 != Vec2End; ++Vec2) {
7004 QualType LandR[2] = { *Vec1, *Vec2 };
7005 QualType Result = S.Context.BoolTy;
7006 if (!isComparison) {
7007 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7008 Result = *Vec1;
7009 else
7010 Result = *Vec2;
7011 }
7012
7013 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7014 }
7015 }
7016 }
7017
7018 // C++ [over.built]p17:
7019 //
7020 // For every pair of promoted integral types L and R, there
7021 // exist candidate operator functions of the form
7022 //
7023 // LR operator%(L, R);
7024 // LR operator&(L, R);
7025 // LR operator^(L, R);
7026 // LR operator|(L, R);
7027 // L operator<<(L, R);
7028 // L operator>>(L, R);
7029 //
7030 // where LR is the result of the usual arithmetic conversions
7031 // between types L and R.
7032 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007033 if (!HasArithmeticOrEnumeralCandidateType)
7034 return;
7035
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007036 for (unsigned Left = FirstPromotedIntegralType;
7037 Left < LastPromotedIntegralType; ++Left) {
7038 for (unsigned Right = FirstPromotedIntegralType;
7039 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007040 QualType LandR[2] = { getArithmeticType(Left),
7041 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007042 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7043 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007044 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007045 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7046 }
7047 }
7048 }
7049
7050 // C++ [over.built]p20:
7051 //
7052 // For every pair (T, VQ), where T is an enumeration or
7053 // pointer to member type and VQ is either volatile or
7054 // empty, there exist candidate operator functions of the form
7055 //
7056 // VQ T& operator=(VQ T&, T);
7057 void addAssignmentMemberPointerOrEnumeralOverloads() {
7058 /// Set of (canonical) types that we've already handled.
7059 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7060
7061 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7062 for (BuiltinCandidateTypeSet::iterator
7063 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7064 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7065 Enum != EnumEnd; ++Enum) {
7066 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7067 continue;
7068
7069 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7070 CandidateSet);
7071 }
7072
7073 for (BuiltinCandidateTypeSet::iterator
7074 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7075 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7076 MemPtr != MemPtrEnd; ++MemPtr) {
7077 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7078 continue;
7079
7080 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7081 CandidateSet);
7082 }
7083 }
7084 }
7085
7086 // C++ [over.built]p19:
7087 //
7088 // For every pair (T, VQ), where T is any type and VQ is either
7089 // volatile or empty, there exist candidate operator functions
7090 // of the form
7091 //
7092 // T*VQ& operator=(T*VQ&, T*);
7093 //
7094 // C++ [over.built]p21:
7095 //
7096 // For every pair (T, VQ), where T is a cv-qualified or
7097 // cv-unqualified object type and VQ is either volatile or
7098 // empty, there exist candidate operator functions of the form
7099 //
7100 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7101 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7102 void addAssignmentPointerOverloads(bool isEqualOp) {
7103 /// Set of (canonical) types that we've already handled.
7104 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7105
7106 for (BuiltinCandidateTypeSet::iterator
7107 Ptr = CandidateTypes[0].pointer_begin(),
7108 PtrEnd = CandidateTypes[0].pointer_end();
7109 Ptr != PtrEnd; ++Ptr) {
7110 // If this is operator=, keep track of the builtin candidates we added.
7111 if (isEqualOp)
7112 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007113 else if (!(*Ptr)->getPointeeType()->isObjectType())
7114 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007115
7116 // non-volatile version
7117 QualType ParamTypes[2] = {
7118 S.Context.getLValueReferenceType(*Ptr),
7119 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7120 };
7121 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7122 /*IsAssigmentOperator=*/ isEqualOp);
7123
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007124 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7125 VisibleTypeConversionsQuals.hasVolatile();
7126 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007127 // volatile version
7128 ParamTypes[0] =
7129 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7130 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7131 /*IsAssigmentOperator=*/isEqualOp);
7132 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007133
7134 if (!(*Ptr).isRestrictQualified() &&
7135 VisibleTypeConversionsQuals.hasRestrict()) {
7136 // restrict version
7137 ParamTypes[0]
7138 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7139 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7140 /*IsAssigmentOperator=*/isEqualOp);
7141
7142 if (NeedVolatile) {
7143 // volatile restrict version
7144 ParamTypes[0]
7145 = S.Context.getLValueReferenceType(
7146 S.Context.getCVRQualifiedType(*Ptr,
7147 (Qualifiers::Volatile |
7148 Qualifiers::Restrict)));
7149 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7150 CandidateSet,
7151 /*IsAssigmentOperator=*/isEqualOp);
7152 }
7153 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007154 }
7155
7156 if (isEqualOp) {
7157 for (BuiltinCandidateTypeSet::iterator
7158 Ptr = CandidateTypes[1].pointer_begin(),
7159 PtrEnd = CandidateTypes[1].pointer_end();
7160 Ptr != PtrEnd; ++Ptr) {
7161 // Make sure we don't add the same candidate twice.
7162 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7163 continue;
7164
Chandler Carruth6df868e2010-12-12 08:17:55 +00007165 QualType ParamTypes[2] = {
7166 S.Context.getLValueReferenceType(*Ptr),
7167 *Ptr,
7168 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007169
7170 // non-volatile version
7171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7172 /*IsAssigmentOperator=*/true);
7173
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007174 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7175 VisibleTypeConversionsQuals.hasVolatile();
7176 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007177 // volatile version
7178 ParamTypes[0] =
7179 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007180 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7181 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007182 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007183
7184 if (!(*Ptr).isRestrictQualified() &&
7185 VisibleTypeConversionsQuals.hasRestrict()) {
7186 // restrict version
7187 ParamTypes[0]
7188 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7189 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7190 CandidateSet, /*IsAssigmentOperator=*/true);
7191
7192 if (NeedVolatile) {
7193 // volatile restrict version
7194 ParamTypes[0]
7195 = S.Context.getLValueReferenceType(
7196 S.Context.getCVRQualifiedType(*Ptr,
7197 (Qualifiers::Volatile |
7198 Qualifiers::Restrict)));
7199 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7200 CandidateSet, /*IsAssigmentOperator=*/true);
7201
7202 }
7203 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007204 }
7205 }
7206 }
7207
7208 // C++ [over.built]p18:
7209 //
7210 // For every triple (L, VQ, R), where L is an arithmetic type,
7211 // VQ is either volatile or empty, and R is a promoted
7212 // arithmetic type, there exist candidate operator functions of
7213 // the form
7214 //
7215 // VQ L& operator=(VQ L&, R);
7216 // VQ L& operator*=(VQ L&, R);
7217 // VQ L& operator/=(VQ L&, R);
7218 // VQ L& operator+=(VQ L&, R);
7219 // VQ L& operator-=(VQ L&, R);
7220 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007221 if (!HasArithmeticOrEnumeralCandidateType)
7222 return;
7223
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007224 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7225 for (unsigned Right = FirstPromotedArithmeticType;
7226 Right < LastPromotedArithmeticType; ++Right) {
7227 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007228 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007229
7230 // Add this built-in operator as a candidate (VQ is empty).
7231 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007232 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007233 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7234 /*IsAssigmentOperator=*/isEqualOp);
7235
7236 // Add this built-in operator as a candidate (VQ is 'volatile').
7237 if (VisibleTypeConversionsQuals.hasVolatile()) {
7238 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007239 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007240 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007241 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7242 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007243 /*IsAssigmentOperator=*/isEqualOp);
7244 }
7245 }
7246 }
7247
7248 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7249 for (BuiltinCandidateTypeSet::iterator
7250 Vec1 = CandidateTypes[0].vector_begin(),
7251 Vec1End = CandidateTypes[0].vector_end();
7252 Vec1 != Vec1End; ++Vec1) {
7253 for (BuiltinCandidateTypeSet::iterator
7254 Vec2 = CandidateTypes[1].vector_begin(),
7255 Vec2End = CandidateTypes[1].vector_end();
7256 Vec2 != Vec2End; ++Vec2) {
7257 QualType ParamTypes[2];
7258 ParamTypes[1] = *Vec2;
7259 // Add this built-in operator as a candidate (VQ is empty).
7260 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7261 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7262 /*IsAssigmentOperator=*/isEqualOp);
7263
7264 // Add this built-in operator as a candidate (VQ is 'volatile').
7265 if (VisibleTypeConversionsQuals.hasVolatile()) {
7266 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7267 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007268 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7269 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007270 /*IsAssigmentOperator=*/isEqualOp);
7271 }
7272 }
7273 }
7274 }
7275
7276 // C++ [over.built]p22:
7277 //
7278 // For every triple (L, VQ, R), where L is an integral type, VQ
7279 // is either volatile or empty, and R is a promoted integral
7280 // type, there exist candidate operator functions of the form
7281 //
7282 // VQ L& operator%=(VQ L&, R);
7283 // VQ L& operator<<=(VQ L&, R);
7284 // VQ L& operator>>=(VQ L&, R);
7285 // VQ L& operator&=(VQ L&, R);
7286 // VQ L& operator^=(VQ L&, R);
7287 // VQ L& operator|=(VQ L&, R);
7288 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007289 if (!HasArithmeticOrEnumeralCandidateType)
7290 return;
7291
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007292 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7293 for (unsigned Right = FirstPromotedIntegralType;
7294 Right < LastPromotedIntegralType; ++Right) {
7295 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007296 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007297
7298 // Add this built-in operator as a candidate (VQ is empty).
7299 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007300 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007301 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7302 if (VisibleTypeConversionsQuals.hasVolatile()) {
7303 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007304 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007305 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7306 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7307 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7308 CandidateSet);
7309 }
7310 }
7311 }
7312 }
7313
7314 // C++ [over.operator]p23:
7315 //
7316 // There also exist candidate operator functions of the form
7317 //
7318 // bool operator!(bool);
7319 // bool operator&&(bool, bool);
7320 // bool operator||(bool, bool);
7321 void addExclaimOverload() {
7322 QualType ParamTy = S.Context.BoolTy;
7323 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7324 /*IsAssignmentOperator=*/false,
7325 /*NumContextualBoolArguments=*/1);
7326 }
7327 void addAmpAmpOrPipePipeOverload() {
7328 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7329 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7330 /*IsAssignmentOperator=*/false,
7331 /*NumContextualBoolArguments=*/2);
7332 }
7333
7334 // C++ [over.built]p13:
7335 //
7336 // For every cv-qualified or cv-unqualified object type T there
7337 // exist candidate operator functions of the form
7338 //
7339 // T* operator+(T*, ptrdiff_t); [ABOVE]
7340 // T& operator[](T*, ptrdiff_t);
7341 // T* operator-(T*, ptrdiff_t); [ABOVE]
7342 // T* operator+(ptrdiff_t, T*); [ABOVE]
7343 // T& operator[](ptrdiff_t, T*);
7344 void addSubscriptOverloads() {
7345 for (BuiltinCandidateTypeSet::iterator
7346 Ptr = CandidateTypes[0].pointer_begin(),
7347 PtrEnd = CandidateTypes[0].pointer_end();
7348 Ptr != PtrEnd; ++Ptr) {
7349 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7350 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007351 if (!PointeeType->isObjectType())
7352 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007353
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007354 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7355
7356 // T& operator[](T*, ptrdiff_t)
7357 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7358 }
7359
7360 for (BuiltinCandidateTypeSet::iterator
7361 Ptr = CandidateTypes[1].pointer_begin(),
7362 PtrEnd = CandidateTypes[1].pointer_end();
7363 Ptr != PtrEnd; ++Ptr) {
7364 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7365 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007366 if (!PointeeType->isObjectType())
7367 continue;
7368
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007369 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7370
7371 // T& operator[](ptrdiff_t, T*)
7372 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7373 }
7374 }
7375
7376 // C++ [over.built]p11:
7377 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7378 // C1 is the same type as C2 or is a derived class of C2, T is an object
7379 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7380 // there exist candidate operator functions of the form
7381 //
7382 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7383 //
7384 // where CV12 is the union of CV1 and CV2.
7385 void addArrowStarOverloads() {
7386 for (BuiltinCandidateTypeSet::iterator
7387 Ptr = CandidateTypes[0].pointer_begin(),
7388 PtrEnd = CandidateTypes[0].pointer_end();
7389 Ptr != PtrEnd; ++Ptr) {
7390 QualType C1Ty = (*Ptr);
7391 QualType C1;
7392 QualifierCollector Q1;
7393 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7394 if (!isa<RecordType>(C1))
7395 continue;
7396 // heuristic to reduce number of builtin candidates in the set.
7397 // Add volatile/restrict version only if there are conversions to a
7398 // volatile/restrict type.
7399 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7400 continue;
7401 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7402 continue;
7403 for (BuiltinCandidateTypeSet::iterator
7404 MemPtr = CandidateTypes[1].member_pointer_begin(),
7405 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7406 MemPtr != MemPtrEnd; ++MemPtr) {
7407 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7408 QualType C2 = QualType(mptr->getClass(), 0);
7409 C2 = C2.getUnqualifiedType();
7410 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7411 break;
7412 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7413 // build CV12 T&
7414 QualType T = mptr->getPointeeType();
7415 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7416 T.isVolatileQualified())
7417 continue;
7418 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7419 T.isRestrictQualified())
7420 continue;
7421 T = Q1.apply(S.Context, T);
7422 QualType ResultTy = S.Context.getLValueReferenceType(T);
7423 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7424 }
7425 }
7426 }
7427
7428 // Note that we don't consider the first argument, since it has been
7429 // contextually converted to bool long ago. The candidates below are
7430 // therefore added as binary.
7431 //
7432 // C++ [over.built]p25:
7433 // For every type T, where T is a pointer, pointer-to-member, or scoped
7434 // enumeration type, there exist candidate operator functions of the form
7435 //
7436 // T operator?(bool, T, T);
7437 //
7438 void addConditionalOperatorOverloads() {
7439 /// Set of (canonical) types that we've already handled.
7440 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7441
7442 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7443 for (BuiltinCandidateTypeSet::iterator
7444 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7445 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7446 Ptr != PtrEnd; ++Ptr) {
7447 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7448 continue;
7449
7450 QualType ParamTypes[2] = { *Ptr, *Ptr };
7451 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7452 }
7453
7454 for (BuiltinCandidateTypeSet::iterator
7455 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7456 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7457 MemPtr != MemPtrEnd; ++MemPtr) {
7458 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7459 continue;
7460
7461 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7462 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7463 }
7464
David Blaikie4e4d0842012-03-11 07:00:24 +00007465 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007466 for (BuiltinCandidateTypeSet::iterator
7467 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7468 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7469 Enum != EnumEnd; ++Enum) {
7470 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7471 continue;
7472
7473 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7474 continue;
7475
7476 QualType ParamTypes[2] = { *Enum, *Enum };
7477 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7478 }
7479 }
7480 }
7481 }
7482};
7483
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007484} // end anonymous namespace
7485
7486/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7487/// operator overloads to the candidate set (C++ [over.built]), based
7488/// on the operator @p Op and the arguments given. For example, if the
7489/// operator is a binary '+', this routine might add "int
7490/// operator+(int, int)" to cover integer addition.
7491void
7492Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7493 SourceLocation OpLoc,
7494 Expr **Args, unsigned NumArgs,
7495 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007496 // Find all of the types that the arguments can convert to, but only
7497 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007498 // that make use of these types. Also record whether we encounter non-record
7499 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007500 Qualifiers VisibleTypeConversionsQuals;
7501 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007502 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7503 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007504
7505 bool HasNonRecordCandidateType = false;
7506 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007507 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007508 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7509 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7510 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7511 OpLoc,
7512 true,
7513 (Op == OO_Exclaim ||
7514 Op == OO_AmpAmp ||
7515 Op == OO_PipePipe),
7516 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007517 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7518 CandidateTypes[ArgIdx].hasNonRecordTypes();
7519 HasArithmeticOrEnumeralCandidateType =
7520 HasArithmeticOrEnumeralCandidateType ||
7521 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007522 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007523
Chandler Carruth6a577462010-12-13 01:44:01 +00007524 // Exit early when no non-record types have been added to the candidate set
7525 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007526 //
7527 // We can't exit early for !, ||, or &&, since there we have always have
7528 // 'bool' overloads.
7529 if (!HasNonRecordCandidateType &&
7530 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007531 return;
7532
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007533 // Setup an object to manage the common state for building overloads.
7534 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7535 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007536 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007537 CandidateTypes, CandidateSet);
7538
7539 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007540 switch (Op) {
7541 case OO_None:
7542 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007543 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007544
Chandler Carruthabb71842010-12-12 08:51:33 +00007545 case OO_New:
7546 case OO_Delete:
7547 case OO_Array_New:
7548 case OO_Array_Delete:
7549 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007550 llvm_unreachable(
7551 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007552
7553 case OO_Comma:
7554 case OO_Arrow:
7555 // C++ [over.match.oper]p3:
7556 // -- For the operator ',', the unary operator '&', or the
7557 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007558 break;
7559
7560 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007561 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007562 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007563 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007564
7565 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007566 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007567 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007568 } else {
7569 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7570 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7571 }
Douglas Gregor74253732008-11-19 15:42:04 +00007572 break;
7573
Chandler Carruthabb71842010-12-12 08:51:33 +00007574 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007575 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007576 OpBuilder.addUnaryStarPointerOverloads();
7577 else
7578 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7579 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007580
Chandler Carruthabb71842010-12-12 08:51:33 +00007581 case OO_Slash:
7582 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007583 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007584
7585 case OO_PlusPlus:
7586 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007587 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7588 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007589 break;
7590
Douglas Gregor19b7b152009-08-24 13:43:27 +00007591 case OO_EqualEqual:
7592 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007593 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007594 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007595
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007596 case OO_Less:
7597 case OO_Greater:
7598 case OO_LessEqual:
7599 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007600 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007601 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7602 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007603
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007604 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007605 case OO_Caret:
7606 case OO_Pipe:
7607 case OO_LessLess:
7608 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007609 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007610 break;
7611
Chandler Carruthabb71842010-12-12 08:51:33 +00007612 case OO_Amp: // '&' is either unary or binary
7613 if (NumArgs == 1)
7614 // C++ [over.match.oper]p3:
7615 // -- For the operator ',', the unary operator '&', or the
7616 // operator '->', the built-in candidates set is empty.
7617 break;
7618
7619 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7620 break;
7621
7622 case OO_Tilde:
7623 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7624 break;
7625
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007626 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007627 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007628 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007629
7630 case OO_PlusEqual:
7631 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007632 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007633 // Fall through.
7634
7635 case OO_StarEqual:
7636 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007637 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007638 break;
7639
7640 case OO_PercentEqual:
7641 case OO_LessLessEqual:
7642 case OO_GreaterGreaterEqual:
7643 case OO_AmpEqual:
7644 case OO_CaretEqual:
7645 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007646 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007647 break;
7648
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007649 case OO_Exclaim:
7650 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007651 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007652
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007653 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007654 case OO_PipePipe:
7655 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007656 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007657
7658 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007659 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007660 break;
7661
7662 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007663 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007664 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007665
7666 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007667 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007668 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7669 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007670 }
7671}
7672
Douglas Gregorfa047642009-02-04 00:32:51 +00007673/// \brief Add function candidates found via argument-dependent lookup
7674/// to the set of overloading candidates.
7675///
7676/// This routine performs argument-dependent name lookup based on the
7677/// given function name (which may also be an operator name) and adds
7678/// all of the overload candidates found by ADL to the overload
7679/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007680void
Douglas Gregorfa047642009-02-04 00:32:51 +00007681Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007682 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007683 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007684 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007685 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007686 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007687 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007688
John McCalla113e722010-01-26 06:04:06 +00007689 // FIXME: This approach for uniquing ADL results (and removing
7690 // redundant candidates from the set) relies on pointer-equality,
7691 // which means we need to key off the canonical decl. However,
7692 // always going back to the canonical decl might not get us the
7693 // right set of default arguments. What default arguments are
7694 // we supposed to consider on ADL candidates, anyway?
7695
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007696 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007697 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007698
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007699 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007700 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7701 CandEnd = CandidateSet.end();
7702 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007703 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007704 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007705 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007706 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007707 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007708
7709 // For each of the ADL candidates we found, add it to the overload
7710 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007711 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007712 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007713 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007714 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007715 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007716
Ahmed Charles13a140c2012-02-25 11:00:22 +00007717 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7718 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007719 } else
John McCall6e266892010-01-26 03:27:55 +00007720 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007721 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007722 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007723 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007724}
7725
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007726/// isBetterOverloadCandidate - Determines whether the first overload
7727/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007728bool
John McCall120d63c2010-08-24 20:38:10 +00007729isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007730 const OverloadCandidate &Cand1,
7731 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007732 SourceLocation Loc,
7733 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007734 // Define viable functions to be better candidates than non-viable
7735 // functions.
7736 if (!Cand2.Viable)
7737 return Cand1.Viable;
7738 else if (!Cand1.Viable)
7739 return false;
7740
Douglas Gregor88a35142008-12-22 05:46:06 +00007741 // C++ [over.match.best]p1:
7742 //
7743 // -- if F is a static member function, ICS1(F) is defined such
7744 // that ICS1(F) is neither better nor worse than ICS1(G) for
7745 // any function G, and, symmetrically, ICS1(G) is neither
7746 // better nor worse than ICS1(F).
7747 unsigned StartArg = 0;
7748 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7749 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007750
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007751 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007752 // A viable function F1 is defined to be a better function than another
7753 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007754 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007755 unsigned NumArgs = Cand1.NumConversions;
7756 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007757 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007758 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007759 switch (CompareImplicitConversionSequences(S,
7760 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007761 Cand2.Conversions[ArgIdx])) {
7762 case ImplicitConversionSequence::Better:
7763 // Cand1 has a better conversion sequence.
7764 HasBetterConversion = true;
7765 break;
7766
7767 case ImplicitConversionSequence::Worse:
7768 // Cand1 can't be better than Cand2.
7769 return false;
7770
7771 case ImplicitConversionSequence::Indistinguishable:
7772 // Do nothing.
7773 break;
7774 }
7775 }
7776
Mike Stump1eb44332009-09-09 15:08:12 +00007777 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007778 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007779 if (HasBetterConversion)
7780 return true;
7781
Mike Stump1eb44332009-09-09 15:08:12 +00007782 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007783 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007784 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007785 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7786 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007787
7788 // -- F1 and F2 are function template specializations, and the function
7789 // template for F1 is more specialized than the template for F2
7790 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007791 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007792 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007793 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007794 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007795 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7796 Cand2.Function->getPrimaryTemplate(),
7797 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007798 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007799 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007800 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007801 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007802 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007803
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007804 // -- the context is an initialization by user-defined conversion
7805 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7806 // from the return type of F1 to the destination type (i.e.,
7807 // the type of the entity being initialized) is a better
7808 // conversion sequence than the standard conversion sequence
7809 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007810 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007811 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007812 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007813 // First check whether we prefer one of the conversion functions over the
7814 // other. This only distinguishes the results in non-standard, extension
7815 // cases such as the conversion from a lambda closure type to a function
7816 // pointer or block.
7817 ImplicitConversionSequence::CompareKind FuncResult
7818 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7819 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7820 return FuncResult;
7821
John McCall120d63c2010-08-24 20:38:10 +00007822 switch (CompareStandardConversionSequences(S,
7823 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007824 Cand2.FinalConversion)) {
7825 case ImplicitConversionSequence::Better:
7826 // Cand1 has a better conversion sequence.
7827 return true;
7828
7829 case ImplicitConversionSequence::Worse:
7830 // Cand1 can't be better than Cand2.
7831 return false;
7832
7833 case ImplicitConversionSequence::Indistinguishable:
7834 // Do nothing
7835 break;
7836 }
7837 }
7838
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007839 return false;
7840}
7841
Mike Stump1eb44332009-09-09 15:08:12 +00007842/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007843/// within an overload candidate set.
7844///
James Dennettefce31f2012-06-22 08:10:18 +00007845/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007846/// which overload resolution occurs.
7847///
James Dennettefce31f2012-06-22 08:10:18 +00007848/// \param Best If overload resolution was successful or found a deleted
7849/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007850///
7851/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007852OverloadingResult
7853OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007854 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007855 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007856 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007857 Best = end();
7858 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7859 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007860 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007861 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007862 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007863 }
7864
7865 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007866 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007867 return OR_No_Viable_Function;
7868
7869 // Make sure that this function is better than every other viable
7870 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007871 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007872 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007873 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007874 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007875 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007876 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007877 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007878 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007879 }
Mike Stump1eb44332009-09-09 15:08:12 +00007880
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007881 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007882 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007883 (Best->Function->isDeleted() ||
7884 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007885 return OR_Deleted;
7886
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007887 return OR_Success;
7888}
7889
John McCall3c80f572010-01-12 02:15:36 +00007890namespace {
7891
7892enum OverloadCandidateKind {
7893 oc_function,
7894 oc_method,
7895 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007896 oc_function_template,
7897 oc_method_template,
7898 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007899 oc_implicit_default_constructor,
7900 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007901 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007902 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007903 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007904 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007905};
7906
John McCall220ccbf2010-01-13 00:25:19 +00007907OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7908 FunctionDecl *Fn,
7909 std::string &Description) {
7910 bool isTemplate = false;
7911
7912 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7913 isTemplate = true;
7914 Description = S.getTemplateArgumentBindingsText(
7915 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7916 }
John McCallb1622a12010-01-06 09:43:14 +00007917
7918 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007919 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007920 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007921
Sebastian Redlf677ea32011-02-05 19:23:19 +00007922 if (Ctor->getInheritedConstructor())
7923 return oc_implicit_inherited_constructor;
7924
Sean Hunt82713172011-05-25 23:16:36 +00007925 if (Ctor->isDefaultConstructor())
7926 return oc_implicit_default_constructor;
7927
7928 if (Ctor->isMoveConstructor())
7929 return oc_implicit_move_constructor;
7930
7931 assert(Ctor->isCopyConstructor() &&
7932 "unexpected sort of implicit constructor");
7933 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007934 }
7935
7936 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7937 // This actually gets spelled 'candidate function' for now, but
7938 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007939 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007940 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007941
Sean Hunt82713172011-05-25 23:16:36 +00007942 if (Meth->isMoveAssignmentOperator())
7943 return oc_implicit_move_assignment;
7944
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007945 if (Meth->isCopyAssignmentOperator())
7946 return oc_implicit_copy_assignment;
7947
7948 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7949 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007950 }
7951
John McCall220ccbf2010-01-13 00:25:19 +00007952 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007953}
7954
Sebastian Redlf677ea32011-02-05 19:23:19 +00007955void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7956 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7957 if (!Ctor) return;
7958
7959 Ctor = Ctor->getInheritedConstructor();
7960 if (!Ctor) return;
7961
7962 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7963}
7964
John McCall3c80f572010-01-12 02:15:36 +00007965} // end anonymous namespace
7966
7967// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007968void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007969 std::string FnDesc;
7970 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007971 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7972 << (unsigned) K << FnDesc;
7973 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7974 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007975 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007976}
7977
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007978//Notes the location of all overload candidates designated through
7979// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007980void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007981 assert(OverloadedExpr->getType() == Context.OverloadTy);
7982
7983 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7984 OverloadExpr *OvlExpr = Ovl.Expression;
7985
7986 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7987 IEnd = OvlExpr->decls_end();
7988 I != IEnd; ++I) {
7989 if (FunctionTemplateDecl *FunTmpl =
7990 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007991 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007992 } else if (FunctionDecl *Fun
7993 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007994 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007995 }
7996 }
7997}
7998
John McCall1d318332010-01-12 00:44:57 +00007999/// Diagnoses an ambiguous conversion. The partial diagnostic is the
8000/// "lead" diagnostic; it will be given two arguments, the source and
8001/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00008002void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
8003 Sema &S,
8004 SourceLocation CaretLoc,
8005 const PartialDiagnostic &PDiag) const {
8006 S.Diag(CaretLoc, PDiag)
8007 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008008 // FIXME: The note limiting machinery is borrowed from
8009 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8010 // refactoring here.
8011 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8012 unsigned CandsShown = 0;
8013 AmbiguousConversionSequence::const_iterator I, E;
8014 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8015 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8016 break;
8017 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008018 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008019 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008020 if (I != E)
8021 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008022}
8023
John McCall1d318332010-01-12 00:44:57 +00008024namespace {
8025
John McCalladbb8f82010-01-13 09:16:55 +00008026void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8027 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8028 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008029 assert(Cand->Function && "for now, candidate must be a function");
8030 FunctionDecl *Fn = Cand->Function;
8031
8032 // There's a conversion slot for the object argument if this is a
8033 // non-constructor method. Note that 'I' corresponds the
8034 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008035 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008036 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008037 if (I == 0)
8038 isObjectArgument = true;
8039 else
8040 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008041 }
8042
John McCall220ccbf2010-01-13 00:25:19 +00008043 std::string FnDesc;
8044 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8045
John McCalladbb8f82010-01-13 09:16:55 +00008046 Expr *FromExpr = Conv.Bad.FromExpr;
8047 QualType FromTy = Conv.Bad.getFromType();
8048 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008049
John McCall5920dbb2010-02-02 02:42:52 +00008050 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008051 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008052 Expr *E = FromExpr->IgnoreParens();
8053 if (isa<UnaryOperator>(E))
8054 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008055 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008056
8057 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8058 << (unsigned) FnKind << FnDesc
8059 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8060 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008061 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008062 return;
8063 }
8064
John McCall258b2032010-01-23 08:10:49 +00008065 // Do some hand-waving analysis to see if the non-viability is due
8066 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008067 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8068 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8069 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8070 CToTy = RT->getPointeeType();
8071 else {
8072 // TODO: detect and diagnose the full richness of const mismatches.
8073 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8074 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8075 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8076 }
8077
8078 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8079 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008080 Qualifiers FromQs = CFromTy.getQualifiers();
8081 Qualifiers ToQs = CToTy.getQualifiers();
8082
8083 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8085 << (unsigned) FnKind << FnDesc
8086 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8087 << FromTy
8088 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8089 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008090 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008091 return;
8092 }
8093
John McCallf85e1932011-06-15 23:02:42 +00008094 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008095 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008096 << (unsigned) FnKind << FnDesc
8097 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8098 << FromTy
8099 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8100 << (unsigned) isObjectArgument << I+1;
8101 MaybeEmitInheritedConstructorNote(S, Fn);
8102 return;
8103 }
8104
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008105 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8106 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8107 << (unsigned) FnKind << FnDesc
8108 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8109 << FromTy
8110 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8111 << (unsigned) isObjectArgument << I+1;
8112 MaybeEmitInheritedConstructorNote(S, Fn);
8113 return;
8114 }
8115
John McCall651f3ee2010-01-14 03:28:57 +00008116 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8117 assert(CVR && "unexpected qualifiers mismatch");
8118
8119 if (isObjectArgument) {
8120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8121 << (unsigned) FnKind << FnDesc
8122 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8123 << FromTy << (CVR - 1);
8124 } else {
8125 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8126 << (unsigned) FnKind << FnDesc
8127 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8128 << FromTy << (CVR - 1) << I+1;
8129 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008130 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008131 return;
8132 }
8133
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008134 // Special diagnostic for failure to convert an initializer list, since
8135 // telling the user that it has type void is not useful.
8136 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8137 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8138 << (unsigned) FnKind << FnDesc
8139 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8140 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8141 MaybeEmitInheritedConstructorNote(S, Fn);
8142 return;
8143 }
8144
John McCall258b2032010-01-23 08:10:49 +00008145 // Diagnose references or pointers to incomplete types differently,
8146 // since it's far from impossible that the incompleteness triggered
8147 // the failure.
8148 QualType TempFromTy = FromTy.getNonReferenceType();
8149 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8150 TempFromTy = PTy->getPointeeType();
8151 if (TempFromTy->isIncompleteType()) {
8152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8153 << (unsigned) FnKind << FnDesc
8154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8155 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008156 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008157 return;
8158 }
8159
Douglas Gregor85789812010-06-30 23:01:39 +00008160 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008161 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008162 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8163 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8164 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8165 FromPtrTy->getPointeeType()) &&
8166 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8167 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008168 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008169 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008170 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008171 }
8172 } else if (const ObjCObjectPointerType *FromPtrTy
8173 = FromTy->getAs<ObjCObjectPointerType>()) {
8174 if (const ObjCObjectPointerType *ToPtrTy
8175 = ToTy->getAs<ObjCObjectPointerType>())
8176 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8177 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8178 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8179 FromPtrTy->getPointeeType()) &&
8180 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008181 BaseToDerivedConversion = 2;
8182 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008183 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8184 !FromTy->isIncompleteType() &&
8185 !ToRefTy->getPointeeType()->isIncompleteType() &&
8186 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8187 BaseToDerivedConversion = 3;
8188 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8189 ToTy.getNonReferenceType().getCanonicalType() ==
8190 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008191 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8192 << (unsigned) FnKind << FnDesc
8193 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8194 << (unsigned) isObjectArgument << I + 1;
8195 MaybeEmitInheritedConstructorNote(S, Fn);
8196 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008197 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008198 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008199
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008200 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008201 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008202 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008203 << (unsigned) FnKind << FnDesc
8204 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008205 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008206 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008207 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008208 return;
8209 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008210
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008211 if (isa<ObjCObjectPointerType>(CFromTy) &&
8212 isa<PointerType>(CToTy)) {
8213 Qualifiers FromQs = CFromTy.getQualifiers();
8214 Qualifiers ToQs = CToTy.getQualifiers();
8215 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8216 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8217 << (unsigned) FnKind << FnDesc
8218 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8219 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8220 MaybeEmitInheritedConstructorNote(S, Fn);
8221 return;
8222 }
8223 }
8224
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008225 // Emit the generic diagnostic and, optionally, add the hints to it.
8226 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8227 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008228 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008229 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8230 << (unsigned) (Cand->Fix.Kind);
8231
8232 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008233 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8234 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008235 FDiag << *HI;
8236 S.Diag(Fn->getLocation(), FDiag);
8237
Sebastian Redlf677ea32011-02-05 19:23:19 +00008238 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008239}
8240
8241void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8242 unsigned NumFormalArgs) {
8243 // TODO: treat calls to a missing default constructor as a special case
8244
8245 FunctionDecl *Fn = Cand->Function;
8246 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8247
8248 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008249
Douglas Gregor439d3c32011-05-05 00:13:13 +00008250 // With invalid overloaded operators, it's possible that we think we
8251 // have an arity mismatch when it fact it looks like we have the
8252 // right number of arguments, because only overloaded operators have
8253 // the weird behavior of overloading member and non-member functions.
8254 // Just don't report anything.
8255 if (Fn->isInvalidDecl() &&
8256 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8257 return;
8258
John McCalladbb8f82010-01-13 09:16:55 +00008259 // at least / at most / exactly
8260 unsigned mode, modeCount;
8261 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008262 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8263 (Cand->FailureKind == ovl_fail_bad_deduction &&
8264 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008265 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008266 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008267 mode = 0; // "at least"
8268 else
8269 mode = 2; // "exactly"
8270 modeCount = MinParams;
8271 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008272 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8273 (Cand->FailureKind == ovl_fail_bad_deduction &&
8274 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008275 if (MinParams != FnTy->getNumArgs())
8276 mode = 1; // "at most"
8277 else
8278 mode = 2; // "exactly"
8279 modeCount = FnTy->getNumArgs();
8280 }
8281
8282 std::string Description;
8283 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8284
Richard Smithf7b80562012-05-11 05:16:41 +00008285 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8286 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8287 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8288 << Fn->getParamDecl(0) << NumFormalArgs;
8289 else
8290 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8291 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8292 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008293 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008294}
8295
John McCall342fec42010-02-01 18:53:26 +00008296/// Diagnose a failed template-argument deduction.
8297void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008298 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008299 FunctionDecl *Fn = Cand->Function; // pattern
8300
Douglas Gregora9333192010-05-08 17:41:32 +00008301 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008302 NamedDecl *ParamD;
8303 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8304 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8305 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008306 switch (Cand->DeductionFailure.Result) {
8307 case Sema::TDK_Success:
8308 llvm_unreachable("TDK_success while diagnosing bad deduction");
8309
8310 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008311 assert(ParamD && "no parameter found for incomplete deduction result");
8312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8313 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008314 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008315 return;
8316 }
8317
John McCall57e97782010-08-05 09:05:08 +00008318 case Sema::TDK_Underqualified: {
8319 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8320 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8321
8322 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8323
8324 // Param will have been canonicalized, but it should just be a
8325 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008326 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008327 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008328 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008329 assert(S.Context.hasSameType(Param, NonCanonParam));
8330
8331 // Arg has also been canonicalized, but there's nothing we can do
8332 // about that. It also doesn't matter as much, because it won't
8333 // have any template parameters in it (because deduction isn't
8334 // done on dependent types).
8335 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8336
8337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8338 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008339 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008340 return;
8341 }
8342
8343 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008344 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008345 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008346 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008347 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008348 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008349 which = 1;
8350 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008351 which = 2;
8352 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008353
Douglas Gregora9333192010-05-08 17:41:32 +00008354 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008355 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008356 << *Cand->DeductionFailure.getFirstArg()
8357 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008358 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008359 return;
8360 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008361
Douglas Gregorf1a84452010-05-08 19:15:54 +00008362 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008363 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008364 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008365 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008366 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8367 << ParamD->getDeclName();
8368 else {
8369 int index = 0;
8370 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8371 index = TTP->getIndex();
8372 else if (NonTypeTemplateParmDecl *NTTP
8373 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8374 index = NTTP->getIndex();
8375 else
8376 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008377 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008378 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8379 << (index + 1);
8380 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008381 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008382 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008383
Douglas Gregora18592e2010-05-08 18:13:28 +00008384 case Sema::TDK_TooManyArguments:
8385 case Sema::TDK_TooFewArguments:
8386 DiagnoseArityMismatch(S, Cand, NumArgs);
8387 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008388
8389 case Sema::TDK_InstantiationDepth:
8390 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008391 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008392 return;
8393
8394 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008395 // Format the template argument list into the argument string.
8396 llvm::SmallString<128> TemplateArgString;
8397 if (TemplateArgumentList *Args =
8398 Cand->DeductionFailure.getTemplateArgumentList()) {
8399 TemplateArgString = " ";
8400 TemplateArgString += S.getTemplateArgumentBindingsText(
8401 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8402 }
8403
Richard Smith4493c0a2012-05-09 05:17:00 +00008404 // If this candidate was disabled by enable_if, say so.
8405 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8406 if (PDiag && PDiag->second.getDiagID() ==
8407 diag::err_typename_nested_not_found_enable_if) {
8408 // FIXME: Use the source range of the condition, and the fully-qualified
8409 // name of the enable_if template. These are both present in PDiag.
8410 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8411 << "'enable_if'" << TemplateArgString;
8412 return;
8413 }
8414
Richard Smithb8590f32012-05-07 09:03:25 +00008415 // Format the SFINAE diagnostic into the argument string.
8416 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8417 // formatted message in another diagnostic.
8418 llvm::SmallString<128> SFINAEArgString;
8419 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008420 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008421 SFINAEArgString = ": ";
8422 R = SourceRange(PDiag->first, PDiag->first);
8423 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8424 }
8425
Douglas Gregorec20f462010-05-08 20:07:26 +00008426 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008427 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008428 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008429 return;
8430 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008431
John McCall342fec42010-02-01 18:53:26 +00008432 // TODO: diagnose these individually, then kill off
8433 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008434 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008435 case Sema::TDK_FailedOverloadResolution:
8436 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008437 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008438 return;
8439 }
8440}
8441
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008442/// CUDA: diagnose an invalid call across targets.
8443void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8444 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8445 FunctionDecl *Callee = Cand->Function;
8446
8447 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8448 CalleeTarget = S.IdentifyCUDATarget(Callee);
8449
8450 std::string FnDesc;
8451 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8452
8453 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8454 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8455}
8456
John McCall342fec42010-02-01 18:53:26 +00008457/// Generates a 'note' diagnostic for an overload candidate. We've
8458/// already generated a primary error at the call site.
8459///
8460/// It really does need to be a single diagnostic with its caret
8461/// pointed at the candidate declaration. Yes, this creates some
8462/// major challenges of technical writing. Yes, this makes pointing
8463/// out problems with specific arguments quite awkward. It's still
8464/// better than generating twenty screens of text for every failed
8465/// overload.
8466///
8467/// It would be great to be able to express per-candidate problems
8468/// more richly for those diagnostic clients that cared, but we'd
8469/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008470void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008471 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008472 FunctionDecl *Fn = Cand->Function;
8473
John McCall81201622010-01-08 04:41:39 +00008474 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008475 if (Cand->Viable && (Fn->isDeleted() ||
8476 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008477 std::string FnDesc;
8478 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008479
8480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008481 << FnKind << FnDesc
8482 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008483 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008484 return;
John McCall81201622010-01-08 04:41:39 +00008485 }
8486
John McCall220ccbf2010-01-13 00:25:19 +00008487 // We don't really have anything else to say about viable candidates.
8488 if (Cand->Viable) {
8489 S.NoteOverloadCandidate(Fn);
8490 return;
8491 }
John McCall1d318332010-01-12 00:44:57 +00008492
John McCalladbb8f82010-01-13 09:16:55 +00008493 switch (Cand->FailureKind) {
8494 case ovl_fail_too_many_arguments:
8495 case ovl_fail_too_few_arguments:
8496 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008497
John McCalladbb8f82010-01-13 09:16:55 +00008498 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008499 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008500
John McCall717e8912010-01-23 05:17:32 +00008501 case ovl_fail_trivial_conversion:
8502 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008503 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008504 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008505
John McCallb1bdc622010-02-25 01:37:24 +00008506 case ovl_fail_bad_conversion: {
8507 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008508 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008509 if (Cand->Conversions[I].isBad())
8510 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008511
John McCalladbb8f82010-01-13 09:16:55 +00008512 // FIXME: this currently happens when we're called from SemaInit
8513 // when user-conversion overload fails. Figure out how to handle
8514 // those conditions and diagnose them well.
8515 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008516 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008517
8518 case ovl_fail_bad_target:
8519 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008520 }
John McCalla1d7d622010-01-08 00:58:21 +00008521}
8522
8523void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8524 // Desugar the type of the surrogate down to a function type,
8525 // retaining as many typedefs as possible while still showing
8526 // the function type (and, therefore, its parameter types).
8527 QualType FnType = Cand->Surrogate->getConversionType();
8528 bool isLValueReference = false;
8529 bool isRValueReference = false;
8530 bool isPointer = false;
8531 if (const LValueReferenceType *FnTypeRef =
8532 FnType->getAs<LValueReferenceType>()) {
8533 FnType = FnTypeRef->getPointeeType();
8534 isLValueReference = true;
8535 } else if (const RValueReferenceType *FnTypeRef =
8536 FnType->getAs<RValueReferenceType>()) {
8537 FnType = FnTypeRef->getPointeeType();
8538 isRValueReference = true;
8539 }
8540 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8541 FnType = FnTypePtr->getPointeeType();
8542 isPointer = true;
8543 }
8544 // Desugar down to a function type.
8545 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8546 // Reconstruct the pointer/reference as appropriate.
8547 if (isPointer) FnType = S.Context.getPointerType(FnType);
8548 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8549 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8550
8551 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8552 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008553 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008554}
8555
8556void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008557 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008558 SourceLocation OpLoc,
8559 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008560 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008561 std::string TypeStr("operator");
8562 TypeStr += Opc;
8563 TypeStr += "(";
8564 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008565 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008566 TypeStr += ")";
8567 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8568 } else {
8569 TypeStr += ", ";
8570 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8571 TypeStr += ")";
8572 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8573 }
8574}
8575
8576void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8577 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008578 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008579 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8580 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008581 if (ICS.isBad()) break; // all meaningless after first invalid
8582 if (!ICS.isAmbiguous()) continue;
8583
John McCall120d63c2010-08-24 20:38:10 +00008584 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008585 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008586 }
8587}
8588
John McCall1b77e732010-01-15 23:32:50 +00008589SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8590 if (Cand->Function)
8591 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008592 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008593 return Cand->Surrogate->getLocation();
8594 return SourceLocation();
8595}
8596
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008597static unsigned
8598RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008599 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008600 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008601 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008602
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008603 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008604 case Sema::TDK_Incomplete:
8605 return 1;
8606
8607 case Sema::TDK_Underqualified:
8608 case Sema::TDK_Inconsistent:
8609 return 2;
8610
8611 case Sema::TDK_SubstitutionFailure:
8612 case Sema::TDK_NonDeducedMismatch:
8613 return 3;
8614
8615 case Sema::TDK_InstantiationDepth:
8616 case Sema::TDK_FailedOverloadResolution:
8617 return 4;
8618
8619 case Sema::TDK_InvalidExplicitArguments:
8620 return 5;
8621
8622 case Sema::TDK_TooManyArguments:
8623 case Sema::TDK_TooFewArguments:
8624 return 6;
8625 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008626 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008627}
8628
John McCallbf65c0b2010-01-12 00:48:53 +00008629struct CompareOverloadCandidatesForDisplay {
8630 Sema &S;
8631 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008632
8633 bool operator()(const OverloadCandidate *L,
8634 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008635 // Fast-path this check.
8636 if (L == R) return false;
8637
John McCall81201622010-01-08 04:41:39 +00008638 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008639 if (L->Viable) {
8640 if (!R->Viable) return true;
8641
8642 // TODO: introduce a tri-valued comparison for overload
8643 // candidates. Would be more worthwhile if we had a sort
8644 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008645 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8646 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008647 } else if (R->Viable)
8648 return false;
John McCall81201622010-01-08 04:41:39 +00008649
John McCall1b77e732010-01-15 23:32:50 +00008650 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008651
John McCall1b77e732010-01-15 23:32:50 +00008652 // Criteria by which we can sort non-viable candidates:
8653 if (!L->Viable) {
8654 // 1. Arity mismatches come after other candidates.
8655 if (L->FailureKind == ovl_fail_too_many_arguments ||
8656 L->FailureKind == ovl_fail_too_few_arguments)
8657 return false;
8658 if (R->FailureKind == ovl_fail_too_many_arguments ||
8659 R->FailureKind == ovl_fail_too_few_arguments)
8660 return true;
John McCall81201622010-01-08 04:41:39 +00008661
John McCall717e8912010-01-23 05:17:32 +00008662 // 2. Bad conversions come first and are ordered by the number
8663 // of bad conversions and quality of good conversions.
8664 if (L->FailureKind == ovl_fail_bad_conversion) {
8665 if (R->FailureKind != ovl_fail_bad_conversion)
8666 return true;
8667
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008668 // The conversion that can be fixed with a smaller number of changes,
8669 // comes first.
8670 unsigned numLFixes = L->Fix.NumConversionsFixed;
8671 unsigned numRFixes = R->Fix.NumConversionsFixed;
8672 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8673 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008674 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008675 if (numLFixes < numRFixes)
8676 return true;
8677 else
8678 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008679 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008680
John McCall717e8912010-01-23 05:17:32 +00008681 // If there's any ordering between the defined conversions...
8682 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008683 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008684
8685 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008686 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008687 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008688 switch (CompareImplicitConversionSequences(S,
8689 L->Conversions[I],
8690 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008691 case ImplicitConversionSequence::Better:
8692 leftBetter++;
8693 break;
8694
8695 case ImplicitConversionSequence::Worse:
8696 leftBetter--;
8697 break;
8698
8699 case ImplicitConversionSequence::Indistinguishable:
8700 break;
8701 }
8702 }
8703 if (leftBetter > 0) return true;
8704 if (leftBetter < 0) return false;
8705
8706 } else if (R->FailureKind == ovl_fail_bad_conversion)
8707 return false;
8708
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008709 if (L->FailureKind == ovl_fail_bad_deduction) {
8710 if (R->FailureKind != ovl_fail_bad_deduction)
8711 return true;
8712
8713 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8714 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008715 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008716 } else if (R->FailureKind == ovl_fail_bad_deduction)
8717 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008718
John McCall1b77e732010-01-15 23:32:50 +00008719 // TODO: others?
8720 }
8721
8722 // Sort everything else by location.
8723 SourceLocation LLoc = GetLocationForCandidate(L);
8724 SourceLocation RLoc = GetLocationForCandidate(R);
8725
8726 // Put candidates without locations (e.g. builtins) at the end.
8727 if (LLoc.isInvalid()) return false;
8728 if (RLoc.isInvalid()) return true;
8729
8730 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008731 }
8732};
8733
John McCall717e8912010-01-23 05:17:32 +00008734/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008735/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008736void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008737 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008738 assert(!Cand->Viable);
8739
8740 // Don't do anything on failures other than bad conversion.
8741 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8742
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008743 // We only want the FixIts if all the arguments can be corrected.
8744 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008745 // Use a implicit copy initialization to check conversion fixes.
8746 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008747
John McCall717e8912010-01-23 05:17:32 +00008748 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008749 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008750 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008751 while (true) {
8752 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8753 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008754 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008755 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008756 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008757 }
John McCall717e8912010-01-23 05:17:32 +00008758 }
8759
8760 if (ConvIdx == ConvCount)
8761 return;
8762
John McCallb1bdc622010-02-25 01:37:24 +00008763 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8764 "remaining conversion is initialized?");
8765
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008766 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008767 // operation somehow.
8768 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008769
8770 const FunctionProtoType* Proto;
8771 unsigned ArgIdx = ConvIdx;
8772
8773 if (Cand->IsSurrogate) {
8774 QualType ConvType
8775 = Cand->Surrogate->getConversionType().getNonReferenceType();
8776 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8777 ConvType = ConvPtrType->getPointeeType();
8778 Proto = ConvType->getAs<FunctionProtoType>();
8779 ArgIdx--;
8780 } else if (Cand->Function) {
8781 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8782 if (isa<CXXMethodDecl>(Cand->Function) &&
8783 !isa<CXXConstructorDecl>(Cand->Function))
8784 ArgIdx--;
8785 } else {
8786 // Builtin binary operator with a bad first conversion.
8787 assert(ConvCount <= 3);
8788 for (; ConvIdx != ConvCount; ++ConvIdx)
8789 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008790 = TryCopyInitialization(S, Args[ConvIdx],
8791 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008792 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008793 /*InOverloadResolution*/ true,
8794 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008795 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008796 return;
8797 }
8798
8799 // Fill in the rest of the conversions.
8800 unsigned NumArgsInProto = Proto->getNumArgs();
8801 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008802 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008803 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008804 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008805 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008806 /*InOverloadResolution=*/true,
8807 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008808 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008809 // Store the FixIt in the candidate if it exists.
8810 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008811 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008812 }
John McCall717e8912010-01-23 05:17:32 +00008813 else
8814 Cand->Conversions[ConvIdx].setEllipsis();
8815 }
8816}
8817
John McCalla1d7d622010-01-08 00:58:21 +00008818} // end anonymous namespace
8819
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008820/// PrintOverloadCandidates - When overload resolution fails, prints
8821/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008822/// set.
John McCall120d63c2010-08-24 20:38:10 +00008823void OverloadCandidateSet::NoteCandidates(Sema &S,
8824 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008825 llvm::ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008826 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008827 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008828 // Sort the candidates by viability and position. Sorting directly would
8829 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008830 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008831 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8832 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008833 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008834 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008835 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008836 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008837 if (Cand->Function || Cand->IsSurrogate)
8838 Cands.push_back(Cand);
8839 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8840 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008841 }
8842 }
8843
John McCallbf65c0b2010-01-12 00:48:53 +00008844 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008845 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008846
John McCall1d318332010-01-12 00:44:57 +00008847 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008848
Chris Lattner5f9e2722011-07-23 10:55:15 +00008849 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008850 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008851 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008852 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8853 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008854
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008855 // Set an arbitrary limit on the number of candidate functions we'll spam
8856 // the user with. FIXME: This limit should depend on details of the
8857 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008858 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008859 break;
8860 }
8861 ++CandsShown;
8862
John McCalla1d7d622010-01-08 00:58:21 +00008863 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008864 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008865 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008866 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008867 else {
8868 assert(Cand->Viable &&
8869 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008870 // Generally we only see ambiguities including viable builtin
8871 // operators if overload resolution got screwed up by an
8872 // ambiguous user-defined conversion.
8873 //
8874 // FIXME: It's quite possible for different conversions to see
8875 // different ambiguities, though.
8876 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008877 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008878 ReportedAmbiguousConversions = true;
8879 }
John McCalla1d7d622010-01-08 00:58:21 +00008880
John McCall1d318332010-01-12 00:44:57 +00008881 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008882 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008883 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008884 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008885
8886 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008887 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008888}
8889
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008890// [PossiblyAFunctionType] --> [Return]
8891// NonFunctionType --> NonFunctionType
8892// R (A) --> R(A)
8893// R (*)(A) --> R (A)
8894// R (&)(A) --> R (A)
8895// R (S::*)(A) --> R (A)
8896QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8897 QualType Ret = PossiblyAFunctionType;
8898 if (const PointerType *ToTypePtr =
8899 PossiblyAFunctionType->getAs<PointerType>())
8900 Ret = ToTypePtr->getPointeeType();
8901 else if (const ReferenceType *ToTypeRef =
8902 PossiblyAFunctionType->getAs<ReferenceType>())
8903 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008904 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008905 PossiblyAFunctionType->getAs<MemberPointerType>())
8906 Ret = MemTypePtr->getPointeeType();
8907 Ret =
8908 Context.getCanonicalType(Ret).getUnqualifiedType();
8909 return Ret;
8910}
Douglas Gregor904eed32008-11-10 20:40:00 +00008911
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008912// A helper class to help with address of function resolution
8913// - allows us to avoid passing around all those ugly parameters
8914class AddressOfFunctionResolver
8915{
8916 Sema& S;
8917 Expr* SourceExpr;
8918 const QualType& TargetType;
8919 QualType TargetFunctionType; // Extracted function type from target type
8920
8921 bool Complain;
8922 //DeclAccessPair& ResultFunctionAccessPair;
8923 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008924
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008925 bool TargetTypeIsNonStaticMemberFunction;
8926 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008927
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008928 OverloadExpr::FindResult OvlExprInfo;
8929 OverloadExpr *OvlExpr;
8930 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008931 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008932
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008933public:
8934 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8935 const QualType& TargetType, bool Complain)
8936 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8937 Complain(Complain), Context(S.getASTContext()),
8938 TargetTypeIsNonStaticMemberFunction(
8939 !!TargetType->getAs<MemberPointerType>()),
8940 FoundNonTemplateFunction(false),
8941 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8942 OvlExpr(OvlExprInfo.Expression)
8943 {
8944 ExtractUnqualifiedFunctionTypeFromTargetType();
8945
8946 if (!TargetFunctionType->isFunctionType()) {
8947 if (OvlExpr->hasExplicitTemplateArgs()) {
8948 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008949 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008950 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008951
8952 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8953 if (!Method->isStatic()) {
8954 // If the target type is a non-function type and the function
8955 // found is a non-static member function, pretend as if that was
8956 // the target, it's the only possible type to end up with.
8957 TargetTypeIsNonStaticMemberFunction = true;
8958
8959 // And skip adding the function if its not in the proper form.
8960 // We'll diagnose this due to an empty set of functions.
8961 if (!OvlExprInfo.HasFormOfMemberPointer)
8962 return;
8963 }
8964 }
8965
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008966 Matches.push_back(std::make_pair(dap,Fn));
8967 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008968 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008969 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008970 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008971
8972 if (OvlExpr->hasExplicitTemplateArgs())
8973 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008974
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008975 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8976 // C++ [over.over]p4:
8977 // If more than one function is selected, [...]
8978 if (Matches.size() > 1) {
8979 if (FoundNonTemplateFunction)
8980 EliminateAllTemplateMatches();
8981 else
8982 EliminateAllExceptMostSpecializedTemplate();
8983 }
8984 }
8985 }
8986
8987private:
8988 bool isTargetTypeAFunction() const {
8989 return TargetFunctionType->isFunctionType();
8990 }
8991
8992 // [ToType] [Return]
8993
8994 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8995 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8996 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8997 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8998 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8999 }
9000
9001 // return true if any matching specializations were found
9002 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
9003 const DeclAccessPair& CurAccessFunPair) {
9004 if (CXXMethodDecl *Method
9005 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
9006 // Skip non-static function templates when converting to pointer, and
9007 // static when converting to member pointer.
9008 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9009 return false;
9010 }
9011 else if (TargetTypeIsNonStaticMemberFunction)
9012 return false;
9013
9014 // C++ [over.over]p2:
9015 // If the name is a function template, template argument deduction is
9016 // done (14.8.2.2), and if the argument deduction succeeds, the
9017 // resulting template argument list is used to generate a single
9018 // function template specialization, which is added to the set of
9019 // overloaded functions considered.
9020 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009021 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009022 if (Sema::TemplateDeductionResult Result
9023 = S.DeduceTemplateArguments(FunctionTemplate,
9024 &OvlExplicitTemplateArgs,
9025 TargetFunctionType, Specialization,
9026 Info)) {
9027 // FIXME: make a note of the failed deduction for diagnostics.
9028 (void)Result;
9029 return false;
9030 }
9031
9032 // Template argument deduction ensures that we have an exact match.
9033 // This function template specicalization works.
9034 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9035 assert(TargetFunctionType
9036 == Context.getCanonicalType(Specialization->getType()));
9037 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9038 return true;
9039 }
9040
9041 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9042 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009044 // Skip non-static functions when converting to pointer, and static
9045 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009046 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9047 return false;
9048 }
9049 else if (TargetTypeIsNonStaticMemberFunction)
9050 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009051
Chandler Carruthbd647292009-12-29 06:17:27 +00009052 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009053 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009054 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9055 if (S.CheckCUDATarget(Caller, FunDecl))
9056 return false;
9057
Douglas Gregor43c79c22009-12-09 00:47:37 +00009058 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009059 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9060 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009061 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9062 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009063 Matches.push_back(std::make_pair(CurAccessFunPair,
9064 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009065 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009066 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009067 }
Mike Stump1eb44332009-09-09 15:08:12 +00009068 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009069
9070 return false;
9071 }
9072
9073 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9074 bool Ret = false;
9075
9076 // If the overload expression doesn't have the form of a pointer to
9077 // member, don't try to convert it to a pointer-to-member type.
9078 if (IsInvalidFormOfPointerToMemberFunction())
9079 return false;
9080
9081 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9082 E = OvlExpr->decls_end();
9083 I != E; ++I) {
9084 // Look through any using declarations to find the underlying function.
9085 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9086
9087 // C++ [over.over]p3:
9088 // Non-member functions and static member functions match
9089 // targets of type "pointer-to-function" or "reference-to-function."
9090 // Nonstatic member functions match targets of
9091 // type "pointer-to-member-function."
9092 // Note that according to DR 247, the containing class does not matter.
9093 if (FunctionTemplateDecl *FunctionTemplate
9094 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9095 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9096 Ret = true;
9097 }
9098 // If we have explicit template arguments supplied, skip non-templates.
9099 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9100 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9101 Ret = true;
9102 }
9103 assert(Ret || Matches.empty());
9104 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009105 }
9106
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009107 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009108 // [...] and any given function template specialization F1 is
9109 // eliminated if the set contains a second function template
9110 // specialization whose function template is more specialized
9111 // than the function template of F1 according to the partial
9112 // ordering rules of 14.5.5.2.
9113
9114 // The algorithm specified above is quadratic. We instead use a
9115 // two-pass algorithm (similar to the one used to identify the
9116 // best viable function in an overload set) that identifies the
9117 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009118
9119 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9120 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9121 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009122
John McCallc373d482010-01-27 01:50:18 +00009123 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009124 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9125 TPOC_Other, 0, SourceExpr->getLocStart(),
9126 S.PDiag(),
9127 S.PDiag(diag::err_addr_ovl_ambiguous)
9128 << Matches[0].second->getDeclName(),
9129 S.PDiag(diag::note_ovl_candidate)
9130 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009131 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009132
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009133 if (Result != MatchesCopy.end()) {
9134 // Make it the first and only element
9135 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9136 Matches[0].second = cast<FunctionDecl>(*Result);
9137 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009138 }
9139 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009140
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009141 void EliminateAllTemplateMatches() {
9142 // [...] any function template specializations in the set are
9143 // eliminated if the set also contains a non-template function, [...]
9144 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9145 if (Matches[I].second->getPrimaryTemplate() == 0)
9146 ++I;
9147 else {
9148 Matches[I] = Matches[--N];
9149 Matches.set_size(N);
9150 }
9151 }
9152 }
9153
9154public:
9155 void ComplainNoMatchesFound() const {
9156 assert(Matches.empty());
9157 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9158 << OvlExpr->getName() << TargetFunctionType
9159 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009160 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009161 }
9162
9163 bool IsInvalidFormOfPointerToMemberFunction() const {
9164 return TargetTypeIsNonStaticMemberFunction &&
9165 !OvlExprInfo.HasFormOfMemberPointer;
9166 }
9167
9168 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9169 // TODO: Should we condition this on whether any functions might
9170 // have matched, or is it more appropriate to do that in callers?
9171 // TODO: a fixit wouldn't hurt.
9172 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9173 << TargetType << OvlExpr->getSourceRange();
9174 }
9175
9176 void ComplainOfInvalidConversion() const {
9177 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9178 << OvlExpr->getName() << TargetType;
9179 }
9180
9181 void ComplainMultipleMatchesFound() const {
9182 assert(Matches.size() > 1);
9183 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9184 << OvlExpr->getName()
9185 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009186 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009187 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009188
9189 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9190
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009191 int getNumMatches() const { return Matches.size(); }
9192
9193 FunctionDecl* getMatchingFunctionDecl() const {
9194 if (Matches.size() != 1) return 0;
9195 return Matches[0].second;
9196 }
9197
9198 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9199 if (Matches.size() != 1) return 0;
9200 return &Matches[0].first;
9201 }
9202};
9203
9204/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9205/// an overloaded function (C++ [over.over]), where @p From is an
9206/// expression with overloaded function type and @p ToType is the type
9207/// we're trying to resolve to. For example:
9208///
9209/// @code
9210/// int f(double);
9211/// int f(int);
9212///
9213/// int (*pfd)(double) = f; // selects f(double)
9214/// @endcode
9215///
9216/// This routine returns the resulting FunctionDecl if it could be
9217/// resolved, and NULL otherwise. When @p Complain is true, this
9218/// routine will emit diagnostics if there is an error.
9219FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009220Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9221 QualType TargetType,
9222 bool Complain,
9223 DeclAccessPair &FoundResult,
9224 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009225 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009226
9227 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9228 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009229 int NumMatches = Resolver.getNumMatches();
9230 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009231 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009232 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9233 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9234 else
9235 Resolver.ComplainNoMatchesFound();
9236 }
9237 else if (NumMatches > 1 && Complain)
9238 Resolver.ComplainMultipleMatchesFound();
9239 else if (NumMatches == 1) {
9240 Fn = Resolver.getMatchingFunctionDecl();
9241 assert(Fn);
9242 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009243 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009244 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009245 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009246
9247 if (pHadMultipleCandidates)
9248 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009249 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009250}
9251
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009252/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009253/// resolve that overloaded function expression down to a single function.
9254///
9255/// This routine can only resolve template-ids that refer to a single function
9256/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009257/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009258/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009259FunctionDecl *
9260Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9261 bool Complain,
9262 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009263 // C++ [over.over]p1:
9264 // [...] [Note: any redundant set of parentheses surrounding the
9265 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009266 // C++ [over.over]p1:
9267 // [...] The overloaded function name can be preceded by the &
9268 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009269
Douglas Gregor4b52e252009-12-21 23:17:24 +00009270 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009271 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009272 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009273
9274 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009275 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009276
Douglas Gregor4b52e252009-12-21 23:17:24 +00009277 // Look through all of the overloaded functions, searching for one
9278 // whose type matches exactly.
9279 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009280 for (UnresolvedSetIterator I = ovl->decls_begin(),
9281 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009282 // C++0x [temp.arg.explicit]p3:
9283 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009284 // where deduction is not done, if a template argument list is
9285 // specified and it, along with any default template arguments,
9286 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009287 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009288 FunctionTemplateDecl *FunctionTemplate
9289 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009290
Douglas Gregor4b52e252009-12-21 23:17:24 +00009291 // C++ [over.over]p2:
9292 // If the name is a function template, template argument deduction is
9293 // done (14.8.2.2), and if the argument deduction succeeds, the
9294 // resulting template argument list is used to generate a single
9295 // function template specialization, which is added to the set of
9296 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009297 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009298 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009299 if (TemplateDeductionResult Result
9300 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9301 Specialization, Info)) {
9302 // FIXME: make a note of the failed deduction for diagnostics.
9303 (void)Result;
9304 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009305 }
9306
John McCall864c0412011-04-26 20:42:42 +00009307 assert(Specialization && "no specialization and no error?");
9308
Douglas Gregor4b52e252009-12-21 23:17:24 +00009309 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009310 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009311 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009312 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9313 << ovl->getName();
9314 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009315 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009316 return 0;
John McCall864c0412011-04-26 20:42:42 +00009317 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009318
John McCall864c0412011-04-26 20:42:42 +00009319 Matched = Specialization;
9320 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009321 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009322
Douglas Gregor4b52e252009-12-21 23:17:24 +00009323 return Matched;
9324}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009325
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009326
9327
9328
John McCall6dbba4f2011-10-11 23:14:30 +00009329// Resolve and fix an overloaded expression that can be resolved
9330// because it identifies a single function template specialization.
9331//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009332// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009333//
9334// Return true if it was logically possible to so resolve the
9335// expression, regardless of whether or not it succeeded. Always
9336// returns true if 'complain' is set.
9337bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9338 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9339 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009340 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009341 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009342 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009343
John McCall6dbba4f2011-10-11 23:14:30 +00009344 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009345
John McCall864c0412011-04-26 20:42:42 +00009346 DeclAccessPair found;
9347 ExprResult SingleFunctionExpression;
9348 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9349 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009350 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009351 SrcExpr = ExprError();
9352 return true;
9353 }
John McCall864c0412011-04-26 20:42:42 +00009354
9355 // It is only correct to resolve to an instance method if we're
9356 // resolving a form that's permitted to be a pointer to member.
9357 // Otherwise we'll end up making a bound member expression, which
9358 // is illegal in all the contexts we resolve like this.
9359 if (!ovl.HasFormOfMemberPointer &&
9360 isa<CXXMethodDecl>(fn) &&
9361 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009362 if (!complain) return false;
9363
9364 Diag(ovl.Expression->getExprLoc(),
9365 diag::err_bound_member_function)
9366 << 0 << ovl.Expression->getSourceRange();
9367
9368 // TODO: I believe we only end up here if there's a mix of
9369 // static and non-static candidates (otherwise the expression
9370 // would have 'bound member' type, not 'overload' type).
9371 // Ideally we would note which candidate was chosen and why
9372 // the static candidates were rejected.
9373 SrcExpr = ExprError();
9374 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009375 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009376
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009377 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009378 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009379 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009380
9381 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009382 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009383 SingleFunctionExpression =
9384 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009385 if (SingleFunctionExpression.isInvalid()) {
9386 SrcExpr = ExprError();
9387 return true;
9388 }
9389 }
John McCall864c0412011-04-26 20:42:42 +00009390 }
9391
9392 if (!SingleFunctionExpression.isUsable()) {
9393 if (complain) {
9394 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9395 << ovl.Expression->getName()
9396 << DestTypeForComplaining
9397 << OpRangeForComplaining
9398 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009399 NoteAllOverloadCandidates(SrcExpr.get());
9400
9401 SrcExpr = ExprError();
9402 return true;
9403 }
9404
9405 return false;
John McCall864c0412011-04-26 20:42:42 +00009406 }
9407
John McCall6dbba4f2011-10-11 23:14:30 +00009408 SrcExpr = SingleFunctionExpression;
9409 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009410}
9411
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009412/// \brief Add a single candidate to the overload set.
9413static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009414 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009415 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009416 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009417 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009418 bool PartialOverloading,
9419 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009420 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009421 if (isa<UsingShadowDecl>(Callee))
9422 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9423
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009424 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009425 if (ExplicitTemplateArgs) {
9426 assert(!KnownValid && "Explicit template arguments?");
9427 return;
9428 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009429 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9430 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009431 return;
John McCallba135432009-11-21 08:51:07 +00009432 }
9433
9434 if (FunctionTemplateDecl *FuncTemplate
9435 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009436 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009437 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009438 return;
9439 }
9440
Richard Smith2ced0442011-06-26 22:19:54 +00009441 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009442}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009443
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009444/// \brief Add the overload candidates named by callee and/or found by argument
9445/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009446void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009447 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009448 OverloadCandidateSet &CandidateSet,
9449 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009450
9451#ifndef NDEBUG
9452 // Verify that ArgumentDependentLookup is consistent with the rules
9453 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009454 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009455 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9456 // and let Y be the lookup set produced by argument dependent
9457 // lookup (defined as follows). If X contains
9458 //
9459 // -- a declaration of a class member, or
9460 //
9461 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009462 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009463 //
9464 // -- a declaration that is neither a function or a function
9465 // template
9466 //
9467 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009468
John McCall3b4294e2009-12-16 12:17:52 +00009469 if (ULE->requiresADL()) {
9470 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9471 E = ULE->decls_end(); I != E; ++I) {
9472 assert(!(*I)->getDeclContext()->isRecord());
9473 assert(isa<UsingShadowDecl>(*I) ||
9474 !(*I)->getDeclContext()->isFunctionOrMethod());
9475 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009476 }
9477 }
9478#endif
9479
John McCall3b4294e2009-12-16 12:17:52 +00009480 // It would be nice to avoid this copy.
9481 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009482 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009483 if (ULE->hasExplicitTemplateArgs()) {
9484 ULE->copyTemplateArgumentsInto(TABuffer);
9485 ExplicitTemplateArgs = &TABuffer;
9486 }
9487
9488 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9489 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009490 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9491 CandidateSet, PartialOverloading,
9492 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009493
John McCall3b4294e2009-12-16 12:17:52 +00009494 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009495 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009496 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009497 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009498 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009499}
John McCall578b69b2009-12-16 08:11:27 +00009500
Richard Smithf50e88a2011-06-05 22:42:48 +00009501/// Attempt to recover from an ill-formed use of a non-dependent name in a
9502/// template, where the non-dependent name was declared after the template
9503/// was defined. This is common in code written for a compilers which do not
9504/// correctly implement two-stage name lookup.
9505///
9506/// Returns true if a viable candidate was found and a diagnostic was issued.
9507static bool
9508DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9509 const CXXScopeSpec &SS, LookupResult &R,
9510 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009511 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009512 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9513 return false;
9514
9515 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009516 if (DC->isTransparentContext())
9517 continue;
9518
Richard Smithf50e88a2011-06-05 22:42:48 +00009519 SemaRef.LookupQualifiedName(R, DC);
9520
9521 if (!R.empty()) {
9522 R.suppressDiagnostics();
9523
9524 if (isa<CXXRecordDecl>(DC)) {
9525 // Don't diagnose names we find in classes; we get much better
9526 // diagnostics for these from DiagnoseEmptyLookup.
9527 R.clear();
9528 return false;
9529 }
9530
9531 OverloadCandidateSet Candidates(FnLoc);
9532 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9533 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009534 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009535 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009536
9537 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009538 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009539 // No viable functions. Don't bother the user with notes for functions
9540 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009541 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009542 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009543 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009544
9545 // Find the namespaces where ADL would have looked, and suggest
9546 // declaring the function there instead.
9547 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9548 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009549 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009550 AssociatedNamespaces,
9551 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009552 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009553 DeclContext *Std = SemaRef.getStdNamespace();
9554 for (Sema::AssociatedNamespaceSet::iterator
9555 it = AssociatedNamespaces.begin(),
9556 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009557 // Never suggest declaring a function within namespace 'std'.
9558 if (Std && Std->Encloses(*it))
9559 continue;
9560
9561 // Never suggest declaring a function within a namespace with a reserved
9562 // name, like __gnu_cxx.
9563 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9564 if (NS &&
9565 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9566 continue;
9567
9568 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009569 }
9570
9571 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9572 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009573 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009574 SemaRef.Diag(Best->Function->getLocation(),
9575 diag::note_not_found_by_two_phase_lookup)
9576 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009577 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009578 SemaRef.Diag(Best->Function->getLocation(),
9579 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009580 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009581 } else {
9582 // FIXME: It would be useful to list the associated namespaces here,
9583 // but the diagnostics infrastructure doesn't provide a way to produce
9584 // a localized representation of a list of items.
9585 SemaRef.Diag(Best->Function->getLocation(),
9586 diag::note_not_found_by_two_phase_lookup)
9587 << R.getLookupName() << 2;
9588 }
9589
9590 // Try to recover by calling this function.
9591 return true;
9592 }
9593
9594 R.clear();
9595 }
9596
9597 return false;
9598}
9599
9600/// Attempt to recover from ill-formed use of a non-dependent operator in a
9601/// template, where the non-dependent operator was declared after the template
9602/// was defined.
9603///
9604/// Returns true if a viable candidate was found and a diagnostic was issued.
9605static bool
9606DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9607 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009608 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009609 DeclarationName OpName =
9610 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9611 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9612 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009613 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009614}
9615
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009616namespace {
9617// Callback to limit the allowed keywords and to only accept typo corrections
9618// that are keywords or whose decls refer to functions (or template functions)
9619// that accept the given number of arguments.
9620class RecoveryCallCCC : public CorrectionCandidateCallback {
9621 public:
9622 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9623 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009624 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009625 WantRemainingKeywords = false;
9626 }
9627
9628 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9629 if (!candidate.getCorrectionDecl())
9630 return candidate.isKeyword();
9631
9632 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9633 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9634 FunctionDecl *FD = 0;
9635 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9636 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9637 FD = FTD->getTemplatedDecl();
9638 if (!HasExplicitTemplateArgs && !FD) {
9639 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9640 // If the Decl is neither a function nor a template function,
9641 // determine if it is a pointer or reference to a function. If so,
9642 // check against the number of arguments expected for the pointee.
9643 QualType ValType = cast<ValueDecl>(ND)->getType();
9644 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9645 ValType = ValType->getPointeeType();
9646 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9647 if (FPT->getNumArgs() == NumArgs)
9648 return true;
9649 }
9650 }
9651 if (FD && FD->getNumParams() >= NumArgs &&
9652 FD->getMinRequiredArguments() <= NumArgs)
9653 return true;
9654 }
9655 return false;
9656 }
9657
9658 private:
9659 unsigned NumArgs;
9660 bool HasExplicitTemplateArgs;
9661};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009662
9663// Callback that effectively disabled typo correction
9664class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9665 public:
9666 NoTypoCorrectionCCC() {
9667 WantTypeSpecifiers = false;
9668 WantExpressionKeywords = false;
9669 WantCXXNamedCasts = false;
9670 WantRemainingKeywords = false;
9671 }
9672
9673 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9674 return false;
9675 }
9676};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009677
9678class BuildRecoveryCallExprRAII {
9679 Sema &SemaRef;
9680public:
9681 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9682 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9683 SemaRef.IsBuildingRecoveryCallExpr = true;
9684 }
9685
9686 ~BuildRecoveryCallExprRAII() {
9687 SemaRef.IsBuildingRecoveryCallExpr = false;
9688 }
9689};
9690
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009691}
9692
John McCall578b69b2009-12-16 08:11:27 +00009693/// Attempts to recover from a call where no functions were found.
9694///
9695/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009696static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009697BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009698 UnresolvedLookupExpr *ULE,
9699 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009700 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009701 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009702 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009703 // Do not try to recover if it is already building a recovery call.
9704 // This stops infinite loops for template instantiations like
9705 //
9706 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9707 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9708 //
9709 if (SemaRef.IsBuildingRecoveryCallExpr)
9710 return ExprError();
9711 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009712
9713 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009714 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009715 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009716
John McCall3b4294e2009-12-16 12:17:52 +00009717 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009718 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009719 if (ULE->hasExplicitTemplateArgs()) {
9720 ULE->copyTemplateArgumentsInto(TABuffer);
9721 ExplicitTemplateArgs = &TABuffer;
9722 }
9723
John McCall578b69b2009-12-16 08:11:27 +00009724 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9725 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009726 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009727 NoTypoCorrectionCCC RejectAll;
9728 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9729 (CorrectionCandidateCallback*)&Validator :
9730 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009731 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009732 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009733 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009734 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009735 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009736 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009737
John McCall3b4294e2009-12-16 12:17:52 +00009738 assert(!R.empty() && "lookup results empty despite recovery");
9739
9740 // Build an implicit member call if appropriate. Just drop the
9741 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009742 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009743 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009744 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9745 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009746 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009747 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009748 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009749 else
9750 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9751
9752 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009753 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009754
9755 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009756 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009757 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009758 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009759 MultiExprArg(Args.data(), Args.size()),
9760 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009761}
Douglas Gregord7a95972010-06-08 17:35:15 +00009762
Sam Panzere1715b62012-08-21 00:52:01 +00009763/// \brief Constructs and populates an OverloadedCandidateSet from
9764/// the given function.
9765/// \returns true when an the ExprResult output parameter has been set.
9766bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9767 UnresolvedLookupExpr *ULE,
9768 Expr **Args, unsigned NumArgs,
9769 SourceLocation RParenLoc,
9770 OverloadCandidateSet *CandidateSet,
9771 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009772#ifndef NDEBUG
9773 if (ULE->requiresADL()) {
9774 // To do ADL, we must have found an unqualified name.
9775 assert(!ULE->getQualifier() && "qualified name with ADL");
9776
9777 // We don't perform ADL for implicit declarations of builtins.
9778 // Verify that this was correctly set up.
9779 FunctionDecl *F;
9780 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9781 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9782 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009783 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009784
John McCall3b4294e2009-12-16 12:17:52 +00009785 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009786 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009787 }
John McCall3b4294e2009-12-16 12:17:52 +00009788#endif
9789
John McCall5acb0c92011-10-17 18:40:02 +00009790 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009791 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9792 *Result = ExprError();
9793 return true;
9794 }
Douglas Gregor17330012009-02-04 15:01:18 +00009795
John McCall3b4294e2009-12-16 12:17:52 +00009796 // Add the functions denoted by the callee to the set of candidate
9797 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009798 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009799 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009800
9801 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009802 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9803 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009804 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009805 // In Microsoft mode, if we are inside a template class member function then
9806 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009807 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009808 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009809 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009810 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009811 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9812 llvm::makeArrayRef(Args, NumArgs),
9813 Context.DependentTy, VK_RValue,
9814 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009815 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009816 *Result = Owned(CE);
9817 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009818 }
Sam Panzere1715b62012-08-21 00:52:01 +00009819 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009820 }
John McCall578b69b2009-12-16 08:11:27 +00009821
John McCall5acb0c92011-10-17 18:40:02 +00009822 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009823 return false;
9824}
John McCall5acb0c92011-10-17 18:40:02 +00009825
Sam Panzere1715b62012-08-21 00:52:01 +00009826/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9827/// the completed call expression. If overload resolution fails, emits
9828/// diagnostics and returns ExprError()
9829static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9830 UnresolvedLookupExpr *ULE,
9831 SourceLocation LParenLoc,
9832 Expr **Args, unsigned NumArgs,
9833 SourceLocation RParenLoc,
9834 Expr *ExecConfig,
9835 OverloadCandidateSet *CandidateSet,
9836 OverloadCandidateSet::iterator *Best,
9837 OverloadingResult OverloadResult,
9838 bool AllowTypoCorrection) {
9839 if (CandidateSet->empty())
9840 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9841 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9842 RParenLoc, /*EmptyLookup=*/true,
9843 AllowTypoCorrection);
9844
9845 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009846 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009847 FunctionDecl *FDecl = (*Best)->Function;
9848 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9849 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9850 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9851 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9852 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9853 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009854 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009855
Richard Smithf50e88a2011-06-05 22:42:48 +00009856 case OR_No_Viable_Function: {
9857 // Try to recover by looking for viable functions which the user might
9858 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009859 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009860 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9861 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009862 /*EmptyLookup=*/false,
9863 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009864 if (!Recovery.isInvalid())
9865 return Recovery;
9866
Sam Panzere1715b62012-08-21 00:52:01 +00009867 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009868 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009869 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009870 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9871 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009872 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009873 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009874
9875 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009876 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00009877 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009878 CandidateSet->NoteCandidates(SemaRef, OCD_ViableCandidates,
9879 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009880 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009881
Sam Panzere1715b62012-08-21 00:52:01 +00009882 case OR_Deleted: {
9883 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9884 << (*Best)->Function->isDeleted()
9885 << ULE->getName()
9886 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9887 << Fn->getSourceRange();
9888 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9889 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009890
Sam Panzere1715b62012-08-21 00:52:01 +00009891 // We emitted an error for the unvailable/deleted function call but keep
9892 // the call in the AST.
9893 FunctionDecl *FDecl = (*Best)->Function;
9894 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9895 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9896 RParenLoc, ExecConfig);
9897 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009898 }
9899
Douglas Gregorff331c12010-07-25 18:17:45 +00009900 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009901 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009902}
9903
Sam Panzere1715b62012-08-21 00:52:01 +00009904/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9905/// (which eventually refers to the declaration Func) and the call
9906/// arguments Args/NumArgs, attempt to resolve the function call down
9907/// to a specific function. If overload resolution succeeds, returns
9908/// the call expression produced by overload resolution.
9909/// Otherwise, emits diagnostics and returns ExprError.
9910ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9911 UnresolvedLookupExpr *ULE,
9912 SourceLocation LParenLoc,
9913 Expr **Args, unsigned NumArgs,
9914 SourceLocation RParenLoc,
9915 Expr *ExecConfig,
9916 bool AllowTypoCorrection) {
9917 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9918 ExprResult result;
9919
9920 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9921 &CandidateSet, &result))
9922 return result;
9923
9924 OverloadCandidateSet::iterator Best;
9925 OverloadingResult OverloadResult =
9926 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9927
9928 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9929 RParenLoc, ExecConfig, &CandidateSet,
9930 &Best, OverloadResult,
9931 AllowTypoCorrection);
9932}
9933
John McCall6e266892010-01-26 03:27:55 +00009934static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009935 return Functions.size() > 1 ||
9936 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9937}
9938
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009939/// \brief Create a unary operation that may resolve to an overloaded
9940/// operator.
9941///
9942/// \param OpLoc The location of the operator itself (e.g., '*').
9943///
9944/// \param OpcIn The UnaryOperator::Opcode that describes this
9945/// operator.
9946///
James Dennett40ae6662012-06-22 08:52:37 +00009947/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009948/// considered by overload resolution. The caller needs to build this
9949/// set based on the context using, e.g.,
9950/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9951/// set should not contain any member functions; those will be added
9952/// by CreateOverloadedUnaryOp().
9953///
James Dennett8da16872012-06-22 10:32:46 +00009954/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009955ExprResult
John McCall6e266892010-01-26 03:27:55 +00009956Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9957 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009958 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009959 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009960
9961 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9962 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9963 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009964 // TODO: provide better source location info.
9965 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009966
John McCall5acb0c92011-10-17 18:40:02 +00009967 if (checkPlaceholderForOverload(*this, Input))
9968 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009969
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009970 Expr *Args[2] = { Input, 0 };
9971 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009972
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009973 // For post-increment and post-decrement, add the implicit '0' as
9974 // the second argument, so that we know this is a post-increment or
9975 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009976 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009977 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009978 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9979 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009980 NumArgs = 2;
9981 }
9982
9983 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009984 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009985 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009986 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009987 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009988 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009989 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009990
John McCallc373d482010-01-27 01:50:18 +00009991 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009992 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009993 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009994 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009995 /*ADL*/ true, IsOverloaded(Fns),
9996 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009997 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009998 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009999 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010000 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010001 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010002 }
10003
10004 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010005 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010006
10007 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010008 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10009 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010010
10011 // Add operator candidates that are member functions.
10012 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10013
John McCall6e266892010-01-26 03:27:55 +000010014 // Add candidates from ADL.
10015 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010016 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010017 /*ExplicitTemplateArgs*/ 0,
10018 CandidateSet);
10019
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010020 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010021 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010022
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010023 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10024
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010025 // Perform overload resolution.
10026 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010027 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010028 case OR_Success: {
10029 // We found a built-in operator or an overloaded operator.
10030 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010031
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010032 if (FnDecl) {
10033 // We matched an overloaded operator. Build a call to that
10034 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010035
Eli Friedman5f2987c2012-02-02 03:46:19 +000010036 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010037
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010038 // Convert the arguments.
10039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010040 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010041
John Wiegley429bb272011-04-08 18:41:53 +000010042 ExprResult InputRes =
10043 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10044 Best->FoundDecl, Method);
10045 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010046 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010047 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010048 } else {
10049 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010050 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010051 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010052 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010053 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010054 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010055 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010056 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010057 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010058 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010059 }
10060
John McCallb697e082010-05-06 18:15:07 +000010061 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10062
John McCallf89e55a2010-11-18 06:31:45 +000010063 // Determine the result type.
10064 QualType ResultTy = FnDecl->getResultType();
10065 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10066 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010067
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010068 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010069 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010070 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010071 if (FnExpr.isInvalid())
10072 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010073
Eli Friedman4c3b8962009-11-18 03:58:17 +000010074 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010075 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010076 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010077 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010078 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010079
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010080 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010081 FnDecl))
10082 return ExprError();
10083
John McCall9ae2f072010-08-23 23:25:46 +000010084 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010085 } else {
10086 // We matched a built-in operator. Convert the arguments, then
10087 // break out so that we will build the appropriate built-in
10088 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010089 ExprResult InputRes =
10090 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10091 Best->Conversions[0], AA_Passing);
10092 if (InputRes.isInvalid())
10093 return ExprError();
10094 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010095 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010096 }
John Wiegley429bb272011-04-08 18:41:53 +000010097 }
10098
10099 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010100 // This is an erroneous use of an operator which can be overloaded by
10101 // a non-member function. Check for non-member operators which were
10102 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010103 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10104 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010105 // FIXME: Recover by calling the found function.
10106 return ExprError();
10107
John Wiegley429bb272011-04-08 18:41:53 +000010108 // No viable function; fall through to handling this as a
10109 // built-in operator, which will produce an error message for us.
10110 break;
10111
10112 case OR_Ambiguous:
10113 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10114 << UnaryOperator::getOpcodeStr(Opc)
10115 << Input->getType()
10116 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010117 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10118 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010119 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10120 return ExprError();
10121
10122 case OR_Deleted:
10123 Diag(OpLoc, diag::err_ovl_deleted_oper)
10124 << Best->Function->isDeleted()
10125 << UnaryOperator::getOpcodeStr(Opc)
10126 << getDeletedOrUnavailableSuffix(Best->Function)
10127 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010128 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10129 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010130 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010131 return ExprError();
10132 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010133
10134 // Either we found no viable overloaded operator or we matched a
10135 // built-in operator. In either case, fall through to trying to
10136 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010137 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010138}
10139
Douglas Gregor063daf62009-03-13 18:40:31 +000010140/// \brief Create a binary operation that may resolve to an overloaded
10141/// operator.
10142///
10143/// \param OpLoc The location of the operator itself (e.g., '+').
10144///
10145/// \param OpcIn The BinaryOperator::Opcode that describes this
10146/// operator.
10147///
James Dennett40ae6662012-06-22 08:52:37 +000010148/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010149/// considered by overload resolution. The caller needs to build this
10150/// set based on the context using, e.g.,
10151/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10152/// set should not contain any member functions; those will be added
10153/// by CreateOverloadedBinOp().
10154///
10155/// \param LHS Left-hand argument.
10156/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010157ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010158Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010159 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010160 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010161 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010162 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010163 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010164
10165 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10166 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10167 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10168
10169 // If either side is type-dependent, create an appropriate dependent
10170 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010171 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010172 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010173 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010174 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010175 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010176 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010177 Context.DependentTy,
10178 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010179 OpLoc,
10180 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010181
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010182 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10183 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010184 VK_LValue,
10185 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010186 Context.DependentTy,
10187 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010188 OpLoc,
10189 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010190 }
John McCall6e266892010-01-26 03:27:55 +000010191
10192 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010193 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010194 // TODO: provide better source location info in DNLoc component.
10195 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010196 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010197 = UnresolvedLookupExpr::Create(Context, NamingClass,
10198 NestedNameSpecifierLoc(), OpNameInfo,
10199 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010200 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010201 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10202 Context.DependentTy, VK_RValue,
10203 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010204 }
10205
John McCall5acb0c92011-10-17 18:40:02 +000010206 // Always do placeholder-like conversions on the RHS.
10207 if (checkPlaceholderForOverload(*this, Args[1]))
10208 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010209
John McCall3c3b7f92011-10-25 17:37:35 +000010210 // Do placeholder-like conversion on the LHS; note that we should
10211 // not get here with a PseudoObject LHS.
10212 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010213 if (checkPlaceholderForOverload(*this, Args[0]))
10214 return ExprError();
10215
Sebastian Redl275c2b42009-11-18 23:10:33 +000010216 // If this is the assignment operator, we only perform overload resolution
10217 // if the left-hand side is a class or enumeration type. This is actually
10218 // a hack. The standard requires that we do overload resolution between the
10219 // various built-in candidates, but as DR507 points out, this can lead to
10220 // problems. So we do it this way, which pretty much follows what GCC does.
10221 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010222 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010223 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010224
John McCall0e800c92010-12-04 08:14:53 +000010225 // If this is the .* operator, which is not overloadable, just
10226 // create a built-in binary operator.
10227 if (Opc == BO_PtrMemD)
10228 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10229
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010230 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010231 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010232
10233 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010234 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010235
10236 // Add operator candidates that are member functions.
10237 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10238
John McCall6e266892010-01-26 03:27:55 +000010239 // Add candidates from ADL.
10240 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010241 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010242 /*ExplicitTemplateArgs*/ 0,
10243 CandidateSet);
10244
Douglas Gregor063daf62009-03-13 18:40:31 +000010245 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010246 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010247
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010248 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10249
Douglas Gregor063daf62009-03-13 18:40:31 +000010250 // Perform overload resolution.
10251 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010252 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010253 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010254 // We found a built-in operator or an overloaded operator.
10255 FunctionDecl *FnDecl = Best->Function;
10256
10257 if (FnDecl) {
10258 // We matched an overloaded operator. Build a call to that
10259 // operator.
10260
Eli Friedman5f2987c2012-02-02 03:46:19 +000010261 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010262
Douglas Gregor063daf62009-03-13 18:40:31 +000010263 // Convert the arguments.
10264 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010265 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010266 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010267
Chandler Carruth6df868e2010-12-12 08:17:55 +000010268 ExprResult Arg1 =
10269 PerformCopyInitialization(
10270 InitializedEntity::InitializeParameter(Context,
10271 FnDecl->getParamDecl(0)),
10272 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010273 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010274 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010275
John Wiegley429bb272011-04-08 18:41:53 +000010276 ExprResult Arg0 =
10277 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10278 Best->FoundDecl, Method);
10279 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010280 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010281 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010282 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010283 } else {
10284 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010285 ExprResult Arg0 = PerformCopyInitialization(
10286 InitializedEntity::InitializeParameter(Context,
10287 FnDecl->getParamDecl(0)),
10288 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010289 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010290 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010291
Chandler Carruth6df868e2010-12-12 08:17:55 +000010292 ExprResult Arg1 =
10293 PerformCopyInitialization(
10294 InitializedEntity::InitializeParameter(Context,
10295 FnDecl->getParamDecl(1)),
10296 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010297 if (Arg1.isInvalid())
10298 return ExprError();
10299 Args[0] = LHS = Arg0.takeAs<Expr>();
10300 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010301 }
10302
John McCallb697e082010-05-06 18:15:07 +000010303 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10304
John McCallf89e55a2010-11-18 06:31:45 +000010305 // Determine the result type.
10306 QualType ResultTy = FnDecl->getResultType();
10307 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10308 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010309
10310 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010311 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10312 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010313 if (FnExpr.isInvalid())
10314 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010315
John McCall9ae2f072010-08-23 23:25:46 +000010316 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010317 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010318 Args, ResultTy, VK, OpLoc,
10319 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010320
10321 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010322 FnDecl))
10323 return ExprError();
10324
John McCall9ae2f072010-08-23 23:25:46 +000010325 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010326 } else {
10327 // We matched a built-in operator. Convert the arguments, then
10328 // break out so that we will build the appropriate built-in
10329 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010330 ExprResult ArgsRes0 =
10331 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10332 Best->Conversions[0], AA_Passing);
10333 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010334 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010335 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010336
John Wiegley429bb272011-04-08 18:41:53 +000010337 ExprResult ArgsRes1 =
10338 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10339 Best->Conversions[1], AA_Passing);
10340 if (ArgsRes1.isInvalid())
10341 return ExprError();
10342 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010343 break;
10344 }
10345 }
10346
Douglas Gregor33074752009-09-30 21:46:01 +000010347 case OR_No_Viable_Function: {
10348 // C++ [over.match.oper]p9:
10349 // If the operator is the operator , [...] and there are no
10350 // viable functions, then the operator is assumed to be the
10351 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010352 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010353 break;
10354
Chandler Carruth6df868e2010-12-12 08:17:55 +000010355 // For class as left operand for assignment or compound assigment
10356 // operator do not fall through to handling in built-in, but report that
10357 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010358 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010359 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010360 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010361 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10362 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010363 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010364 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010365 // This is an erroneous use of an operator which can be overloaded by
10366 // a non-member function. Check for non-member operators which were
10367 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010368 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010369 // FIXME: Recover by calling the found function.
10370 return ExprError();
10371
Douglas Gregor33074752009-09-30 21:46:01 +000010372 // No viable function; try to create a built-in operation, which will
10373 // produce an error. Then, show the non-viable candidates.
10374 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010375 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010376 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010377 "C++ binary operator overloading is missing candidates!");
10378 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010379 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010380 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010381 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010382 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010383
10384 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010385 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010386 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010387 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010388 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010389 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010390 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010391 return ExprError();
10392
10393 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010394 if (isImplicitlyDeleted(Best->Function)) {
10395 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10396 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
Richard Smith0f46e642012-12-28 12:23:24 +000010397 << Context.getRecordType(Method->getParent())
10398 << getSpecialMember(Method);
Richard Smith5bdaac52012-04-02 20:59:25 +000010399
Richard Smith0f46e642012-12-28 12:23:24 +000010400 // The user probably meant to call this special member. Just
10401 // explain why it's deleted.
10402 NoteDeletedFunction(Method);
10403 return ExprError();
Douglas Gregore4e68d42012-02-15 19:33:52 +000010404 } else {
10405 Diag(OpLoc, diag::err_ovl_deleted_oper)
10406 << Best->Function->isDeleted()
10407 << BinaryOperator::getOpcodeStr(Opc)
10408 << getDeletedOrUnavailableSuffix(Best->Function)
10409 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10410 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010411 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010412 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010413 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010414 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010415
Douglas Gregor33074752009-09-30 21:46:01 +000010416 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010417 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010418}
10419
John McCall60d7b3a2010-08-24 06:29:42 +000010420ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010421Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10422 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010423 Expr *Base, Expr *Idx) {
10424 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010425 DeclarationName OpName =
10426 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10427
10428 // If either side is type-dependent, create an appropriate dependent
10429 // expression.
10430 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10431
John McCallc373d482010-01-27 01:50:18 +000010432 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010433 // CHECKME: no 'operator' keyword?
10434 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10435 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010436 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010437 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010438 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010439 /*ADL*/ true, /*Overloaded*/ false,
10440 UnresolvedSetIterator(),
10441 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010442 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010443
Sebastian Redlf322ed62009-10-29 20:17:01 +000010444 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010445 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010446 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010447 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010448 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010449 }
10450
John McCall5acb0c92011-10-17 18:40:02 +000010451 // Handle placeholders on both operands.
10452 if (checkPlaceholderForOverload(*this, Args[0]))
10453 return ExprError();
10454 if (checkPlaceholderForOverload(*this, Args[1]))
10455 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010456
Sebastian Redlf322ed62009-10-29 20:17:01 +000010457 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010458 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010459
10460 // Subscript can only be overloaded as a member function.
10461
10462 // Add operator candidates that are member functions.
10463 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10464
10465 // Add builtin operator candidates.
10466 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10467
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010468 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10469
Sebastian Redlf322ed62009-10-29 20:17:01 +000010470 // Perform overload resolution.
10471 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010472 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010473 case OR_Success: {
10474 // We found a built-in operator or an overloaded operator.
10475 FunctionDecl *FnDecl = Best->Function;
10476
10477 if (FnDecl) {
10478 // We matched an overloaded operator. Build a call to that
10479 // operator.
10480
Eli Friedman5f2987c2012-02-02 03:46:19 +000010481 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010482
John McCall9aa472c2010-03-19 07:35:19 +000010483 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010484 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010485
Sebastian Redlf322ed62009-10-29 20:17:01 +000010486 // Convert the arguments.
10487 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010488 ExprResult Arg0 =
10489 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10490 Best->FoundDecl, Method);
10491 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010492 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010493 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010494
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010495 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010496 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010497 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010498 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010499 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010500 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010501 Owned(Args[1]));
10502 if (InputInit.isInvalid())
10503 return ExprError();
10504
10505 Args[1] = InputInit.takeAs<Expr>();
10506
Sebastian Redlf322ed62009-10-29 20:17:01 +000010507 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010508 QualType ResultTy = FnDecl->getResultType();
10509 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10510 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010511
10512 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010513 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10514 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010515 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10516 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010517 OpLocInfo.getLoc(),
10518 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010519 if (FnExpr.isInvalid())
10520 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010521
John McCall9ae2f072010-08-23 23:25:46 +000010522 CXXOperatorCallExpr *TheCall =
10523 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010524 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010525 ResultTy, VK, RLoc,
10526 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010527
John McCall9ae2f072010-08-23 23:25:46 +000010528 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010529 FnDecl))
10530 return ExprError();
10531
John McCall9ae2f072010-08-23 23:25:46 +000010532 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010533 } else {
10534 // We matched a built-in operator. Convert the arguments, then
10535 // break out so that we will build the appropriate built-in
10536 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010537 ExprResult ArgsRes0 =
10538 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10539 Best->Conversions[0], AA_Passing);
10540 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010541 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010542 Args[0] = ArgsRes0.take();
10543
10544 ExprResult ArgsRes1 =
10545 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10546 Best->Conversions[1], AA_Passing);
10547 if (ArgsRes1.isInvalid())
10548 return ExprError();
10549 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010550
10551 break;
10552 }
10553 }
10554
10555 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010556 if (CandidateSet.empty())
10557 Diag(LLoc, diag::err_ovl_no_oper)
10558 << Args[0]->getType() << /*subscript*/ 0
10559 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10560 else
10561 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10562 << Args[0]->getType()
10563 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010564 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010565 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010566 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010567 }
10568
10569 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010570 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010571 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010572 << Args[0]->getType() << Args[1]->getType()
10573 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010574 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010575 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010576 return ExprError();
10577
10578 case OR_Deleted:
10579 Diag(LLoc, diag::err_ovl_deleted_oper)
10580 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010581 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010582 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010583 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010584 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010585 return ExprError();
10586 }
10587
10588 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010589 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010590}
10591
Douglas Gregor88a35142008-12-22 05:46:06 +000010592/// BuildCallToMemberFunction - Build a call to a member
10593/// function. MemExpr is the expression that refers to the member
10594/// function (and includes the object parameter), Args/NumArgs are the
10595/// arguments to the function call (not including the object
10596/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010597/// expression refers to a non-static member function or an overloaded
10598/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010599ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010600Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10601 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010602 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010603 assert(MemExprE->getType() == Context.BoundMemberTy ||
10604 MemExprE->getType() == Context.OverloadTy);
10605
Douglas Gregor88a35142008-12-22 05:46:06 +000010606 // Dig out the member expression. This holds both the object
10607 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010608 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010609
John McCall864c0412011-04-26 20:42:42 +000010610 // Determine whether this is a call to a pointer-to-member function.
10611 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10612 assert(op->getType() == Context.BoundMemberTy);
10613 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10614
10615 QualType fnType =
10616 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10617
10618 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10619 QualType resultType = proto->getCallResultType(Context);
10620 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10621
10622 // Check that the object type isn't more qualified than the
10623 // member function we're calling.
10624 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10625
10626 QualType objectType = op->getLHS()->getType();
10627 if (op->getOpcode() == BO_PtrMemI)
10628 objectType = objectType->castAs<PointerType>()->getPointeeType();
10629 Qualifiers objectQuals = objectType.getQualifiers();
10630
10631 Qualifiers difference = objectQuals - funcQuals;
10632 difference.removeObjCGCAttr();
10633 difference.removeAddressSpace();
10634 if (difference) {
10635 std::string qualsString = difference.getAsString();
10636 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10637 << fnType.getUnqualifiedType()
10638 << qualsString
10639 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10640 }
10641
10642 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010643 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10644 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010645 resultType, valueKind, RParenLoc);
10646
10647 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010648 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010649 call, 0))
10650 return ExprError();
10651
10652 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10653 return ExprError();
10654
10655 return MaybeBindToTemporary(call);
10656 }
10657
John McCall5acb0c92011-10-17 18:40:02 +000010658 UnbridgedCastsSet UnbridgedCasts;
10659 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10660 return ExprError();
10661
John McCall129e2df2009-11-30 22:42:35 +000010662 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010663 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010664 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010665 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010666 if (isa<MemberExpr>(NakedMemExpr)) {
10667 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010668 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010669 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010670 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010671 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010672 } else {
10673 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010674 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010675
John McCall701c89e2009-12-03 04:06:58 +000010676 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010677 Expr::Classification ObjectClassification
10678 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10679 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010680
Douglas Gregor88a35142008-12-22 05:46:06 +000010681 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010682 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010683
John McCallaa81e162009-12-01 22:10:20 +000010684 // FIXME: avoid copy.
10685 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10686 if (UnresExpr->hasExplicitTemplateArgs()) {
10687 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10688 TemplateArgs = &TemplateArgsBuffer;
10689 }
10690
John McCall129e2df2009-11-30 22:42:35 +000010691 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10692 E = UnresExpr->decls_end(); I != E; ++I) {
10693
John McCall701c89e2009-12-03 04:06:58 +000010694 NamedDecl *Func = *I;
10695 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10696 if (isa<UsingShadowDecl>(Func))
10697 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10698
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010699
Francois Pichetdbee3412011-01-18 05:04:39 +000010700 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010701 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010702 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10703 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010704 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010705 // If explicit template arguments were provided, we can't call a
10706 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010707 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010708 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010709
John McCall9aa472c2010-03-19 07:35:19 +000010710 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010711 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010712 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010713 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010714 } else {
John McCall129e2df2009-11-30 22:42:35 +000010715 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010716 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010717 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010718 llvm::makeArrayRef(Args, NumArgs),
10719 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010720 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010721 }
Douglas Gregordec06662009-08-21 18:42:58 +000010722 }
Mike Stump1eb44332009-09-09 15:08:12 +000010723
John McCall129e2df2009-11-30 22:42:35 +000010724 DeclarationName DeclName = UnresExpr->getMemberName();
10725
John McCall5acb0c92011-10-17 18:40:02 +000010726 UnbridgedCasts.restore();
10727
Douglas Gregor88a35142008-12-22 05:46:06 +000010728 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010729 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010730 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010731 case OR_Success:
10732 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010733 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010734 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010735 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010736 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010737 break;
10738
10739 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010740 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010741 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010742 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010743 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10744 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010745 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010746 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010747
10748 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010749 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010750 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010751 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10752 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010753 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010754 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010755
10756 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010757 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010758 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010759 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010760 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010761 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010762 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10763 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010764 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010765 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010766 }
10767
John McCall6bb80172010-03-30 21:47:33 +000010768 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010769
John McCallaa81e162009-12-01 22:10:20 +000010770 // If overload resolution picked a static member, build a
10771 // non-member call based on that function.
10772 if (Method->isStatic()) {
10773 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10774 Args, NumArgs, RParenLoc);
10775 }
10776
John McCall129e2df2009-11-30 22:42:35 +000010777 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010778 }
10779
John McCallf89e55a2010-11-18 06:31:45 +000010780 QualType ResultType = Method->getResultType();
10781 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10782 ResultType = ResultType.getNonLValueExprType(Context);
10783
Douglas Gregor88a35142008-12-22 05:46:06 +000010784 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010785 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010786 new (Context) CXXMemberCallExpr(Context, MemExprE,
10787 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010788 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010789
Anders Carlssoneed3e692009-10-10 00:06:20 +000010790 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010791 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010792 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010793 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010794
Douglas Gregor88a35142008-12-22 05:46:06 +000010795 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010796 // We only need to do this if there was actually an overload; otherwise
10797 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010798 if (!Method->isStatic()) {
10799 ExprResult ObjectArg =
10800 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10801 FoundDecl, Method);
10802 if (ObjectArg.isInvalid())
10803 return ExprError();
10804 MemExpr->setBase(ObjectArg.take());
10805 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010806
10807 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010808 const FunctionProtoType *Proto =
10809 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010810 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010811 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010812 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010813
Eli Friedmane61eb042012-02-18 04:48:30 +000010814 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10815
Richard Smith831421f2012-06-25 20:30:08 +000010816 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010817 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010818
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010819 if ((isa<CXXConstructorDecl>(CurContext) ||
10820 isa<CXXDestructorDecl>(CurContext)) &&
10821 TheCall->getMethodDecl()->isPure()) {
10822 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10823
Chandler Carruthae198062011-06-27 08:31:58 +000010824 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010825 Diag(MemExpr->getLocStart(),
10826 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10827 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10828 << MD->getParent()->getDeclName();
10829
10830 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010831 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010832 }
John McCall9ae2f072010-08-23 23:25:46 +000010833 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010834}
10835
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010836/// BuildCallToObjectOfClassType - Build a call to an object of class
10837/// type (C++ [over.call.object]), which can end up invoking an
10838/// overloaded function call operator (@c operator()) or performing a
10839/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010840ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010841Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010842 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010843 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010844 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010845 if (checkPlaceholderForOverload(*this, Obj))
10846 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010847 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010848
10849 UnbridgedCastsSet UnbridgedCasts;
10850 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10851 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010852
John Wiegley429bb272011-04-08 18:41:53 +000010853 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10854 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010855
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010856 // C++ [over.call.object]p1:
10857 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010858 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010859 // candidate functions includes at least the function call
10860 // operators of T. The function call operators of T are obtained by
10861 // ordinary lookup of the name operator() in the context of
10862 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010863 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010864 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010865
John Wiegley429bb272011-04-08 18:41:53 +000010866 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010867 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010868 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010869
John McCalla24dc2e2009-11-17 02:14:36 +000010870 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10871 LookupQualifiedName(R, Record->getDecl());
10872 R.suppressDiagnostics();
10873
Douglas Gregor593564b2009-11-15 07:48:03 +000010874 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010875 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010876 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10877 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010878 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010879 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010880
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010881 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010882 // In addition, for each (non-explicit in C++0x) conversion function
10883 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010884 //
10885 // operator conversion-type-id () cv-qualifier;
10886 //
10887 // where cv-qualifier is the same cv-qualification as, or a
10888 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010889 // denotes the type "pointer to function of (P1,...,Pn) returning
10890 // R", or the type "reference to pointer to function of
10891 // (P1,...,Pn) returning R", or the type "reference to function
10892 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010893 // is also considered as a candidate function. Similarly,
10894 // surrogate call functions are added to the set of candidate
10895 // functions for each conversion function declared in an
10896 // accessible base class provided the function is not hidden
10897 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010898 std::pair<CXXRecordDecl::conversion_iterator,
10899 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010900 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010901 for (CXXRecordDecl::conversion_iterator
10902 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010903 NamedDecl *D = *I;
10904 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10905 if (isa<UsingShadowDecl>(D))
10906 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010907
Douglas Gregor4a27d702009-10-21 06:18:39 +000010908 // Skip over templated conversion functions; they aren't
10909 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010910 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010911 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010912
John McCall701c89e2009-12-03 04:06:58 +000010913 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010914 if (!Conv->isExplicit()) {
10915 // Strip the reference type (if any) and then the pointer type (if
10916 // any) to get down to what might be a function type.
10917 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10918 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10919 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010920
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010921 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10922 {
10923 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010924 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10925 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010926 }
10927 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010928 }
Mike Stump1eb44332009-09-09 15:08:12 +000010929
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010930 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10931
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010932 // Perform overload resolution.
10933 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010934 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010935 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010936 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010937 // Overload resolution succeeded; we'll build the appropriate call
10938 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010939 break;
10940
10941 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010942 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010943 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010944 << Object.get()->getType() << /*call*/ 1
10945 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010946 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010947 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010948 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010949 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010950 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10951 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010952 break;
10953
10954 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010955 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010956 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010957 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010958 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10959 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010960 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010961
10962 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010963 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010964 diag::err_ovl_deleted_object_call)
10965 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010966 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010967 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010968 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010969 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10970 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010971 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010972 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010973
Douglas Gregorff331c12010-07-25 18:17:45 +000010974 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010975 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010976
John McCall5acb0c92011-10-17 18:40:02 +000010977 UnbridgedCasts.restore();
10978
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010979 if (Best->Function == 0) {
10980 // Since there is no function declaration, this is one of the
10981 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010982 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010983 = cast<CXXConversionDecl>(
10984 Best->Conversions[0].UserDefined.ConversionFunction);
10985
John Wiegley429bb272011-04-08 18:41:53 +000010986 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010987 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010988
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010989 // We selected one of the surrogate functions that converts the
10990 // object parameter to a function pointer. Perform the conversion
10991 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010992
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010993 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010994 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010995 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10996 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010997 if (Call.isInvalid())
10998 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010999 // Record usage of conversion in an implicit cast.
11000 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
11001 CK_UserDefinedConversion,
11002 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011003
Douglas Gregorf2ae5262011-01-20 00:18:04 +000011004 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011005 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011006 }
11007
Eli Friedman5f2987c2012-02-02 03:46:19 +000011008 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011009 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011010 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011011
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011012 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11013 // that calls this method, using Object for the implicit object
11014 // parameter and passing along the remaining arguments.
11015 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011016
11017 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011018 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011019 return ExprError();
11020
Chandler Carruth6df868e2010-12-12 08:17:55 +000011021 const FunctionProtoType *Proto =
11022 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011023
11024 unsigned NumArgsInProto = Proto->getNumArgs();
11025 unsigned NumArgsToCheck = NumArgs;
11026
11027 // Build the full argument list for the method call (the
11028 // implicit object parameter is placed at the beginning of the
11029 // list).
11030 Expr **MethodArgs;
11031 if (NumArgs < NumArgsInProto) {
11032 NumArgsToCheck = NumArgsInProto;
11033 MethodArgs = new Expr*[NumArgsInProto + 1];
11034 } else {
11035 MethodArgs = new Expr*[NumArgs + 1];
11036 }
John Wiegley429bb272011-04-08 18:41:53 +000011037 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011038 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11039 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011040
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011041 DeclarationNameInfo OpLocInfo(
11042 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11043 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011044 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011045 HadMultipleCandidates,
11046 OpLocInfo.getLoc(),
11047 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011048 if (NewFn.isInvalid())
11049 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011050
11051 // Once we've built TheCall, all of the expressions are properly
11052 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011053 QualType ResultTy = Method->getResultType();
11054 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11055 ResultTy = ResultTy.getNonLValueExprType(Context);
11056
John McCall9ae2f072010-08-23 23:25:46 +000011057 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011058 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011059 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011060 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011061 delete [] MethodArgs;
11062
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011063 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011064 Method))
11065 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011066
Douglas Gregor518fda12009-01-13 05:10:00 +000011067 // We may have default arguments. If so, we need to allocate more
11068 // slots in the call for them.
11069 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011070 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011071 else if (NumArgs > NumArgsInProto)
11072 NumArgsToCheck = NumArgsInProto;
11073
Chris Lattner312531a2009-04-12 08:11:20 +000011074 bool IsError = false;
11075
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011076 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011077 ExprResult ObjRes =
11078 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11079 Best->FoundDecl, Method);
11080 if (ObjRes.isInvalid())
11081 IsError = true;
11082 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011083 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011084 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011085
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011086 // Check the argument types.
11087 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011088 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011089 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011090 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011091
Douglas Gregor518fda12009-01-13 05:10:00 +000011092 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011093
John McCall60d7b3a2010-08-24 06:29:42 +000011094 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011095 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011096 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011097 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011098 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011099
Anders Carlsson3faa4862010-01-29 18:43:53 +000011100 IsError |= InputInit.isInvalid();
11101 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011102 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011103 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011104 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11105 if (DefArg.isInvalid()) {
11106 IsError = true;
11107 break;
11108 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011109
Douglas Gregord47c47d2009-11-09 19:27:57 +000011110 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011111 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011112
11113 TheCall->setArg(i + 1, Arg);
11114 }
11115
11116 // If this is a variadic call, handle args passed through "...".
11117 if (Proto->isVariadic()) {
11118 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011119 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011120 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11121 IsError |= Arg.isInvalid();
11122 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011123 }
11124 }
11125
Chris Lattner312531a2009-04-12 08:11:20 +000011126 if (IsError) return true;
11127
Eli Friedmane61eb042012-02-18 04:48:30 +000011128 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11129
Richard Smith831421f2012-06-25 20:30:08 +000011130 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011131 return true;
11132
John McCall182f7092010-08-24 06:09:16 +000011133 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011134}
11135
Douglas Gregor8ba10742008-11-20 16:27:02 +000011136/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011137/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011138/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011139ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011140Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011141 assert(Base->getType()->isRecordType() &&
11142 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011143
John McCall5acb0c92011-10-17 18:40:02 +000011144 if (checkPlaceholderForOverload(*this, Base))
11145 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011146
John McCall5769d612010-02-08 23:07:23 +000011147 SourceLocation Loc = Base->getExprLoc();
11148
Douglas Gregor8ba10742008-11-20 16:27:02 +000011149 // C++ [over.ref]p1:
11150 //
11151 // [...] An expression x->m is interpreted as (x.operator->())->m
11152 // for a class object x of type T if T::operator->() exists and if
11153 // the operator is selected as the best match function by the
11154 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011155 DeclarationName OpName =
11156 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011157 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011158 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011159
John McCall5769d612010-02-08 23:07:23 +000011160 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011161 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011162 return ExprError();
11163
John McCalla24dc2e2009-11-17 02:14:36 +000011164 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11165 LookupQualifiedName(R, BaseRecord->getDecl());
11166 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011167
11168 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011169 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011170 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11171 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011172 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011173
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011174 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11175
Douglas Gregor8ba10742008-11-20 16:27:02 +000011176 // Perform overload resolution.
11177 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011178 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011179 case OR_Success:
11180 // Overload resolution succeeded; we'll build the call below.
11181 break;
11182
11183 case OR_No_Viable_Function:
11184 if (CandidateSet.empty())
11185 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011186 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011187 else
11188 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011189 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011190 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011191 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011192
11193 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011194 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11195 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011196 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011197 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011198
11199 case OR_Deleted:
11200 Diag(OpLoc, diag::err_ovl_deleted_oper)
11201 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011202 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011203 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011204 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011205 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011206 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011207 }
11208
Eli Friedman5f2987c2012-02-02 03:46:19 +000011209 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011210 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011211 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011212
Douglas Gregor8ba10742008-11-20 16:27:02 +000011213 // Convert the object parameter.
11214 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011215 ExprResult BaseResult =
11216 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11217 Best->FoundDecl, Method);
11218 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011219 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011220 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011221
Douglas Gregor8ba10742008-11-20 16:27:02 +000011222 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011223 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011224 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011225 if (FnExpr.isInvalid())
11226 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011227
John McCallf89e55a2010-11-18 06:31:45 +000011228 QualType ResultTy = Method->getResultType();
11229 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11230 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011231 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011232 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011233 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011234
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011235 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011236 Method))
11237 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011238
11239 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011240}
11241
Richard Smith36f5cfe2012-03-09 08:00:36 +000011242/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11243/// a literal operator described by the provided lookup results.
11244ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11245 DeclarationNameInfo &SuffixInfo,
11246 ArrayRef<Expr*> Args,
11247 SourceLocation LitEndLoc,
11248 TemplateArgumentListInfo *TemplateArgs) {
11249 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011250
Richard Smith36f5cfe2012-03-09 08:00:36 +000011251 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11252 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11253 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011254
Richard Smith36f5cfe2012-03-09 08:00:36 +000011255 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11256
Richard Smith36f5cfe2012-03-09 08:00:36 +000011257 // Perform overload resolution. This will usually be trivial, but might need
11258 // to perform substitutions for a literal operator template.
11259 OverloadCandidateSet::iterator Best;
11260 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11261 case OR_Success:
11262 case OR_Deleted:
11263 break;
11264
11265 case OR_No_Viable_Function:
11266 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11267 << R.getLookupName();
11268 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11269 return ExprError();
11270
11271 case OR_Ambiguous:
11272 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11273 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11274 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011275 }
11276
Richard Smith36f5cfe2012-03-09 08:00:36 +000011277 FunctionDecl *FD = Best->Function;
11278 MarkFunctionReferenced(UDSuffixLoc, FD);
11279 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011280
Richard Smith36f5cfe2012-03-09 08:00:36 +000011281 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11282 SuffixInfo.getLoc(),
11283 SuffixInfo.getInfo());
11284 if (Fn.isInvalid())
11285 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011286
11287 // Check the argument types. This should almost always be a no-op, except
11288 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011289 Expr *ConvArgs[2];
11290 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11291 ExprResult InputInit = PerformCopyInitialization(
11292 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11293 SourceLocation(), Args[ArgIdx]);
11294 if (InputInit.isInvalid())
11295 return true;
11296 ConvArgs[ArgIdx] = InputInit.take();
11297 }
11298
Richard Smith9fcce652012-03-07 08:35:16 +000011299 QualType ResultTy = FD->getResultType();
11300 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11301 ResultTy = ResultTy.getNonLValueExprType(Context);
11302
Richard Smith9fcce652012-03-07 08:35:16 +000011303 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011304 new (Context) UserDefinedLiteral(Context, Fn.take(),
11305 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011306 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11307
11308 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11309 return ExprError();
11310
Richard Smith831421f2012-06-25 20:30:08 +000011311 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011312 return ExprError();
11313
11314 return MaybeBindToTemporary(UDL);
11315}
11316
Sam Panzere1715b62012-08-21 00:52:01 +000011317/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11318/// given LookupResult is non-empty, it is assumed to describe a member which
11319/// will be invoked. Otherwise, the function will be found via argument
11320/// dependent lookup.
11321/// CallExpr is set to a valid expression and FRS_Success returned on success,
11322/// otherwise CallExpr is set to ExprError() and some non-success value
11323/// is returned.
11324Sema::ForRangeStatus
11325Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11326 SourceLocation RangeLoc, VarDecl *Decl,
11327 BeginEndFunction BEF,
11328 const DeclarationNameInfo &NameInfo,
11329 LookupResult &MemberLookup,
11330 OverloadCandidateSet *CandidateSet,
11331 Expr *Range, ExprResult *CallExpr) {
11332 CandidateSet->clear();
11333 if (!MemberLookup.empty()) {
11334 ExprResult MemberRef =
11335 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11336 /*IsPtr=*/false, CXXScopeSpec(),
11337 /*TemplateKWLoc=*/SourceLocation(),
11338 /*FirstQualifierInScope=*/0,
11339 MemberLookup,
11340 /*TemplateArgs=*/0);
11341 if (MemberRef.isInvalid()) {
11342 *CallExpr = ExprError();
11343 Diag(Range->getLocStart(), diag::note_in_for_range)
11344 << RangeLoc << BEF << Range->getType();
11345 return FRS_DiagnosticIssued;
11346 }
11347 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11348 if (CallExpr->isInvalid()) {
11349 *CallExpr = ExprError();
11350 Diag(Range->getLocStart(), diag::note_in_for_range)
11351 << RangeLoc << BEF << Range->getType();
11352 return FRS_DiagnosticIssued;
11353 }
11354 } else {
11355 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011356 UnresolvedLookupExpr *Fn =
11357 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11358 NestedNameSpecifierLoc(), NameInfo,
11359 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011360 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011361
11362 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11363 CandidateSet, CallExpr);
11364 if (CandidateSet->empty() || CandidateSetError) {
11365 *CallExpr = ExprError();
11366 return FRS_NoViableFunction;
11367 }
11368 OverloadCandidateSet::iterator Best;
11369 OverloadingResult OverloadResult =
11370 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11371
11372 if (OverloadResult == OR_No_Viable_Function) {
11373 *CallExpr = ExprError();
11374 return FRS_NoViableFunction;
11375 }
11376 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11377 Loc, 0, CandidateSet, &Best,
11378 OverloadResult,
11379 /*AllowTypoCorrection=*/false);
11380 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11381 *CallExpr = ExprError();
11382 Diag(Range->getLocStart(), diag::note_in_for_range)
11383 << RangeLoc << BEF << Range->getType();
11384 return FRS_DiagnosticIssued;
11385 }
11386 }
11387 return FRS_Success;
11388}
11389
11390
Douglas Gregor904eed32008-11-10 20:40:00 +000011391/// FixOverloadedFunctionReference - E is an expression that refers to
11392/// a C++ overloaded function (possibly with some parentheses and
11393/// perhaps a '&' around it). We have resolved the overloaded function
11394/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011395/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011396Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011397 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011398 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011399 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11400 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011401 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011402 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011403
Douglas Gregor699ee522009-11-20 19:42:02 +000011404 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011405 }
11406
Douglas Gregor699ee522009-11-20 19:42:02 +000011407 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011408 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11409 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011410 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011411 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011412 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011413 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011414 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011415 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011416
11417 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011418 ICE->getCastKind(),
11419 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011420 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011421 }
11422
Douglas Gregor699ee522009-11-20 19:42:02 +000011423 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011424 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011425 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011426 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11427 if (Method->isStatic()) {
11428 // Do nothing: static member functions aren't any different
11429 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011430 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011431 // Fix the sub expression, which really has to be an
11432 // UnresolvedLookupExpr holding an overloaded member function
11433 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011434 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11435 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011436 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011437 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011438
John McCallba135432009-11-21 08:51:07 +000011439 assert(isa<DeclRefExpr>(SubExpr)
11440 && "fixed to something other than a decl ref");
11441 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11442 && "fixed to a member ref with no nested name qualifier");
11443
11444 // We have taken the address of a pointer to member
11445 // function. Perform the computation here so that we get the
11446 // appropriate pointer to member type.
11447 QualType ClassType
11448 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11449 QualType MemPtrType
11450 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11451
John McCallf89e55a2010-11-18 06:31:45 +000011452 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11453 VK_RValue, OK_Ordinary,
11454 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011455 }
11456 }
John McCall6bb80172010-03-30 21:47:33 +000011457 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11458 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011459 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011460 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011461
John McCall2de56d12010-08-25 11:45:40 +000011462 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011463 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011464 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011465 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011466 }
John McCallba135432009-11-21 08:51:07 +000011467
11468 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011469 // FIXME: avoid copy.
11470 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011471 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011472 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11473 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011474 }
11475
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011476 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11477 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011478 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011479 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011480 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011481 ULE->getNameLoc(),
11482 Fn->getType(),
11483 VK_LValue,
11484 Found.getDecl(),
11485 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011486 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011487 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11488 return DRE;
John McCallba135432009-11-21 08:51:07 +000011489 }
11490
John McCall129e2df2009-11-30 22:42:35 +000011491 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011492 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011493 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11494 if (MemExpr->hasExplicitTemplateArgs()) {
11495 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11496 TemplateArgs = &TemplateArgsBuffer;
11497 }
John McCalld5532b62009-11-23 01:53:49 +000011498
John McCallaa81e162009-12-01 22:10:20 +000011499 Expr *Base;
11500
John McCallf89e55a2010-11-18 06:31:45 +000011501 // If we're filling in a static method where we used to have an
11502 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011503 if (MemExpr->isImplicitAccess()) {
11504 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011505 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11506 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011507 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011508 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011509 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011510 MemExpr->getMemberLoc(),
11511 Fn->getType(),
11512 VK_LValue,
11513 Found.getDecl(),
11514 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011515 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011516 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11517 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011518 } else {
11519 SourceLocation Loc = MemExpr->getMemberLoc();
11520 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011521 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011522 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011523 Base = new (Context) CXXThisExpr(Loc,
11524 MemExpr->getBaseType(),
11525 /*isImplicit=*/true);
11526 }
John McCallaa81e162009-12-01 22:10:20 +000011527 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011528 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011529
John McCallf5307512011-04-27 00:36:17 +000011530 ExprValueKind valueKind;
11531 QualType type;
11532 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11533 valueKind = VK_LValue;
11534 type = Fn->getType();
11535 } else {
11536 valueKind = VK_RValue;
11537 type = Context.BoundMemberTy;
11538 }
11539
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011540 MemberExpr *ME = MemberExpr::Create(Context, Base,
11541 MemExpr->isArrow(),
11542 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011543 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011544 Fn,
11545 Found,
11546 MemExpr->getMemberNameInfo(),
11547 TemplateArgs,
11548 type, valueKind, OK_Ordinary);
11549 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011550 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011551 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011552 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011553
John McCall3fa5cae2010-10-26 07:05:15 +000011554 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011555}
11556
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011557ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011558 DeclAccessPair Found,
11559 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011560 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011561}
11562
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011563} // end namespace clang