blob: e5af2b16d70db51744a4c7ab4439832f23070fe1 [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
John McCallad00b772010-06-16 08:42:20 +0000933bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
934 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000935 // If both of the functions are extern "C", then they are not
936 // overloads.
937 if (Old->isExternC() && New->isExternC())
938 return false;
939
John McCall68263142009-11-18 22:49:29 +0000940 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
941 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
942
943 // C++ [temp.fct]p2:
944 // A function template can be overloaded with other function templates
945 // and with normal (non-template) functions.
946 if ((OldTemplate == 0) != (NewTemplate == 0))
947 return true;
948
949 // Is the function New an overload of the function Old?
950 QualType OldQType = Context.getCanonicalType(Old->getType());
951 QualType NewQType = Context.getCanonicalType(New->getType());
952
953 // Compare the signatures (C++ 1.3.10) of the two functions to
954 // determine whether they are overloads. If we find any mismatch
955 // in the signature, they are overloads.
956
957 // If either of these functions is a K&R-style function (no
958 // prototype), then we consider them to have matching signatures.
959 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
960 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
961 return false;
962
John McCallf4c73712011-01-19 06:33:43 +0000963 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
964 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000965
966 // The signature of a function includes the types of its
967 // parameters (C++ 1.3.10), which includes the presence or absence
968 // of the ellipsis; see C++ DR 357).
969 if (OldQType != NewQType &&
970 (OldType->getNumArgs() != NewType->getNumArgs() ||
971 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000972 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000973 return true;
974
975 // C++ [temp.over.link]p4:
976 // The signature of a function template consists of its function
977 // signature, its return type and its template parameter list. The names
978 // of the template parameters are significant only for establishing the
979 // relationship between the template parameters and the rest of the
980 // signature.
981 //
982 // We check the return type and template parameter lists for function
983 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000984 //
985 // However, we don't consider either of these when deciding whether
986 // a member introduced by a shadow declaration is hidden.
987 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000988 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
989 OldTemplate->getTemplateParameters(),
990 false, TPL_TemplateMatch) ||
991 OldType->getResultType() != NewType->getResultType()))
992 return true;
993
994 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000995 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000996 //
997 // As part of this, also check whether one of the member functions
998 // is static, in which case they are not overloads (C++
999 // 13.1p2). While not part of the definition of the signature,
1000 // this check is important to determine whether these functions
1001 // can be overloaded.
1002 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
1003 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
1004 if (OldMethod && NewMethod &&
1005 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +00001006 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +00001007 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
1008 if (!UseUsingDeclRules &&
1009 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
1010 (OldMethod->getRefQualifier() == RQ_None ||
1011 NewMethod->getRefQualifier() == RQ_None)) {
1012 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001013 // - Member function declarations with the same name and the same
1014 // parameter-type-list as well as member function template
1015 // declarations with the same name, the same parameter-type-list, and
1016 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +00001017 // them, but not all, have a ref-qualifier (8.3.5).
1018 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
1019 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
1020 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
1021 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001022
John McCall68263142009-11-18 22:49:29 +00001023 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +00001024 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001025
John McCall68263142009-11-18 22:49:29 +00001026 // The signatures match; this is not an overload.
1027 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028}
1029
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00001030/// \brief Checks availability of the function depending on the current
1031/// function context. Inside an unavailable function, unavailability is ignored.
1032///
1033/// \returns true if \arg FD is unavailable and current context is inside
1034/// an available function, false otherwise.
1035bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
1036 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
1037}
1038
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001039/// \brief Tries a user-defined conversion from From to ToType.
1040///
1041/// Produces an implicit conversion sequence for when a standard conversion
1042/// is not an option. See TryImplicitConversion for more information.
1043static ImplicitConversionSequence
1044TryUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1045 bool SuppressUserConversions,
1046 bool AllowExplicit,
1047 bool InOverloadResolution,
1048 bool CStyle,
1049 bool AllowObjCWritebackConversion) {
1050 ImplicitConversionSequence ICS;
1051
1052 if (SuppressUserConversions) {
1053 // We're not in the case above, so there is no conversion that
1054 // we can perform.
1055 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1056 return ICS;
1057 }
1058
1059 // Attempt user-defined conversion.
1060 OverloadCandidateSet Conversions(From->getExprLoc());
1061 OverloadingResult UserDefResult
1062 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
1063 AllowExplicit);
1064
1065 if (UserDefResult == OR_Success) {
1066 ICS.setUserDefined();
1067 // C++ [over.ics.user]p4:
1068 // A conversion of an expression of class type to the same class
1069 // type is given Exact Match rank, and a conversion of an
1070 // expression of class type to a base class of that type is
1071 // given Conversion rank, in spite of the fact that a copy
1072 // constructor (i.e., a user-defined conversion function) is
1073 // called for those cases.
1074 if (CXXConstructorDecl *Constructor
1075 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
1076 QualType FromCanon
1077 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
1078 QualType ToCanon
1079 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
1080 if (Constructor->isCopyConstructor() &&
1081 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
1082 // Turn this into a "standard" conversion sequence, so that it
1083 // gets ranked with standard conversion sequences.
1084 ICS.setStandard();
1085 ICS.Standard.setAsIdentityConversion();
1086 ICS.Standard.setFromType(From->getType());
1087 ICS.Standard.setAllToTypes(ToType);
1088 ICS.Standard.CopyConstructor = Constructor;
1089 if (ToCanon != FromCanon)
1090 ICS.Standard.Second = ICK_Derived_To_Base;
1091 }
1092 }
1093
1094 // C++ [over.best.ics]p4:
1095 // However, when considering the argument of a user-defined
1096 // conversion function that is a candidate by 13.3.1.3 when
1097 // invoked for the copying of the temporary in the second step
1098 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
1099 // 13.3.1.6 in all cases, only standard conversion sequences and
1100 // ellipsis conversion sequences are allowed.
1101 if (SuppressUserConversions && ICS.isUserDefined()) {
1102 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
1103 }
1104 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
1105 ICS.setAmbiguous();
1106 ICS.Ambiguous.setFromType(From->getType());
1107 ICS.Ambiguous.setToType(ToType);
1108 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
1109 Cand != Conversions.end(); ++Cand)
1110 if (Cand->Viable)
1111 ICS.Ambiguous.addConversion(Cand->Function);
1112 } else {
1113 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
1114 }
1115
1116 return ICS;
1117}
1118
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001119/// TryImplicitConversion - Attempt to perform an implicit conversion
1120/// from the given expression (Expr) to the given type (ToType). This
1121/// function returns an implicit conversion sequence that can be used
1122/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001123///
1124/// void f(float f);
1125/// void g(int i) { f(i); }
1126///
1127/// this routine would produce an implicit conversion sequence to
1128/// describe the initialization of f from i, which will be a standard
1129/// conversion sequence containing an lvalue-to-rvalue conversion (C++
1130/// 4.1) followed by a floating-integral conversion (C++ 4.9).
1131//
1132/// Note that this routine only determines how the conversion can be
1133/// performed; it does not actually perform the conversion. As such,
1134/// it will not produce any diagnostics if no conversion is available,
1135/// but will instead return an implicit conversion sequence of kind
1136/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +00001137///
1138/// If @p SuppressUserConversions, then user-defined conversions are
1139/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001140/// If @p AllowExplicit, then explicit user-defined conversions are
1141/// permitted.
John McCallf85e1932011-06-15 23:02:42 +00001142///
1143/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
1144/// writeback conversion, which allows __autoreleasing id* parameters to
1145/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +00001146static ImplicitConversionSequence
1147TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
1148 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001149 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001150 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001151 bool CStyle,
1152 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001153 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +00001154 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00001155 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +00001156 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +00001157 return ICS;
1158 }
1159
David Blaikie4e4d0842012-03-11 07:00:24 +00001160 if (!S.getLangOpts().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +00001161 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +00001162 return ICS;
1163 }
1164
Douglas Gregor604eb652010-08-11 02:15:33 +00001165 // C++ [over.ics.user]p4:
1166 // A conversion of an expression of class type to the same class
1167 // type is given Exact Match rank, and a conversion of an
1168 // expression of class type to a base class of that type is
1169 // given Conversion rank, in spite of the fact that a copy/move
1170 // constructor (i.e., a user-defined conversion function) is
1171 // called for those cases.
1172 QualType FromType = From->getType();
1173 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001174 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
1175 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001176 ICS.setStandard();
1177 ICS.Standard.setAsIdentityConversion();
1178 ICS.Standard.setFromType(FromType);
1179 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001180
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001181 // We don't actually check at this point whether there is a valid
1182 // copy/move constructor, since overloading just assumes that it
1183 // exists. When we actually perform initialization, we'll find the
1184 // appropriate constructor to copy the returned object, if needed.
1185 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001186
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001187 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +00001188 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001189 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001190
Douglas Gregor604eb652010-08-11 02:15:33 +00001191 return ICS;
1192 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001193
Sebastian Redlcf15cef2011-12-22 18:58:38 +00001194 return TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
1195 AllowExplicit, InOverloadResolution, CStyle,
1196 AllowObjCWritebackConversion);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001197}
1198
John McCallf85e1932011-06-15 23:02:42 +00001199ImplicitConversionSequence
1200Sema::TryImplicitConversion(Expr *From, QualType ToType,
1201 bool SuppressUserConversions,
1202 bool AllowExplicit,
1203 bool InOverloadResolution,
1204 bool CStyle,
1205 bool AllowObjCWritebackConversion) {
1206 return clang::TryImplicitConversion(*this, From, ToType,
1207 SuppressUserConversions, AllowExplicit,
1208 InOverloadResolution, CStyle,
1209 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +00001210}
1211
Douglas Gregor575c63a2010-04-16 22:27:05 +00001212/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +00001213/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +00001214/// converted expression. Flavor is the kind of conversion we're
1215/// performing, used in the error message. If @p AllowExplicit,
1216/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +00001217ExprResult
1218Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001219 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +00001220 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +00001221 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001222}
1223
John Wiegley429bb272011-04-08 18:41:53 +00001224ExprResult
1225Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +00001226 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +00001227 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +00001228 if (checkPlaceholderForOverload(*this, From))
1229 return ExprError();
1230
John McCallf85e1932011-06-15 23:02:42 +00001231 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1232 bool AllowObjCWritebackConversion
David Blaikie4e4d0842012-03-11 07:00:24 +00001233 = getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001234 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001235
John McCall120d63c2010-08-24 20:38:10 +00001236 ICS = clang::TryImplicitConversion(*this, From, ToType,
1237 /*SuppressUserConversions=*/false,
1238 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001239 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001240 /*CStyle=*/false,
1241 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001242 return PerformImplicitConversion(From, ToType, ICS, Action);
1243}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001244
1245/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001246/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001247bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1248 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001249 if (Context.hasSameUnqualifiedType(FromType, ToType))
1250 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001251
John McCall00ccbef2010-12-21 00:44:39 +00001252 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1253 // where F adds one of the following at most once:
1254 // - a pointer
1255 // - a member pointer
1256 // - a block pointer
1257 CanQualType CanTo = Context.getCanonicalType(ToType);
1258 CanQualType CanFrom = Context.getCanonicalType(FromType);
1259 Type::TypeClass TyClass = CanTo->getTypeClass();
1260 if (TyClass != CanFrom->getTypeClass()) return false;
1261 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1262 if (TyClass == Type::Pointer) {
1263 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1264 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1265 } else if (TyClass == Type::BlockPointer) {
1266 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1267 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1268 } else if (TyClass == Type::MemberPointer) {
1269 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1270 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1271 } else {
1272 return false;
1273 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001274
John McCall00ccbef2010-12-21 00:44:39 +00001275 TyClass = CanTo->getTypeClass();
1276 if (TyClass != CanFrom->getTypeClass()) return false;
1277 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1278 return false;
1279 }
1280
1281 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1282 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1283 if (!EInfo.getNoReturn()) return false;
1284
1285 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1286 assert(QualType(FromFn, 0).isCanonical());
1287 if (QualType(FromFn, 0) != CanTo) return false;
1288
1289 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001290 return true;
1291}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001292
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001293/// \brief Determine whether the conversion from FromType to ToType is a valid
1294/// vector conversion.
1295///
1296/// \param ICK Will be set to the vector conversion kind, if this is a vector
1297/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001298static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1299 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001300 // We need at least one of these types to be a vector type to have a vector
1301 // conversion.
1302 if (!ToType->isVectorType() && !FromType->isVectorType())
1303 return false;
1304
1305 // Identical types require no conversions.
1306 if (Context.hasSameUnqualifiedType(FromType, ToType))
1307 return false;
1308
1309 // There are no conversions between extended vector types, only identity.
1310 if (ToType->isExtVectorType()) {
1311 // There are no conversions between extended vector types other than the
1312 // identity conversion.
1313 if (FromType->isExtVectorType())
1314 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001315
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001316 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001317 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001318 ICK = ICK_Vector_Splat;
1319 return true;
1320 }
1321 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001322
1323 // We can perform the conversion between vector types in the following cases:
1324 // 1)vector types are equivalent AltiVec and GCC vector types
1325 // 2)lax vector conversions are permitted and the vector types are of the
1326 // same size
1327 if (ToType->isVectorType() && FromType->isVectorType()) {
1328 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
David Blaikie4e4d0842012-03-11 07:00:24 +00001329 (Context.getLangOpts().LaxVectorConversions &&
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001330 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001331 ICK = ICK_Vector_Conversion;
1332 return true;
1333 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001334 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001335
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001336 return false;
1337}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001338
Douglas Gregor7d000652012-04-12 20:48:09 +00001339static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
1340 bool InOverloadResolution,
1341 StandardConversionSequence &SCS,
1342 bool CStyle);
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001343
Douglas Gregor60d62c22008-10-31 16:23:19 +00001344/// IsStandardConversion - Determines whether there is a standard
1345/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1346/// expression From to the type ToType. Standard conversion sequences
1347/// only consider non-class types; for conversions that involve class
1348/// types, use TryImplicitConversion. If a conversion exists, SCS will
1349/// contain the standard conversion sequence required to perform this
1350/// conversion and this routine will return true. Otherwise, this
1351/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001352static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1353 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001354 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001355 bool CStyle,
1356 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001357 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001358
Douglas Gregor60d62c22008-10-31 16:23:19 +00001359 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001360 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001361 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001362 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001363 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001364 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001365
Douglas Gregorf9201e02009-02-11 23:02:49 +00001366 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001367 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001368 if (FromType->isRecordType() || ToType->isRecordType()) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001369 if (S.getLangOpts().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001370 return false;
1371
Mike Stump1eb44332009-09-09 15:08:12 +00001372 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001373 }
1374
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001375 // The first conversion can be an lvalue-to-rvalue conversion,
1376 // array-to-pointer conversion, or function-to-pointer conversion
1377 // (C++ 4p1).
1378
John McCall120d63c2010-08-24 20:38:10 +00001379 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001380 DeclAccessPair AccessPair;
1381 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001382 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001383 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001384 // We were able to resolve the address of the overloaded function,
1385 // so we can convert to the type of that function.
1386 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001387
1388 // we can sometimes resolve &foo<int> regardless of ToType, so check
1389 // if the type matches (identity) or we are converting to bool
1390 if (!S.Context.hasSameUnqualifiedType(
1391 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1392 QualType resultTy;
1393 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001394 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001395 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1396 // otherwise, only a boolean conversion is standard
1397 if (!ToType->isBooleanType())
1398 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001399 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001400
Chandler Carruth90434232011-03-29 08:08:18 +00001401 // Check if the "from" expression is taking the address of an overloaded
1402 // function and recompute the FromType accordingly. Take advantage of the
1403 // fact that non-static member functions *must* have such an address-of
1404 // expression.
1405 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1406 if (Method && !Method->isStatic()) {
1407 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1408 "Non-unary operator on non-static member address");
1409 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1410 == UO_AddrOf &&
1411 "Non-address-of operator on non-static member address");
1412 const Type *ClassType
1413 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1414 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001415 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1416 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1417 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001418 "Non-address-of operator for overloaded function expression");
1419 FromType = S.Context.getPointerType(FromType);
1420 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001421
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001422 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001423 assert(S.Context.hasSameType(
1424 FromType,
1425 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001426 } else {
1427 return false;
1428 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001429 }
John McCall21480112011-08-30 00:57:29 +00001430 // Lvalue-to-rvalue conversion (C++11 4.1):
1431 // A glvalue (3.10) of a non-function, non-array type T can
1432 // be converted to a prvalue.
1433 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001434 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001435 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001436 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001437 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001438
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001439 // C11 6.3.2.1p2:
1440 // ... if the lvalue has atomic type, the value has the non-atomic version
1441 // of the type of the lvalue ...
1442 if (const AtomicType *Atomic = FromType->getAs<AtomicType>())
1443 FromType = Atomic->getValueType();
1444
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001445 // If T is a non-class type, the type of the rvalue is the
1446 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001447 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1448 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001449 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001450 } else if (FromType->isArrayType()) {
1451 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001452 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001453
1454 // An lvalue or rvalue of type "array of N T" or "array of unknown
1455 // bound of T" can be converted to an rvalue of type "pointer to
1456 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001457 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001458
John McCall120d63c2010-08-24 20:38:10 +00001459 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001460 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001461 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001462
1463 // For the purpose of ranking in overload resolution
1464 // (13.3.3.1.1), this conversion is considered an
1465 // array-to-pointer conversion followed by a qualification
1466 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001467 SCS.Second = ICK_Identity;
1468 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001469 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001470 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001471 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001472 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001473 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001474 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001475 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001476
1477 // An lvalue of function type T can be converted to an rvalue of
1478 // type "pointer to T." The result is a pointer to the
1479 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001480 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001481 } else {
1482 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001483 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001484 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001485 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001486
1487 // The second conversion can be an integral promotion, floating
1488 // point promotion, integral conversion, floating point conversion,
1489 // floating-integral conversion, pointer conversion,
1490 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001491 // For overloading in C, this can also be a "compatible-type"
1492 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001493 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001494 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001495 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001496 // The unqualified versions of the types are the same: there's no
1497 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001498 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001499 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001500 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001501 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001502 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001503 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001504 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001505 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001506 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001507 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001508 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001509 SCS.Second = ICK_Complex_Promotion;
1510 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001511 } else if (ToType->isBooleanType() &&
1512 (FromType->isArithmeticType() ||
1513 FromType->isAnyPointerType() ||
1514 FromType->isBlockPointerType() ||
1515 FromType->isMemberPointerType() ||
1516 FromType->isNullPtrType())) {
1517 // Boolean conversions (C++ 4.12).
1518 SCS.Second = ICK_Boolean_Conversion;
1519 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001520 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001521 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001522 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001523 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001524 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001525 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001526 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001527 SCS.Second = ICK_Complex_Conversion;
1528 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001529 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1530 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001531 // Complex-real conversions (C99 6.3.1.7)
1532 SCS.Second = ICK_Complex_Real;
1533 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001534 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001535 // Floating point conversions (C++ 4.8).
1536 SCS.Second = ICK_Floating_Conversion;
1537 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001538 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001539 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001540 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001541 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001542 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001543 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001544 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001545 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001546 SCS.Second = ICK_Block_Pointer_Conversion;
1547 } else if (AllowObjCWritebackConversion &&
1548 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1549 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001550 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1551 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001552 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001553 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001554 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001555 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001556 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001557 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001558 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001559 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001560 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001561 SCS.Second = SecondICK;
1562 FromType = ToType.getUnqualifiedType();
David Blaikie4e4d0842012-03-11 07:00:24 +00001563 } else if (!S.getLangOpts().CPlusPlus &&
John McCall120d63c2010-08-24 20:38:10 +00001564 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001565 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001566 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001567 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001568 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001569 // Treat a conversion that strips "noreturn" as an identity conversion.
1570 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001571 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1572 InOverloadResolution,
1573 SCS, CStyle)) {
1574 SCS.Second = ICK_TransparentUnionConversion;
1575 FromType = ToType;
Douglas Gregor7d000652012-04-12 20:48:09 +00001576 } else if (tryAtomicConversion(S, From, ToType, InOverloadResolution, SCS,
1577 CStyle)) {
1578 // tryAtomicConversion has updated the standard conversion sequence
Douglas Gregorf7ecc302012-04-12 17:51:55 +00001579 // appropriately.
1580 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001581 } else {
1582 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001583 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001584 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001585 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001586
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001587 QualType CanonFrom;
1588 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001589 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001590 bool ObjCLifetimeConversion;
1591 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1592 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001593 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001594 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001595 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001596 CanonFrom = S.Context.getCanonicalType(FromType);
1597 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001598 } else {
1599 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001600 SCS.Third = ICK_Identity;
1601
Mike Stump1eb44332009-09-09 15:08:12 +00001602 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001603 // [...] Any difference in top-level cv-qualification is
1604 // subsumed by the initialization itself and does not constitute
1605 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001606 CanonFrom = S.Context.getCanonicalType(FromType);
1607 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001608 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001609 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001610 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001611 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1612 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001613 FromType = ToType;
1614 CanonFrom = CanonTo;
1615 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001616 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001617 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001618
1619 // If we have not converted the argument type to the parameter type,
1620 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001621 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001622 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001623
Douglas Gregor60d62c22008-10-31 16:23:19 +00001624 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001625}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001626
1627static bool
1628IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1629 QualType &ToType,
1630 bool InOverloadResolution,
1631 StandardConversionSequence &SCS,
1632 bool CStyle) {
1633
1634 const RecordType *UT = ToType->getAsUnionType();
1635 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1636 return false;
1637 // The field to initialize within the transparent union.
1638 RecordDecl *UD = UT->getDecl();
1639 // It's compatible if the expression matches any of the fields.
1640 for (RecordDecl::field_iterator it = UD->field_begin(),
1641 itend = UD->field_end();
1642 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001643 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1644 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001645 ToType = it->getType();
1646 return true;
1647 }
1648 }
1649 return false;
1650}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001651
1652/// IsIntegralPromotion - Determines whether the conversion from the
1653/// expression From (whose potentially-adjusted type is FromType) to
1654/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1655/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001656bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001657 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001658 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001659 if (!To) {
1660 return false;
1661 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001662
1663 // An rvalue of type char, signed char, unsigned char, short int, or
1664 // unsigned short int can be converted to an rvalue of type int if
1665 // int can represent all the values of the source type; otherwise,
1666 // the source rvalue can be converted to an rvalue of type unsigned
1667 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001668 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1669 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001670 if (// We can promote any signed, promotable integer type to an int
1671 (FromType->isSignedIntegerType() ||
1672 // We can promote any unsigned integer type whose size is
1673 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001674 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001675 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001676 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001677 }
1678
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001679 return To->getKind() == BuiltinType::UInt;
1680 }
1681
Richard Smithe7ff9192012-09-13 21:18:54 +00001682 // C++11 [conv.prom]p3:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001683 // A prvalue of an unscoped enumeration type whose underlying type is not
1684 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1685 // following types that can represent all the values of the enumeration
1686 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1687 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001688 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001689 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001690 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001691 // with lowest integer conversion rank (4.13) greater than the rank of long
1692 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001693 // there are two such extended types, the signed one is chosen.
Richard Smithe7ff9192012-09-13 21:18:54 +00001694 // C++11 [conv.prom]p4:
1695 // A prvalue of an unscoped enumeration type whose underlying type is fixed
1696 // can be converted to a prvalue of its underlying type. Moreover, if
1697 // integral promotion can be applied to its underlying type, a prvalue of an
1698 // unscoped enumeration type whose underlying type is fixed can also be
1699 // converted to a prvalue of the promoted underlying type.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001700 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1701 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1702 // provided for a scoped enumeration.
1703 if (FromEnumType->getDecl()->isScoped())
1704 return false;
1705
Richard Smithe7ff9192012-09-13 21:18:54 +00001706 // We can perform an integral promotion to the underlying type of the enum,
1707 // even if that's not the promoted type.
1708 if (FromEnumType->getDecl()->isFixed()) {
1709 QualType Underlying = FromEnumType->getDecl()->getIntegerType();
1710 return Context.hasSameUnqualifiedType(Underlying, ToType) ||
1711 IsIntegralPromotion(From, Underlying, ToType);
1712 }
1713
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001714 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001715 if (ToType->isIntegerType() &&
Douglas Gregord10099e2012-05-04 16:32:21 +00001716 !RequireCompleteType(From->getLocStart(), FromType, 0))
John McCall842aef82009-12-09 09:09:27 +00001717 return Context.hasSameUnqualifiedType(ToType,
1718 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001719 }
John McCall842aef82009-12-09 09:09:27 +00001720
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001721 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001722 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1723 // to an rvalue a prvalue of the first of the following types that can
1724 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001725 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001726 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001727 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001728 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001729 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001730 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001731 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001732 // Determine whether the type we're converting from is signed or
1733 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001734 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001735 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001736
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001737 // The types we'll try to promote to, in the appropriate
1738 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001739 QualType PromoteTypes[6] = {
1740 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001741 Context.LongTy, Context.UnsignedLongTy ,
1742 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001743 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001744 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001745 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1746 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001747 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001748 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1749 // We found the type that we can promote to. If this is the
1750 // type we wanted, we have a promotion. Otherwise, no
1751 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001752 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001753 }
1754 }
1755 }
1756
1757 // An rvalue for an integral bit-field (9.6) can be converted to an
1758 // rvalue of type int if int can represent all the values of the
1759 // bit-field; otherwise, it can be converted to unsigned int if
1760 // unsigned int can represent all the values of the bit-field. If
1761 // the bit-field is larger yet, no integral promotion applies to
1762 // it. If the bit-field has an enumerated type, it is treated as any
1763 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001764 // FIXME: We should delay checking of bit-fields until we actually perform the
1765 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001766 using llvm::APSInt;
1767 if (From)
1768 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001769 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001770 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001771 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1772 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1773 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Douglas Gregor86f19402008-12-20 23:49:58 +00001775 // Are we promoting to an int from a bitfield that fits in an int?
1776 if (BitWidth < ToSize ||
1777 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1778 return To->getKind() == BuiltinType::Int;
1779 }
Mike Stump1eb44332009-09-09 15:08:12 +00001780
Douglas Gregor86f19402008-12-20 23:49:58 +00001781 // Are we promoting to an unsigned int from an unsigned bitfield
1782 // that fits into an unsigned int?
1783 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1784 return To->getKind() == BuiltinType::UInt;
1785 }
Mike Stump1eb44332009-09-09 15:08:12 +00001786
Douglas Gregor86f19402008-12-20 23:49:58 +00001787 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001788 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001789 }
Mike Stump1eb44332009-09-09 15:08:12 +00001790
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001791 // An rvalue of type bool can be converted to an rvalue of type int,
1792 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001793 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001794 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001795 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001796
1797 return false;
1798}
1799
1800/// IsFloatingPointPromotion - Determines whether the conversion from
1801/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1802/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001803bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001804 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1805 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001806 /// An rvalue of type float can be converted to an rvalue of type
1807 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001808 if (FromBuiltin->getKind() == BuiltinType::Float &&
1809 ToBuiltin->getKind() == BuiltinType::Double)
1810 return true;
1811
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001812 // C99 6.3.1.5p1:
1813 // When a float is promoted to double or long double, or a
1814 // double is promoted to long double [...].
David Blaikie4e4d0842012-03-11 07:00:24 +00001815 if (!getLangOpts().CPlusPlus &&
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001816 (FromBuiltin->getKind() == BuiltinType::Float ||
1817 FromBuiltin->getKind() == BuiltinType::Double) &&
1818 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1819 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001820
1821 // Half can be promoted to float.
1822 if (FromBuiltin->getKind() == BuiltinType::Half &&
1823 ToBuiltin->getKind() == BuiltinType::Float)
1824 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001825 }
1826
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001827 return false;
1828}
1829
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001830/// \brief Determine if a conversion is a complex promotion.
1831///
1832/// A complex promotion is defined as a complex -> complex conversion
1833/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001834/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001835bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001836 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001837 if (!FromComplex)
1838 return false;
1839
John McCall183700f2009-09-21 23:43:11 +00001840 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001841 if (!ToComplex)
1842 return false;
1843
1844 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001845 ToComplex->getElementType()) ||
1846 IsIntegralPromotion(0, FromComplex->getElementType(),
1847 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001848}
1849
Douglas Gregorcb7de522008-11-26 23:31:11 +00001850/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1851/// the pointer type FromPtr to a pointer to type ToPointee, with the
1852/// same type qualifiers as FromPtr has on its pointee type. ToType,
1853/// if non-empty, will be a pointer to ToType that may or may not have
1854/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001855///
Mike Stump1eb44332009-09-09 15:08:12 +00001856static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001857BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001858 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001859 ASTContext &Context,
1860 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001861 assert((FromPtr->getTypeClass() == Type::Pointer ||
1862 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1863 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001864
John McCallf85e1932011-06-15 23:02:42 +00001865 /// Conversions to 'id' subsume cv-qualifier conversions.
1866 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001867 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001868
1869 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001870 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001871 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001872 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001873
John McCallf85e1932011-06-15 23:02:42 +00001874 if (StripObjCLifetime)
1875 Quals.removeObjCLifetime();
1876
Mike Stump1eb44332009-09-09 15:08:12 +00001877 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001878 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001879 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001880 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001881 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001882
1883 // Build a pointer to ToPointee. It has the right qualifiers
1884 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001885 if (isa<ObjCObjectPointerType>(ToType))
1886 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001887 return Context.getPointerType(ToPointee);
1888 }
1889
1890 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001891 QualType QualifiedCanonToPointee
1892 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001893
Douglas Gregorda80f742010-12-01 21:43:58 +00001894 if (isa<ObjCObjectPointerType>(ToType))
1895 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1896 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001897}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001898
Mike Stump1eb44332009-09-09 15:08:12 +00001899static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001900 bool InOverloadResolution,
1901 ASTContext &Context) {
1902 // Handle value-dependent integral null pointer constants correctly.
1903 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1904 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001905 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001906 return !InOverloadResolution;
1907
Douglas Gregorce940492009-09-25 04:25:58 +00001908 return Expr->isNullPointerConstant(Context,
1909 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1910 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001911}
Mike Stump1eb44332009-09-09 15:08:12 +00001912
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001913/// IsPointerConversion - Determines whether the conversion of the
1914/// expression From, which has the (possibly adjusted) type FromType,
1915/// can be converted to the type ToType via a pointer conversion (C++
1916/// 4.10). If so, returns true and places the converted type (that
1917/// might differ from ToType in its cv-qualifiers at some level) into
1918/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001919///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001920/// This routine also supports conversions to and from block pointers
1921/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1922/// pointers to interfaces. FIXME: Once we've determined the
1923/// appropriate overloading rules for Objective-C, we may want to
1924/// split the Objective-C checks into a different routine; however,
1925/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001926/// conversions, so for now they live here. IncompatibleObjC will be
1927/// set if the conversion is an allowed Objective-C conversion that
1928/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001929bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001930 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001931 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001932 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001933 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001934 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1935 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001936 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001937
Mike Stump1eb44332009-09-09 15:08:12 +00001938 // Conversion from a null pointer constant to any Objective-C pointer type.
1939 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001940 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001941 ConvertedType = ToType;
1942 return true;
1943 }
1944
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001945 // Blocks: Block pointers can be converted to void*.
1946 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001947 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001948 ConvertedType = ToType;
1949 return true;
1950 }
1951 // Blocks: A null pointer constant can be converted to a block
1952 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001953 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001954 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001955 ConvertedType = ToType;
1956 return true;
1957 }
1958
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001959 // If the left-hand-side is nullptr_t, the right side can be a null
1960 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001961 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001962 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001963 ConvertedType = ToType;
1964 return true;
1965 }
1966
Ted Kremenek6217b802009-07-29 21:53:49 +00001967 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001968 if (!ToTypePtr)
1969 return false;
1970
1971 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001972 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001973 ConvertedType = ToType;
1974 return true;
1975 }
Sebastian Redl07779722008-10-31 14:43:28 +00001976
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001977 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001978 // , including objective-c pointers.
1979 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001980 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
David Blaikie4e4d0842012-03-11 07:00:24 +00001981 !getLangOpts().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001982 ConvertedType = BuildSimilarlyQualifiedPointerType(
1983 FromType->getAs<ObjCObjectPointerType>(),
1984 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001985 ToType, Context);
1986 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001987 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001988 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001989 if (!FromTypePtr)
1990 return false;
1991
1992 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001993
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001994 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001995 // pointer conversion, so don't do all of the work below.
1996 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1997 return false;
1998
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001999 // An rvalue of type "pointer to cv T," where T is an object type,
2000 // can be converted to an rvalue of type "pointer to cv void" (C++
2001 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00002002 if (FromPointeeType->isIncompleteOrObjectType() &&
2003 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002005 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00002006 ToType, Context,
2007 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002008 return true;
2009 }
2010
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002011 // MSVC allows implicit function to void* type conversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002012 if (getLangOpts().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00002013 ToPointeeType->isVoidType()) {
2014 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2015 ToPointeeType,
2016 ToType, Context);
2017 return true;
2018 }
2019
Douglas Gregorf9201e02009-02-11 23:02:49 +00002020 // When we're overloading in C, we allow a special kind of pointer
2021 // conversion for compatible-but-not-identical pointee types.
David Blaikie4e4d0842012-03-11 07:00:24 +00002022 if (!getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002023 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002024 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00002025 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00002026 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00002027 return true;
2028 }
2029
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002030 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00002031 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002032 // An rvalue of type "pointer to cv D," where D is a class type,
2033 // can be converted to an rvalue of type "pointer to cv B," where
2034 // B is a base class (clause 10) of D. If B is an inaccessible
2035 // (clause 11) or ambiguous (10.2) base class of D, a program that
2036 // necessitates this conversion is ill-formed. The result of the
2037 // conversion is a pointer to the base class sub-object of the
2038 // derived class object. The null pointer value is converted to
2039 // the null pointer value of the destination type.
2040 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002041 // Note that we do not check for ambiguity or inaccessibility
2042 // here. That is handled by CheckPointerConversion.
David Blaikie4e4d0842012-03-11 07:00:24 +00002043 if (getLangOpts().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00002044 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00002045 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002046 !RequireCompleteType(From->getLocStart(), FromPointeeType, 0) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00002047 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002048 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00002049 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002050 ToType, Context);
2051 return true;
2052 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002053
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00002054 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
2055 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
2056 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
2057 ToPointeeType,
2058 ToType, Context);
2059 return true;
2060 }
2061
Douglas Gregorc7887512008-12-19 19:13:09 +00002062 return false;
2063}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002064
2065/// \brief Adopt the given qualifiers for the given type.
2066static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
2067 Qualifiers TQs = T.getQualifiers();
2068
2069 // Check whether qualifiers already match.
2070 if (TQs == Qs)
2071 return T;
2072
2073 if (Qs.compatiblyIncludes(TQs))
2074 return Context.getQualifiedType(T, Qs);
2075
2076 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
2077}
Douglas Gregorc7887512008-12-19 19:13:09 +00002078
2079/// isObjCPointerConversion - Determines whether this is an
2080/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
2081/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00002082bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00002083 QualType& ConvertedType,
2084 bool &IncompatibleObjC) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002085 if (!getLangOpts().ObjC1)
Douglas Gregorc7887512008-12-19 19:13:09 +00002086 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002087
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002088 // The set of qualifiers on the type we're converting from.
2089 Qualifiers FromQualifiers = FromType.getQualifiers();
2090
Steve Naroff14108da2009-07-10 23:34:53 +00002091 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00002092 const ObjCObjectPointerType* ToObjCPtr =
2093 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002094 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00002095 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002096
Steve Naroff14108da2009-07-10 23:34:53 +00002097 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00002098 // If the pointee types are the same (ignoring qualifications),
2099 // then this is not a pointer conversion.
2100 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
2101 FromObjCPtr->getPointeeType()))
2102 return false;
2103
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002104 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00002105 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00002106 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00002107 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002108 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002109 return true;
2110 }
2111 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00002112 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00002113 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00002114 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00002115 /*compare=*/false)) {
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 // Objective C++: We're able to convert from a pointer to an
2120 // interface to a pointer to a different interface.
2121 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002122 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
2123 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002124 if (getLangOpts().CPlusPlus && LHS && RHS &&
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00002125 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
2126 FromObjCPtr->getPointeeType()))
2127 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002128 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002129 ToObjCPtr->getPointeeType(),
2130 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002131 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002132 return true;
2133 }
2134
2135 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
2136 // Okay: this is some kind of implicit downcast of Objective-C
2137 // interfaces, which is permitted. However, we're going to
2138 // complain about it.
2139 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002140 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00002141 ToObjCPtr->getPointeeType(),
2142 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002143 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00002144 return true;
2145 }
Mike Stump1eb44332009-09-09 15:08:12 +00002146 }
Steve Naroff14108da2009-07-10 23:34:53 +00002147 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002148 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002149 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002150 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002151 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002152 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00002153 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002154 // to a block pointer type.
2155 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002156 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002157 return true;
2158 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002159 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00002160 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002161 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002162 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002163 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00002164 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002165 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00002166 return true;
2167 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002168 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002169 return false;
2170
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002171 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002172 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00002173 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00002174 else if (const BlockPointerType *FromBlockPtr =
2175 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002176 FromPointeeType = FromBlockPtr->getPointeeType();
2177 else
Douglas Gregorc7887512008-12-19 19:13:09 +00002178 return false;
2179
Douglas Gregorc7887512008-12-19 19:13:09 +00002180 // If we have pointers to pointers, recursively check whether this
2181 // is an Objective-C conversion.
2182 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
2183 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2184 IncompatibleObjC)) {
2185 // We always complain about this conversion.
2186 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00002187 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002188 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002189 return true;
2190 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002191 // Allow conversion of pointee being objective-c pointer to another one;
2192 // as in I* to id.
2193 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
2194 ToPointeeType->getAs<ObjCObjectPointerType>() &&
2195 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
2196 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00002197
Douglas Gregorda80f742010-12-01 21:43:58 +00002198 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002199 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00002200 return true;
2201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002202
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00002203 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00002204 // differences in the argument and result types are in Objective-C
2205 // pointer conversions. If so, we permit the conversion (but
2206 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00002207 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00002208 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00002209 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00002210 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00002211 if (FromFunctionType && ToFunctionType) {
2212 // If the function types are exactly the same, this isn't an
2213 // Objective-C pointer conversion.
2214 if (Context.getCanonicalType(FromPointeeType)
2215 == Context.getCanonicalType(ToPointeeType))
2216 return false;
2217
2218 // Perform the quick checks that will tell us whether these
2219 // function types are obviously different.
2220 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2221 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
2222 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
2223 return false;
2224
2225 bool HasObjCConversion = false;
2226 if (Context.getCanonicalType(FromFunctionType->getResultType())
2227 == Context.getCanonicalType(ToFunctionType->getResultType())) {
2228 // Okay, the types match exactly. Nothing to do.
2229 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
2230 ToFunctionType->getResultType(),
2231 ConvertedType, IncompatibleObjC)) {
2232 // Okay, we have an Objective-C pointer conversion.
2233 HasObjCConversion = true;
2234 } else {
2235 // Function types are too different. Abort.
2236 return false;
2237 }
Mike Stump1eb44332009-09-09 15:08:12 +00002238
Douglas Gregorc7887512008-12-19 19:13:09 +00002239 // Check argument types.
2240 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2241 ArgIdx != NumArgs; ++ArgIdx) {
2242 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2243 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2244 if (Context.getCanonicalType(FromArgType)
2245 == Context.getCanonicalType(ToArgType)) {
2246 // Okay, the types match exactly. Nothing to do.
2247 } else if (isObjCPointerConversion(FromArgType, ToArgType,
2248 ConvertedType, IncompatibleObjC)) {
2249 // Okay, we have an Objective-C pointer conversion.
2250 HasObjCConversion = true;
2251 } else {
2252 // Argument types are too different. Abort.
2253 return false;
2254 }
2255 }
2256
2257 if (HasObjCConversion) {
2258 // We had an Objective-C conversion. Allow this pointer
2259 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002260 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002261 IncompatibleObjC = true;
2262 return true;
2263 }
2264 }
2265
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002266 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002267}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002268
John McCallf85e1932011-06-15 23:02:42 +00002269/// \brief Determine whether this is an Objective-C writeback conversion,
2270/// used for parameter passing when performing automatic reference counting.
2271///
2272/// \param FromType The type we're converting form.
2273///
2274/// \param ToType The type we're converting to.
2275///
2276/// \param ConvertedType The type that will be produced after applying
2277/// this conversion.
2278bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2279 QualType &ConvertedType) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002280 if (!getLangOpts().ObjCAutoRefCount ||
John McCallf85e1932011-06-15 23:02:42 +00002281 Context.hasSameUnqualifiedType(FromType, ToType))
2282 return false;
2283
2284 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2285 QualType ToPointee;
2286 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2287 ToPointee = ToPointer->getPointeeType();
2288 else
2289 return false;
2290
2291 Qualifiers ToQuals = ToPointee.getQualifiers();
2292 if (!ToPointee->isObjCLifetimeType() ||
2293 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
John McCall200fa532012-02-08 00:46:36 +00002294 !ToQuals.withoutObjCLifetime().empty())
John McCallf85e1932011-06-15 23:02:42 +00002295 return false;
2296
2297 // Argument must be a pointer to __strong to __weak.
2298 QualType FromPointee;
2299 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2300 FromPointee = FromPointer->getPointeeType();
2301 else
2302 return false;
2303
2304 Qualifiers FromQuals = FromPointee.getQualifiers();
2305 if (!FromPointee->isObjCLifetimeType() ||
2306 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2307 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2308 return false;
2309
2310 // Make sure that we have compatible qualifiers.
2311 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2312 if (!ToQuals.compatiblyIncludes(FromQuals))
2313 return false;
2314
2315 // Remove qualifiers from the pointee type we're converting from; they
2316 // aren't used in the compatibility check belong, and we'll be adding back
2317 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2318 FromPointee = FromPointee.getUnqualifiedType();
2319
2320 // The unqualified form of the pointee types must be compatible.
2321 ToPointee = ToPointee.getUnqualifiedType();
2322 bool IncompatibleObjC;
2323 if (Context.typesAreCompatible(FromPointee, ToPointee))
2324 FromPointee = ToPointee;
2325 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2326 IncompatibleObjC))
2327 return false;
2328
2329 /// \brief Construct the type we're converting to, which is a pointer to
2330 /// __autoreleasing pointee.
2331 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2332 ConvertedType = Context.getPointerType(FromPointee);
2333 return true;
2334}
2335
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002336bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2337 QualType& ConvertedType) {
2338 QualType ToPointeeType;
2339 if (const BlockPointerType *ToBlockPtr =
2340 ToType->getAs<BlockPointerType>())
2341 ToPointeeType = ToBlockPtr->getPointeeType();
2342 else
2343 return false;
2344
2345 QualType FromPointeeType;
2346 if (const BlockPointerType *FromBlockPtr =
2347 FromType->getAs<BlockPointerType>())
2348 FromPointeeType = FromBlockPtr->getPointeeType();
2349 else
2350 return false;
2351 // We have pointer to blocks, check whether the only
2352 // differences in the argument and result types are in Objective-C
2353 // pointer conversions. If so, we permit the conversion.
2354
2355 const FunctionProtoType *FromFunctionType
2356 = FromPointeeType->getAs<FunctionProtoType>();
2357 const FunctionProtoType *ToFunctionType
2358 = ToPointeeType->getAs<FunctionProtoType>();
2359
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002360 if (!FromFunctionType || !ToFunctionType)
2361 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002362
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002363 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002364 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002365
2366 // Perform the quick checks that will tell us whether these
2367 // function types are obviously different.
2368 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2369 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2370 return false;
2371
2372 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2373 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2374 if (FromEInfo != ToEInfo)
2375 return false;
2376
2377 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002378 if (Context.hasSameType(FromFunctionType->getResultType(),
2379 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002380 // Okay, the types match exactly. Nothing to do.
2381 } else {
2382 QualType RHS = FromFunctionType->getResultType();
2383 QualType LHS = ToFunctionType->getResultType();
David Blaikie4e4d0842012-03-11 07:00:24 +00002384 if ((!getLangOpts().CPlusPlus || !RHS->isRecordType()) &&
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002385 !RHS.hasQualifiers() && LHS.hasQualifiers())
2386 LHS = LHS.getUnqualifiedType();
2387
2388 if (Context.hasSameType(RHS,LHS)) {
2389 // OK exact match.
2390 } else if (isObjCPointerConversion(RHS, LHS,
2391 ConvertedType, IncompatibleObjC)) {
2392 if (IncompatibleObjC)
2393 return false;
2394 // Okay, we have an Objective-C pointer conversion.
2395 }
2396 else
2397 return false;
2398 }
2399
2400 // Check argument types.
2401 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2402 ArgIdx != NumArgs; ++ArgIdx) {
2403 IncompatibleObjC = false;
2404 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2405 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2406 if (Context.hasSameType(FromArgType, ToArgType)) {
2407 // Okay, the types match exactly. Nothing to do.
2408 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2409 ConvertedType, IncompatibleObjC)) {
2410 if (IncompatibleObjC)
2411 return false;
2412 // Okay, we have an Objective-C pointer conversion.
2413 } else
2414 // Argument types are too different. Abort.
2415 return false;
2416 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002417 if (LangOpts.ObjCAutoRefCount &&
2418 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2419 ToFunctionType))
2420 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002421
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002422 ConvertedType = ToType;
2423 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002424}
2425
Richard Trieu6efd4c52011-11-23 22:32:32 +00002426enum {
2427 ft_default,
2428 ft_different_class,
2429 ft_parameter_arity,
2430 ft_parameter_mismatch,
2431 ft_return_type,
2432 ft_qualifer_mismatch
2433};
2434
2435/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2436/// function types. Catches different number of parameter, mismatch in
2437/// parameter types, and different return types.
2438void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2439 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002440 // If either type is not valid, include no extra info.
2441 if (FromType.isNull() || ToType.isNull()) {
2442 PDiag << ft_default;
2443 return;
2444 }
2445
Richard Trieu6efd4c52011-11-23 22:32:32 +00002446 // Get the function type from the pointers.
2447 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2448 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2449 *ToMember = ToType->getAs<MemberPointerType>();
2450 if (FromMember->getClass() != ToMember->getClass()) {
2451 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2452 << QualType(FromMember->getClass(), 0);
2453 return;
2454 }
2455 FromType = FromMember->getPointeeType();
2456 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002457 }
2458
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002459 if (FromType->isPointerType())
2460 FromType = FromType->getPointeeType();
2461 if (ToType->isPointerType())
2462 ToType = ToType->getPointeeType();
2463
2464 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002465 FromType = FromType.getNonReferenceType();
2466 ToType = ToType.getNonReferenceType();
2467
Richard Trieu6efd4c52011-11-23 22:32:32 +00002468 // Don't print extra info for non-specialized template functions.
2469 if (FromType->isInstantiationDependentType() &&
2470 !FromType->getAs<TemplateSpecializationType>()) {
2471 PDiag << ft_default;
2472 return;
2473 }
2474
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002475 // No extra info for same types.
2476 if (Context.hasSameType(FromType, ToType)) {
2477 PDiag << ft_default;
2478 return;
2479 }
2480
Richard Trieu6efd4c52011-11-23 22:32:32 +00002481 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2482 *ToFunction = ToType->getAs<FunctionProtoType>();
2483
2484 // Both types need to be function types.
2485 if (!FromFunction || !ToFunction) {
2486 PDiag << ft_default;
2487 return;
2488 }
2489
2490 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2491 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2492 << FromFunction->getNumArgs();
2493 return;
2494 }
2495
2496 // Handle different parameter types.
2497 unsigned ArgPos;
2498 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2499 PDiag << ft_parameter_mismatch << ArgPos + 1
2500 << ToFunction->getArgType(ArgPos)
2501 << FromFunction->getArgType(ArgPos);
2502 return;
2503 }
2504
2505 // Handle different return type.
2506 if (!Context.hasSameType(FromFunction->getResultType(),
2507 ToFunction->getResultType())) {
2508 PDiag << ft_return_type << ToFunction->getResultType()
2509 << FromFunction->getResultType();
2510 return;
2511 }
2512
2513 unsigned FromQuals = FromFunction->getTypeQuals(),
2514 ToQuals = ToFunction->getTypeQuals();
2515 if (FromQuals != ToQuals) {
2516 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2517 return;
2518 }
2519
2520 // Unable to find a difference, so add no extra info.
2521 PDiag << ft_default;
2522}
2523
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002524/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002525/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002526/// they have same number of arguments. This routine assumes that Objective-C
2527/// pointer types which only differ in their protocol qualifiers are equal.
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +00002528/// If the parameters are different, ArgPos will have the parameter index
Richard Trieu6efd4c52011-11-23 22:32:32 +00002529/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002530bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002531 const FunctionProtoType *NewType,
2532 unsigned *ArgPos) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002533 if (!getLangOpts().ObjC1) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00002534 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2535 N = NewType->arg_type_begin(),
2536 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2537 if (!Context.hasSameType(*O, *N)) {
2538 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2539 return false;
2540 }
2541 }
2542 return true;
2543 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002544
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002545 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2546 N = NewType->arg_type_begin(),
2547 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2548 QualType ToType = (*O);
2549 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002550 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002551 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2552 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002553 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2554 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2555 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2556 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002557 continue;
2558 }
John McCallc12c5bb2010-05-15 11:32:37 +00002559 else if (const ObjCObjectPointerType *PTTo =
2560 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002561 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002562 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002563 if (Context.hasSameUnqualifiedType(
2564 PTTo->getObjectType()->getBaseType(),
2565 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002566 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002567 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002568 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002569 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002570 }
2571 }
2572 return true;
2573}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002574
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002575/// CheckPointerConversion - Check the pointer conversion from the
2576/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002577/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002578/// conversions for which IsPointerConversion has already returned
2579/// true. It returns true and produces a diagnostic if there was an
2580/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002581bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002582 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002583 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002584 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002585 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002586 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002587
John McCalldaa8e4e2010-11-15 09:13:47 +00002588 Kind = CK_BitCast;
2589
David Blaikie50800fc2012-08-08 17:33:31 +00002590 if (!IsCStyleOrFunctionalCast && !FromType->isAnyPointerType() &&
2591 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull) ==
2592 Expr::NPCK_ZeroExpression) {
2593 if (Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy))
2594 DiagRuntimeBehavior(From->getExprLoc(), From,
2595 PDiag(diag::warn_impcast_bool_to_null_pointer)
2596 << ToType << From->getSourceRange());
2597 else if (!isUnevaluatedContext())
2598 Diag(From->getExprLoc(), diag::warn_non_literal_null_pointer)
2599 << ToType << From->getSourceRange();
2600 }
John McCall1d9b3b22011-09-09 05:25:32 +00002601 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2602 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002603 QualType FromPointeeType = FromPtrType->getPointeeType(),
2604 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002605
Douglas Gregor5fccd362010-03-03 23:55:11 +00002606 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2607 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002608 // We must have a derived-to-base conversion. Check an
2609 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002610 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2611 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002612 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002613 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002614 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002615
Anders Carlsson61faec12009-09-12 04:46:44 +00002616 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002617 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002618 }
2619 }
John McCall1d9b3b22011-09-09 05:25:32 +00002620 } else if (const ObjCObjectPointerType *ToPtrType =
2621 ToType->getAs<ObjCObjectPointerType>()) {
2622 if (const ObjCObjectPointerType *FromPtrType =
2623 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002624 // Objective-C++ conversions are always okay.
2625 // FIXME: We should have a different class of conversions for the
2626 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002627 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002628 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002629 } else if (FromType->isBlockPointerType()) {
2630 Kind = CK_BlockPointerToObjCPointerCast;
2631 } else {
2632 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002633 }
John McCall1d9b3b22011-09-09 05:25:32 +00002634 } else if (ToType->isBlockPointerType()) {
2635 if (!FromType->isBlockPointerType())
2636 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002637 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002638
2639 // We shouldn't fall into this case unless it's valid for other
2640 // reasons.
2641 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2642 Kind = CK_NullToPointer;
2643
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002644 return false;
2645}
2646
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002647/// IsMemberPointerConversion - Determines whether the conversion of the
2648/// expression From, which has the (possibly adjusted) type FromType, can be
2649/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2650/// If so, returns true and places the converted type (that might differ from
2651/// ToType in its cv-qualifiers at some level) into ConvertedType.
2652bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002653 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002654 bool InOverloadResolution,
2655 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002656 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002657 if (!ToTypePtr)
2658 return false;
2659
2660 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002661 if (From->isNullPointerConstant(Context,
2662 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2663 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002664 ConvertedType = ToType;
2665 return true;
2666 }
2667
2668 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002669 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002670 if (!FromTypePtr)
2671 return false;
2672
2673 // A pointer to member of B can be converted to a pointer to member of D,
2674 // where D is derived from B (C++ 4.11p2).
2675 QualType FromClass(FromTypePtr->getClass(), 0);
2676 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002677
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002678 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
Douglas Gregord10099e2012-05-04 16:32:21 +00002679 !RequireCompleteType(From->getLocStart(), ToClass, 0) &&
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002680 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002681 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2682 ToClass.getTypePtr());
2683 return true;
2684 }
2685
2686 return false;
2687}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002688
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002689/// CheckMemberPointerConversion - Check the member pointer conversion from the
2690/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002691/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002692/// for which IsMemberPointerConversion has already returned true. It returns
2693/// true and produces a diagnostic if there was an error, or returns false
2694/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002695bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002696 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002697 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002698 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002699 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002700 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002701 if (!FromPtrType) {
2702 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002703 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002704 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002705 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002706 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002707 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002708 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002709
Ted Kremenek6217b802009-07-29 21:53:49 +00002710 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002711 assert(ToPtrType && "No member pointer cast has a target type "
2712 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002713
Sebastian Redl21593ac2009-01-28 18:33:18 +00002714 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2715 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002716
Sebastian Redl21593ac2009-01-28 18:33:18 +00002717 // FIXME: What about dependent types?
2718 assert(FromClass->isRecordType() && "Pointer into non-class.");
2719 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002720
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002721 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002722 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002723 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2724 assert(DerivationOkay &&
2725 "Should not have been called if derivation isn't OK.");
2726 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002727
Sebastian Redl21593ac2009-01-28 18:33:18 +00002728 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2729 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002730 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2731 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2732 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2733 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002734 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002735
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002736 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002737 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2738 << FromClass << ToClass << QualType(VBase, 0)
2739 << From->getSourceRange();
2740 return true;
2741 }
2742
John McCall6b2accb2010-02-10 09:31:12 +00002743 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002744 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2745 Paths.front(),
2746 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002747
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002748 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002749 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002750 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002751 return false;
2752}
2753
Douglas Gregor98cd5992008-10-21 23:43:52 +00002754/// IsQualificationConversion - Determines whether the conversion from
2755/// an rvalue of type FromType to ToType is a qualification conversion
2756/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002757///
2758/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2759/// when the qualification conversion involves a change in the Objective-C
2760/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002761bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002762Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002763 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002764 FromType = Context.getCanonicalType(FromType);
2765 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002766 ObjCLifetimeConversion = false;
2767
Douglas Gregor98cd5992008-10-21 23:43:52 +00002768 // If FromType and ToType are the same type, this is not a
2769 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002770 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002771 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002772
Douglas Gregor98cd5992008-10-21 23:43:52 +00002773 // (C++ 4.4p4):
2774 // A conversion can add cv-qualifiers at levels other than the first
2775 // in multi-level pointers, subject to the following rules: [...]
2776 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002777 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002778 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002779 // Within each iteration of the loop, we check the qualifiers to
2780 // determine if this still looks like a qualification
2781 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002782 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002783 // until there are no more pointers or pointers-to-members left to
2784 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002785 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002786
Douglas Gregor621c92a2011-04-25 18:40:17 +00002787 Qualifiers FromQuals = FromType.getQualifiers();
2788 Qualifiers ToQuals = ToType.getQualifiers();
2789
John McCallf85e1932011-06-15 23:02:42 +00002790 // Objective-C ARC:
2791 // Check Objective-C lifetime conversions.
2792 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2793 UnwrappedAnyPointer) {
2794 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2795 ObjCLifetimeConversion = true;
2796 FromQuals.removeObjCLifetime();
2797 ToQuals.removeObjCLifetime();
2798 } else {
2799 // Qualification conversions cannot cast between different
2800 // Objective-C lifetime qualifiers.
2801 return false;
2802 }
2803 }
2804
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002805 // Allow addition/removal of GC attributes but not changing GC attributes.
2806 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2807 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2808 FromQuals.removeObjCGCAttr();
2809 ToQuals.removeObjCGCAttr();
2810 }
2811
Douglas Gregor98cd5992008-10-21 23:43:52 +00002812 // -- for every j > 0, if const is in cv 1,j then const is in cv
2813 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002814 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002815 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002816
Douglas Gregor98cd5992008-10-21 23:43:52 +00002817 // -- if the cv 1,j and cv 2,j are different, then const is in
2818 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002819 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002820 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002821 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002822
Douglas Gregor98cd5992008-10-21 23:43:52 +00002823 // Keep track of whether all prior cv-qualifiers in the "to" type
2824 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002825 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002826 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002827 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002828
2829 // We are left with FromType and ToType being the pointee types
2830 // after unwrapping the original FromType and ToType the same number
2831 // of types. If we unwrapped any pointers, and if FromType and
2832 // ToType have the same unqualified type (since we checked
2833 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002834 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002835}
2836
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002837/// \brief - Determine whether this is a conversion from a scalar type to an
2838/// atomic type.
2839///
2840/// If successful, updates \c SCS's second and third steps in the conversion
2841/// sequence to finish the conversion.
Douglas Gregor7d000652012-04-12 20:48:09 +00002842static bool tryAtomicConversion(Sema &S, Expr *From, QualType ToType,
2843 bool InOverloadResolution,
2844 StandardConversionSequence &SCS,
2845 bool CStyle) {
Douglas Gregorf7ecc302012-04-12 17:51:55 +00002846 const AtomicType *ToAtomic = ToType->getAs<AtomicType>();
2847 if (!ToAtomic)
2848 return false;
2849
2850 StandardConversionSequence InnerSCS;
2851 if (!IsStandardConversion(S, From, ToAtomic->getValueType(),
2852 InOverloadResolution, InnerSCS,
2853 CStyle, /*AllowObjCWritebackConversion=*/false))
2854 return false;
2855
2856 SCS.Second = InnerSCS.Second;
2857 SCS.setToType(1, InnerSCS.getToType(1));
2858 SCS.Third = InnerSCS.Third;
2859 SCS.QualificationIncludesObjCLifetime
2860 = InnerSCS.QualificationIncludesObjCLifetime;
2861 SCS.setToType(2, InnerSCS.getToType(2));
2862 return true;
2863}
2864
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002865static bool isFirstArgumentCompatibleWithType(ASTContext &Context,
2866 CXXConstructorDecl *Constructor,
2867 QualType Type) {
2868 const FunctionProtoType *CtorType =
2869 Constructor->getType()->getAs<FunctionProtoType>();
2870 if (CtorType->getNumArgs() > 0) {
2871 QualType FirstArg = CtorType->getArgType(0);
2872 if (Context.hasSameUnqualifiedType(Type, FirstArg.getNonReferenceType()))
2873 return true;
2874 }
2875 return false;
2876}
2877
Sebastian Redl56a04282012-02-11 23:51:08 +00002878static OverloadingResult
2879IsInitializerListConstructorConversion(Sema &S, Expr *From, QualType ToType,
2880 CXXRecordDecl *To,
2881 UserDefinedConversionSequence &User,
2882 OverloadCandidateSet &CandidateSet,
2883 bool AllowExplicit) {
David Blaikie3bc93e32012-12-19 00:45:41 +00002884 DeclContext::lookup_result R = S.LookupConstructors(To);
2885 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Sebastian Redl56a04282012-02-11 23:51:08 +00002886 Con != ConEnd; ++Con) {
2887 NamedDecl *D = *Con;
2888 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2889
2890 // Find the constructor (which may be a template).
2891 CXXConstructorDecl *Constructor = 0;
2892 FunctionTemplateDecl *ConstructorTmpl
2893 = dyn_cast<FunctionTemplateDecl>(D);
2894 if (ConstructorTmpl)
2895 Constructor
2896 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2897 else
2898 Constructor = cast<CXXConstructorDecl>(D);
2899
2900 bool Usable = !Constructor->isInvalidDecl() &&
2901 S.isInitListConstructor(Constructor) &&
2902 (AllowExplicit || !Constructor->isExplicit());
2903 if (Usable) {
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002904 // If the first argument is (a reference to) the target type,
2905 // suppress conversions.
2906 bool SuppressUserConversions =
2907 isFirstArgumentCompatibleWithType(S.Context, Constructor, ToType);
Sebastian Redl56a04282012-02-11 23:51:08 +00002908 if (ConstructorTmpl)
2909 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2910 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002911 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002912 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002913 else
2914 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00002915 From, CandidateSet,
Sebastian Redlf78c0f92012-03-27 18:33:03 +00002916 SuppressUserConversions);
Sebastian Redl56a04282012-02-11 23:51:08 +00002917 }
2918 }
2919
2920 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2921
2922 OverloadCandidateSet::iterator Best;
2923 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
2924 case OR_Success: {
2925 // Record the standard conversion we used and the conversion function.
2926 CXXConstructorDecl *Constructor = cast<CXXConstructorDecl>(Best->Function);
Sebastian Redl56a04282012-02-11 23:51:08 +00002927 QualType ThisType = Constructor->getThisType(S.Context);
2928 // Initializer lists don't have conversions as such.
2929 User.Before.setAsIdentityConversion();
2930 User.HadMultipleCandidates = HadMultipleCandidates;
2931 User.ConversionFunction = Constructor;
2932 User.FoundConversionFunction = Best->FoundDecl;
2933 User.After.setAsIdentityConversion();
2934 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2935 User.After.setAllToTypes(ToType);
2936 return OR_Success;
2937 }
2938
2939 case OR_No_Viable_Function:
2940 return OR_No_Viable_Function;
2941 case OR_Deleted:
2942 return OR_Deleted;
2943 case OR_Ambiguous:
2944 return OR_Ambiguous;
2945 }
2946
2947 llvm_unreachable("Invalid OverloadResult!");
2948}
2949
Douglas Gregor734d9862009-01-30 23:27:23 +00002950/// Determines whether there is a user-defined conversion sequence
2951/// (C++ [over.ics.user]) that converts expression From to the type
2952/// ToType. If such a conversion exists, User will contain the
2953/// user-defined conversion sequence that performs such a conversion
2954/// and this routine will return true. Otherwise, this routine returns
2955/// false and User is unspecified.
2956///
Douglas Gregor734d9862009-01-30 23:27:23 +00002957/// \param AllowExplicit true if the conversion should consider C++0x
2958/// "explicit" conversion functions as well as non-explicit conversion
2959/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002960static OverloadingResult
2961IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
Sebastian Redl56a04282012-02-11 23:51:08 +00002962 UserDefinedConversionSequence &User,
2963 OverloadCandidateSet &CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002964 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002965 // Whether we will only visit constructors.
2966 bool ConstructorsOnly = false;
2967
2968 // If the type we are conversion to is a class type, enumerate its
2969 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002970 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002971 // C++ [over.match.ctor]p1:
2972 // When objects of class type are direct-initialized (8.5), or
2973 // copy-initialized from an expression of the same or a
2974 // derived class type (8.5), overload resolution selects the
2975 // constructor. [...] For copy-initialization, the candidate
2976 // functions are all the converting constructors (12.3.1) of
2977 // that class. The argument list is the expression-list within
2978 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002979 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002980 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002981 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002982 ConstructorsOnly = true;
2983
Benjamin Kramer63b6ebe2012-11-23 17:04:52 +00002984 S.RequireCompleteType(From->getExprLoc(), ToType, 0);
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002985 // RequireCompleteType may have returned true due to some invalid decl
2986 // during template instantiation, but ToType may be complete enough now
2987 // to try to recover.
2988 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002989 // We're not going to find any constructors.
2990 } else if (CXXRecordDecl *ToRecordDecl
2991 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002992
2993 Expr **Args = &From;
2994 unsigned NumArgs = 1;
2995 bool ListInitializing = false;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00002996 if (InitListExpr *InitList = dyn_cast<InitListExpr>(From)) {
Sebastian Redl56a04282012-02-11 23:51:08 +00002997 // But first, see if there is an init-list-contructor that will work.
2998 OverloadingResult Result = IsInitializerListConstructorConversion(
2999 S, From, ToType, ToRecordDecl, User, CandidateSet, AllowExplicit);
3000 if (Result != OR_No_Viable_Function)
3001 return Result;
3002 // Never mind.
3003 CandidateSet.clear();
3004
3005 // If we're list-initializing, we pass the individual elements as
3006 // arguments, not the entire list.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003007 Args = InitList->getInits();
3008 NumArgs = InitList->getNumInits();
3009 ListInitializing = true;
3010 }
3011
David Blaikie3bc93e32012-12-19 00:45:41 +00003012 DeclContext::lookup_result R = S.LookupConstructors(ToRecordDecl);
3013 for (DeclContext::lookup_iterator Con = R.begin(), ConEnd = R.end();
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003014 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00003015 NamedDecl *D = *Con;
3016 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
3017
Douglas Gregordec06662009-08-21 18:42:58 +00003018 // Find the constructor (which may be a template).
3019 CXXConstructorDecl *Constructor = 0;
3020 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00003021 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00003022 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00003023 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00003024 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
3025 else
John McCall9aa472c2010-03-19 07:35:19 +00003026 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003027
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003028 bool Usable = !Constructor->isInvalidDecl();
3029 if (ListInitializing)
3030 Usable = Usable && (AllowExplicit || !Constructor->isExplicit());
3031 else
3032 Usable = Usable &&Constructor->isConvertingConstructor(AllowExplicit);
3033 if (Usable) {
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003034 bool SuppressUserConversions = !ConstructorsOnly;
3035 if (SuppressUserConversions && ListInitializing) {
3036 SuppressUserConversions = false;
3037 if (NumArgs == 1) {
3038 // If the first argument is (a reference to) the target type,
3039 // suppress conversions.
Sebastian Redlf78c0f92012-03-27 18:33:03 +00003040 SuppressUserConversions = isFirstArgumentCompatibleWithType(
3041 S.Context, Constructor, ToType);
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003042 }
3043 }
Douglas Gregordec06662009-08-21 18:42:58 +00003044 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00003045 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
3046 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003047 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003048 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003049 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00003050 // Allow one user-defined conversion when user specifies a
3051 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00003052 S.AddOverloadCandidate(Constructor, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00003053 llvm::makeArrayRef(Args, NumArgs),
Sebastian Redl1cd89c42012-03-20 21:24:14 +00003054 CandidateSet, SuppressUserConversions);
Douglas Gregordec06662009-08-21 18:42:58 +00003055 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00003056 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003057 }
3058 }
3059
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003060 // Enumerate conversion functions, if we're allowed to.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003061 if (ConstructorsOnly || isa<InitListExpr>(From)) {
Douglas Gregord10099e2012-05-04 16:32:21 +00003062 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(), 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003063 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00003064 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003065 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003066 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003067 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
3068 // Add all of the conversion functions as candidates.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003069 std::pair<CXXRecordDecl::conversion_iterator,
3070 CXXRecordDecl::conversion_iterator>
3071 Conversions = FromRecordDecl->getVisibleConversionFunctions();
3072 for (CXXRecordDecl::conversion_iterator
3073 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00003074 DeclAccessPair FoundDecl = I.getPair();
3075 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003076 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
3077 if (isa<UsingShadowDecl>(D))
3078 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3079
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003080 CXXConversionDecl *Conv;
3081 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00003082 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
3083 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003084 else
John McCall32daa422010-03-31 01:36:47 +00003085 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003086
3087 if (AllowExplicit || !Conv->isExplicit()) {
3088 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00003089 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
3090 ActingContext, From, ToType,
3091 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003092 else
John McCall120d63c2010-08-24 20:38:10 +00003093 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
3094 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00003095 }
3096 }
3097 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003098 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003099
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003100 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3101
Douglas Gregor60d62c22008-10-31 16:23:19 +00003102 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003103 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00003104 case OR_Success:
3105 // Record the standard conversion we used and the conversion function.
3106 if (CXXConstructorDecl *Constructor
3107 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
3108 // C++ [over.ics.user]p1:
3109 // If the user-defined conversion is specified by a
3110 // constructor (12.3.1), the initial standard conversion
3111 // sequence converts the source type to the type required by
3112 // the argument of the constructor.
3113 //
3114 QualType ThisType = Constructor->getThisType(S.Context);
Sebastian Redlcf15cef2011-12-22 18:58:38 +00003115 if (isa<InitListExpr>(From)) {
3116 // Initializer lists don't have conversions as such.
3117 User.Before.setAsIdentityConversion();
3118 } else {
3119 if (Best->Conversions[0].isEllipsis())
3120 User.EllipsisConversion = true;
3121 else {
3122 User.Before = Best->Conversions[0].Standard;
3123 User.EllipsisConversion = false;
3124 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00003125 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003126 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003127 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00003128 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003129 User.After.setAsIdentityConversion();
3130 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
3131 User.After.setAllToTypes(ToType);
3132 return OR_Success;
David Blaikie7530c032012-01-17 06:56:22 +00003133 }
3134 if (CXXConversionDecl *Conversion
John McCall120d63c2010-08-24 20:38:10 +00003135 = dyn_cast<CXXConversionDecl>(Best->Function)) {
3136 // C++ [over.ics.user]p1:
3137 //
3138 // [...] If the user-defined conversion is specified by a
3139 // conversion function (12.3.2), the initial standard
3140 // conversion sequence converts the source type to the
3141 // implicit object parameter of the conversion function.
3142 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003143 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00003144 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00003145 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00003146 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00003147
John McCall120d63c2010-08-24 20:38:10 +00003148 // C++ [over.ics.user]p2:
3149 // The second standard conversion sequence converts the
3150 // result of the user-defined conversion to the target type
3151 // for the sequence. Since an implicit conversion sequence
3152 // is an initialization, the special rules for
3153 // initialization by user-defined conversion apply when
3154 // selecting the best user-defined conversion for a
3155 // user-defined conversion sequence (see 13.3.3 and
3156 // 13.3.3.1).
3157 User.After = Best->FinalConversion;
3158 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00003159 }
David Blaikie7530c032012-01-17 06:56:22 +00003160 llvm_unreachable("Not a constructor or conversion function?");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003161
John McCall120d63c2010-08-24 20:38:10 +00003162 case OR_No_Viable_Function:
3163 return OR_No_Viable_Function;
3164 case OR_Deleted:
3165 // No conversion here! We're done.
3166 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003167
John McCall120d63c2010-08-24 20:38:10 +00003168 case OR_Ambiguous:
3169 return OR_Ambiguous;
3170 }
3171
David Blaikie7530c032012-01-17 06:56:22 +00003172 llvm_unreachable("Invalid OverloadResult!");
Douglas Gregor60d62c22008-10-31 16:23:19 +00003173}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003174
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003175bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003176Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003177 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00003178 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003179 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00003180 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003181 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003182 if (OvResult == OR_Ambiguous)
Daniel Dunbar96a00142012-03-09 18:35:03 +00003183 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003184 diag::err_typecheck_ambiguous_condition)
3185 << From->getType() << ToType << From->getSourceRange();
3186 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +00003187 Diag(From->getLocStart(),
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003188 diag::err_typecheck_nonviable_condition)
3189 << From->getType() << ToType << From->getSourceRange();
3190 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003191 return false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00003192 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003193 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003194}
Douglas Gregor60d62c22008-10-31 16:23:19 +00003195
Douglas Gregorb734e242012-02-22 17:32:19 +00003196/// \brief Compare the user-defined conversion functions or constructors
3197/// of two user-defined conversion sequences to determine whether any ordering
3198/// is possible.
3199static ImplicitConversionSequence::CompareKind
3200compareConversionFunctions(Sema &S,
3201 FunctionDecl *Function1,
3202 FunctionDecl *Function2) {
David Blaikie4e4d0842012-03-11 07:00:24 +00003203 if (!S.getLangOpts().ObjC1 || !S.getLangOpts().CPlusPlus0x)
Douglas Gregorb734e242012-02-22 17:32:19 +00003204 return ImplicitConversionSequence::Indistinguishable;
3205
3206 // Objective-C++:
3207 // If both conversion functions are implicitly-declared conversions from
3208 // a lambda closure type to a function pointer and a block pointer,
3209 // respectively, always prefer the conversion to a function pointer,
3210 // because the function pointer is more lightweight and is more likely
3211 // to keep code working.
3212 CXXConversionDecl *Conv1 = dyn_cast<CXXConversionDecl>(Function1);
3213 if (!Conv1)
3214 return ImplicitConversionSequence::Indistinguishable;
3215
3216 CXXConversionDecl *Conv2 = dyn_cast<CXXConversionDecl>(Function2);
3217 if (!Conv2)
3218 return ImplicitConversionSequence::Indistinguishable;
3219
3220 if (Conv1->getParent()->isLambda() && Conv2->getParent()->isLambda()) {
3221 bool Block1 = Conv1->getConversionType()->isBlockPointerType();
3222 bool Block2 = Conv2->getConversionType()->isBlockPointerType();
3223 if (Block1 != Block2)
3224 return Block1? ImplicitConversionSequence::Worse
3225 : ImplicitConversionSequence::Better;
3226 }
3227
3228 return ImplicitConversionSequence::Indistinguishable;
3229}
3230
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003231/// CompareImplicitConversionSequences - Compare two implicit
3232/// conversion sequences to determine whether one is better than the
3233/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00003234static ImplicitConversionSequence::CompareKind
3235CompareImplicitConversionSequences(Sema &S,
3236 const ImplicitConversionSequence& ICS1,
3237 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003238{
3239 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
3240 // conversion sequences (as defined in 13.3.3.1)
3241 // -- a standard conversion sequence (13.3.3.1.1) is a better
3242 // conversion sequence than a user-defined conversion sequence or
3243 // an ellipsis conversion sequence, and
3244 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
3245 // conversion sequence than an ellipsis conversion sequence
3246 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00003247 //
John McCall1d318332010-01-12 00:44:57 +00003248 // C++0x [over.best.ics]p10:
3249 // For the purpose of ranking implicit conversion sequences as
3250 // described in 13.3.3.2, the ambiguous conversion sequence is
3251 // treated as a user-defined sequence that is indistinguishable
3252 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003253 if (ICS1.getKindRank() < ICS2.getKindRank())
3254 return ImplicitConversionSequence::Better;
David Blaikie7530c032012-01-17 06:56:22 +00003255 if (ICS2.getKindRank() < ICS1.getKindRank())
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003256 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003257
Benjamin Kramerb6eee072010-04-18 12:05:54 +00003258 // The following checks require both conversion sequences to be of
3259 // the same kind.
3260 if (ICS1.getKind() != ICS2.getKind())
3261 return ImplicitConversionSequence::Indistinguishable;
3262
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003263 ImplicitConversionSequence::CompareKind Result =
3264 ImplicitConversionSequence::Indistinguishable;
3265
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003266 // Two implicit conversion sequences of the same form are
3267 // indistinguishable conversion sequences unless one of the
3268 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00003269 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003270 Result = CompareStandardConversionSequences(S,
3271 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00003272 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003273 // User-defined conversion sequence U1 is a better conversion
3274 // sequence than another user-defined conversion sequence U2 if
3275 // they contain the same user-defined conversion function or
3276 // constructor and if the second standard conversion sequence of
3277 // U1 is better than the second standard conversion sequence of
3278 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00003279 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003280 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003281 Result = CompareStandardConversionSequences(S,
3282 ICS1.UserDefined.After,
3283 ICS2.UserDefined.After);
Douglas Gregorb734e242012-02-22 17:32:19 +00003284 else
3285 Result = compareConversionFunctions(S,
3286 ICS1.UserDefined.ConversionFunction,
3287 ICS2.UserDefined.ConversionFunction);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003288 }
3289
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003290 // List-initialization sequence L1 is a better conversion sequence than
3291 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
3292 // for some X and L2 does not.
3293 if (Result == ImplicitConversionSequence::Indistinguishable &&
Sebastian Redladfb5352012-02-27 22:38:26 +00003294 !ICS1.isBad() &&
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003295 ICS1.isListInitializationSequence() &&
3296 ICS2.isListInitializationSequence()) {
Sebastian Redladfb5352012-02-27 22:38:26 +00003297 if (ICS1.isStdInitializerListElement() &&
3298 !ICS2.isStdInitializerListElement())
3299 return ImplicitConversionSequence::Better;
3300 if (!ICS1.isStdInitializerListElement() &&
3301 ICS2.isStdInitializerListElement())
3302 return ImplicitConversionSequence::Worse;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003303 }
3304
3305 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003306}
3307
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003308static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
3309 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
3310 Qualifiers Quals;
3311 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003312 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003314
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003315 return Context.hasSameUnqualifiedType(T1, T2);
3316}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003317
Douglas Gregorad323a82010-01-27 03:51:04 +00003318// Per 13.3.3.2p3, compare the given standard conversion sequences to
3319// determine if one is a proper subset of the other.
3320static ImplicitConversionSequence::CompareKind
3321compareStandardConversionSubsets(ASTContext &Context,
3322 const StandardConversionSequence& SCS1,
3323 const StandardConversionSequence& SCS2) {
3324 ImplicitConversionSequence::CompareKind Result
3325 = ImplicitConversionSequence::Indistinguishable;
3326
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003327 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00003328 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00003329 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
3330 return ImplicitConversionSequence::Better;
3331 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
3332 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003333
Douglas Gregorad323a82010-01-27 03:51:04 +00003334 if (SCS1.Second != SCS2.Second) {
3335 if (SCS1.Second == ICK_Identity)
3336 Result = ImplicitConversionSequence::Better;
3337 else if (SCS2.Second == ICK_Identity)
3338 Result = ImplicitConversionSequence::Worse;
3339 else
3340 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00003341 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00003342 return ImplicitConversionSequence::Indistinguishable;
3343
3344 if (SCS1.Third == SCS2.Third) {
3345 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
3346 : ImplicitConversionSequence::Indistinguishable;
3347 }
3348
3349 if (SCS1.Third == ICK_Identity)
3350 return Result == ImplicitConversionSequence::Worse
3351 ? ImplicitConversionSequence::Indistinguishable
3352 : ImplicitConversionSequence::Better;
3353
3354 if (SCS2.Third == ICK_Identity)
3355 return Result == ImplicitConversionSequence::Better
3356 ? ImplicitConversionSequence::Indistinguishable
3357 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358
Douglas Gregorad323a82010-01-27 03:51:04 +00003359 return ImplicitConversionSequence::Indistinguishable;
3360}
3361
Douglas Gregor440a4832011-01-26 14:52:12 +00003362/// \brief Determine whether one of the given reference bindings is better
3363/// than the other based on what kind of bindings they are.
3364static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
3365 const StandardConversionSequence &SCS2) {
3366 // C++0x [over.ics.rank]p3b4:
3367 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
3368 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003369 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00003370 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003371 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00003372 // reference*.
3373 //
3374 // FIXME: Rvalue references. We're going rogue with the above edits,
3375 // because the semantics in the current C++0x working paper (N3225 at the
3376 // time of this writing) break the standard definition of std::forward
3377 // and std::reference_wrapper when dealing with references to functions.
3378 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003379 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
3380 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
3381 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003382
Douglas Gregor440a4832011-01-26 14:52:12 +00003383 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
3384 SCS2.IsLvalueReference) ||
3385 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
3386 !SCS2.IsLvalueReference);
3387}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003388
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003389/// CompareStandardConversionSequences - Compare two standard
3390/// conversion sequences to determine whether one is better than the
3391/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00003392static ImplicitConversionSequence::CompareKind
3393CompareStandardConversionSequences(Sema &S,
3394 const StandardConversionSequence& SCS1,
3395 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003396{
3397 // Standard conversion sequence S1 is a better conversion sequence
3398 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
3399
3400 // -- S1 is a proper subsequence of S2 (comparing the conversion
3401 // sequences in the canonical form defined by 13.3.3.1.1,
3402 // excluding any Lvalue Transformation; the identity conversion
3403 // sequence is considered to be a subsequence of any
3404 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00003405 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00003406 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00003407 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003408
3409 // -- the rank of S1 is better than the rank of S2 (by the rules
3410 // defined below), or, if not that,
3411 ImplicitConversionRank Rank1 = SCS1.getRank();
3412 ImplicitConversionRank Rank2 = SCS2.getRank();
3413 if (Rank1 < Rank2)
3414 return ImplicitConversionSequence::Better;
3415 else if (Rank2 < Rank1)
3416 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003417
Douglas Gregor57373262008-10-22 14:17:15 +00003418 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
3419 // are indistinguishable unless one of the following rules
3420 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00003421
Douglas Gregor57373262008-10-22 14:17:15 +00003422 // A conversion that is not a conversion of a pointer, or
3423 // pointer to member, to bool is better than another conversion
3424 // that is such a conversion.
3425 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
3426 return SCS2.isPointerConversionToBool()
3427 ? ImplicitConversionSequence::Better
3428 : ImplicitConversionSequence::Worse;
3429
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003430 // C++ [over.ics.rank]p4b2:
3431 //
3432 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003433 // conversion of B* to A* is better than conversion of B* to
3434 // void*, and conversion of A* to void* is better than conversion
3435 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00003436 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003437 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00003438 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00003439 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003440 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
3441 // Exactly one of the conversion sequences is a conversion to
3442 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003443 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
3444 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003445 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
3446 // Neither conversion sequence converts to a void pointer; compare
3447 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003448 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00003449 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003450 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003451 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
3452 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003453 // Both conversion sequences are conversions to void
3454 // pointers. Compare the source types to determine if there's an
3455 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003456 QualType FromType1 = SCS1.getFromType();
3457 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003458
3459 // Adjust the types we're converting from via the array-to-pointer
3460 // conversion, if we need to.
3461 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003462 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003463 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003464 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003465
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003466 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3467 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003468
John McCall120d63c2010-08-24 20:38:10 +00003469 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003470 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003471 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003472 return ImplicitConversionSequence::Worse;
3473
3474 // Objective-C++: If one interface is more specific than the
3475 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003476 const ObjCObjectPointerType* FromObjCPtr1
3477 = FromType1->getAs<ObjCObjectPointerType>();
3478 const ObjCObjectPointerType* FromObjCPtr2
3479 = FromType2->getAs<ObjCObjectPointerType>();
3480 if (FromObjCPtr1 && FromObjCPtr2) {
3481 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3482 FromObjCPtr2);
3483 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3484 FromObjCPtr1);
3485 if (AssignLeft != AssignRight) {
3486 return AssignLeft? ImplicitConversionSequence::Better
3487 : ImplicitConversionSequence::Worse;
3488 }
Douglas Gregor01919692009-12-13 21:37:05 +00003489 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003490 }
Douglas Gregor57373262008-10-22 14:17:15 +00003491
3492 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3493 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003494 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003495 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003496 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003497
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003498 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003499 // Check for a better reference binding based on the kind of bindings.
3500 if (isBetterReferenceBindingKind(SCS1, SCS2))
3501 return ImplicitConversionSequence::Better;
3502 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3503 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003504
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003505 // C++ [over.ics.rank]p3b4:
3506 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3507 // which the references refer are the same type except for
3508 // top-level cv-qualifiers, and the type to which the reference
3509 // initialized by S2 refers is more cv-qualified than the type
3510 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003511 QualType T1 = SCS1.getToType(2);
3512 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003513 T1 = S.Context.getCanonicalType(T1);
3514 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003515 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003516 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3517 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003518 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003519 // Objective-C++ ARC: If the references refer to objects with different
3520 // lifetimes, prefer bindings that don't change lifetime.
3521 if (SCS1.ObjCLifetimeConversionBinding !=
3522 SCS2.ObjCLifetimeConversionBinding) {
3523 return SCS1.ObjCLifetimeConversionBinding
3524 ? ImplicitConversionSequence::Worse
3525 : ImplicitConversionSequence::Better;
3526 }
3527
Chandler Carruth6df868e2010-12-12 08:17:55 +00003528 // If the type is an array type, promote the element qualifiers to the
3529 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003530 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003531 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003532 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003533 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003534 if (T2.isMoreQualifiedThan(T1))
3535 return ImplicitConversionSequence::Better;
3536 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003537 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003538 }
3539 }
Douglas Gregor57373262008-10-22 14:17:15 +00003540
Francois Pichet1c98d622011-09-18 21:37:37 +00003541 // In Microsoft mode, prefer an integral conversion to a
3542 // floating-to-integral conversion if the integral conversion
3543 // is between types of the same size.
3544 // For example:
3545 // void f(float);
3546 // void f(int);
3547 // int main {
3548 // long a;
3549 // f(a);
3550 // }
3551 // Here, MSVC will call f(int) instead of generating a compile error
3552 // as clang will do in standard mode.
David Blaikie4e4d0842012-03-11 07:00:24 +00003553 if (S.getLangOpts().MicrosoftMode &&
Francois Pichet1c98d622011-09-18 21:37:37 +00003554 SCS1.Second == ICK_Integral_Conversion &&
3555 SCS2.Second == ICK_Floating_Integral &&
3556 S.Context.getTypeSize(SCS1.getFromType()) ==
3557 S.Context.getTypeSize(SCS1.getToType(2)))
3558 return ImplicitConversionSequence::Better;
3559
Douglas Gregor57373262008-10-22 14:17:15 +00003560 return ImplicitConversionSequence::Indistinguishable;
3561}
3562
3563/// CompareQualificationConversions - Compares two standard conversion
3564/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003565/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3566ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003567CompareQualificationConversions(Sema &S,
3568 const StandardConversionSequence& SCS1,
3569 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003570 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003571 // -- S1 and S2 differ only in their qualification conversion and
3572 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3573 // cv-qualification signature of type T1 is a proper subset of
3574 // the cv-qualification signature of type T2, and S1 is not the
3575 // deprecated string literal array-to-pointer conversion (4.2).
3576 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3577 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3578 return ImplicitConversionSequence::Indistinguishable;
3579
3580 // FIXME: the example in the standard doesn't use a qualification
3581 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003582 QualType T1 = SCS1.getToType(2);
3583 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003584 T1 = S.Context.getCanonicalType(T1);
3585 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003586 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003587 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3588 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003589
3590 // If the types are the same, we won't learn anything by unwrapped
3591 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003592 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003593 return ImplicitConversionSequence::Indistinguishable;
3594
Chandler Carruth28e318c2009-12-29 07:16:59 +00003595 // If the type is an array type, promote the element qualifiers to the type
3596 // for comparison.
3597 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003598 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003599 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003600 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003601
Mike Stump1eb44332009-09-09 15:08:12 +00003602 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003603 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003604
3605 // Objective-C++ ARC:
3606 // Prefer qualification conversions not involving a change in lifetime
3607 // to qualification conversions that do not change lifetime.
3608 if (SCS1.QualificationIncludesObjCLifetime !=
3609 SCS2.QualificationIncludesObjCLifetime) {
3610 Result = SCS1.QualificationIncludesObjCLifetime
3611 ? ImplicitConversionSequence::Worse
3612 : ImplicitConversionSequence::Better;
3613 }
3614
John McCall120d63c2010-08-24 20:38:10 +00003615 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003616 // Within each iteration of the loop, we check the qualifiers to
3617 // determine if this still looks like a qualification
3618 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003619 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003620 // until there are no more pointers or pointers-to-members left
3621 // to unwrap. This essentially mimics what
3622 // IsQualificationConversion does, but here we're checking for a
3623 // strict subset of qualifiers.
3624 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3625 // The qualifiers are the same, so this doesn't tell us anything
3626 // about how the sequences rank.
3627 ;
3628 else if (T2.isMoreQualifiedThan(T1)) {
3629 // T1 has fewer qualifiers, so it could be the better sequence.
3630 if (Result == ImplicitConversionSequence::Worse)
3631 // Neither has qualifiers that are a subset of the other's
3632 // qualifiers.
3633 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Douglas Gregor57373262008-10-22 14:17:15 +00003635 Result = ImplicitConversionSequence::Better;
3636 } else if (T1.isMoreQualifiedThan(T2)) {
3637 // T2 has fewer qualifiers, so it could be the better sequence.
3638 if (Result == ImplicitConversionSequence::Better)
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::Worse;
3644 } else {
3645 // Qualifiers are disjoint.
3646 return ImplicitConversionSequence::Indistinguishable;
3647 }
3648
3649 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003650 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003651 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003652 }
3653
Douglas Gregor57373262008-10-22 14:17:15 +00003654 // Check that the winning standard conversion sequence isn't using
3655 // the deprecated string literal array to pointer conversion.
3656 switch (Result) {
3657 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003658 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003659 Result = ImplicitConversionSequence::Indistinguishable;
3660 break;
3661
3662 case ImplicitConversionSequence::Indistinguishable:
3663 break;
3664
3665 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003666 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003667 Result = ImplicitConversionSequence::Indistinguishable;
3668 break;
3669 }
3670
3671 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003672}
3673
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003674/// CompareDerivedToBaseConversions - Compares two standard conversion
3675/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003676/// various kinds of derived-to-base conversions (C++
3677/// [over.ics.rank]p4b3). As part of these checks, we also look at
3678/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003679ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003680CompareDerivedToBaseConversions(Sema &S,
3681 const StandardConversionSequence& SCS1,
3682 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003683 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003684 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003685 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003686 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003687
3688 // Adjust the types we're converting from via the array-to-pointer
3689 // conversion, if we need to.
3690 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003691 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003692 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003693 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003694
3695 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003696 FromType1 = S.Context.getCanonicalType(FromType1);
3697 ToType1 = S.Context.getCanonicalType(ToType1);
3698 FromType2 = S.Context.getCanonicalType(FromType2);
3699 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003700
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003701 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003702 //
3703 // If class B is derived directly or indirectly from class A and
3704 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003705 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003706 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003707 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003708 SCS2.Second == ICK_Pointer_Conversion &&
3709 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3710 FromType1->isPointerType() && FromType2->isPointerType() &&
3711 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003712 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003713 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003714 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003715 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003716 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003717 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003718 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003719 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003720
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003721 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003722 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003723 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003724 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003725 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003726 return ImplicitConversionSequence::Worse;
3727 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003728
3729 // -- conversion of B* to A* is better than conversion of C* to A*,
3730 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003731 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003732 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003733 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003734 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003735 }
3736 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3737 SCS2.Second == ICK_Pointer_Conversion) {
3738 const ObjCObjectPointerType *FromPtr1
3739 = FromType1->getAs<ObjCObjectPointerType>();
3740 const ObjCObjectPointerType *FromPtr2
3741 = FromType2->getAs<ObjCObjectPointerType>();
3742 const ObjCObjectPointerType *ToPtr1
3743 = ToType1->getAs<ObjCObjectPointerType>();
3744 const ObjCObjectPointerType *ToPtr2
3745 = ToType2->getAs<ObjCObjectPointerType>();
3746
3747 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3748 // Apply the same conversion ranking rules for Objective-C pointer types
3749 // that we do for C++ pointers to class types. However, we employ the
3750 // Objective-C pseudo-subtyping relationship used for assignment of
3751 // Objective-C pointer types.
3752 bool FromAssignLeft
3753 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3754 bool FromAssignRight
3755 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3756 bool ToAssignLeft
3757 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3758 bool ToAssignRight
3759 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3760
3761 // A conversion to an a non-id object pointer type or qualified 'id'
3762 // type is better than a conversion to 'id'.
3763 if (ToPtr1->isObjCIdType() &&
3764 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3765 return ImplicitConversionSequence::Worse;
3766 if (ToPtr2->isObjCIdType() &&
3767 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3768 return ImplicitConversionSequence::Better;
3769
3770 // A conversion to a non-id object pointer type is better than a
3771 // conversion to a qualified 'id' type
3772 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3773 return ImplicitConversionSequence::Worse;
3774 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3775 return ImplicitConversionSequence::Better;
3776
3777 // A conversion to an a non-Class object pointer type or qualified 'Class'
3778 // type is better than a conversion to 'Class'.
3779 if (ToPtr1->isObjCClassType() &&
3780 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3781 return ImplicitConversionSequence::Worse;
3782 if (ToPtr2->isObjCClassType() &&
3783 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3784 return ImplicitConversionSequence::Better;
3785
3786 // A conversion to a non-Class object pointer type is better than a
3787 // conversion to a qualified 'Class' type.
3788 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3789 return ImplicitConversionSequence::Worse;
3790 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3791 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Douglas Gregor395cc372011-01-31 18:51:41 +00003793 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3794 if (S.Context.hasSameType(FromType1, FromType2) &&
3795 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3796 (ToAssignLeft != ToAssignRight))
3797 return ToAssignLeft? ImplicitConversionSequence::Worse
3798 : ImplicitConversionSequence::Better;
3799
3800 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3801 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3802 (FromAssignLeft != FromAssignRight))
3803 return FromAssignLeft? ImplicitConversionSequence::Better
3804 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003805 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003806 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003807
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003808 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003809 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3810 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3811 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003812 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003813 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003814 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003815 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003816 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003817 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003818 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003819 ToType2->getAs<MemberPointerType>();
3820 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3821 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3822 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3823 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3824 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3825 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3826 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3827 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003828 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003829 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003830 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003831 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003832 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003833 return ImplicitConversionSequence::Better;
3834 }
3835 // conversion of B::* to C::* is better than conversion of A::* to C::*
3836 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003837 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003838 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003839 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003840 return ImplicitConversionSequence::Worse;
3841 }
3842 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003843
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003844 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003845 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003846 // -- binding of an expression of type C to a reference of type
3847 // B& is better than binding an expression of type C to a
3848 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003849 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3850 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3851 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003852 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003853 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003854 return ImplicitConversionSequence::Worse;
3855 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003856
Douglas Gregor225c41e2008-11-03 19:09:14 +00003857 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003858 // -- binding of an expression of type B to a reference of type
3859 // A& is better than binding an expression of type C to a
3860 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003861 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3862 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3863 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003864 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003865 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003866 return ImplicitConversionSequence::Worse;
3867 }
3868 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003869
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003870 return ImplicitConversionSequence::Indistinguishable;
3871}
3872
Douglas Gregorabe183d2010-04-13 16:31:36 +00003873/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3874/// determine whether they are reference-related,
3875/// reference-compatible, reference-compatible with added
3876/// qualification, or incompatible, for use in C++ initialization by
3877/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3878/// type, and the first type (T1) is the pointee type of the reference
3879/// type being initialized.
3880Sema::ReferenceCompareResult
3881Sema::CompareReferenceRelationship(SourceLocation Loc,
3882 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003883 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003884 bool &ObjCConversion,
3885 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003886 assert(!OrigT1->isReferenceType() &&
3887 "T1 must be the pointee type of the reference type");
3888 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3889
3890 QualType T1 = Context.getCanonicalType(OrigT1);
3891 QualType T2 = Context.getCanonicalType(OrigT2);
3892 Qualifiers T1Quals, T2Quals;
3893 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3894 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3895
3896 // C++ [dcl.init.ref]p4:
3897 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3898 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3899 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003900 DerivedToBase = false;
3901 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003902 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003903 if (UnqualT1 == UnqualT2) {
3904 // Nothing to do.
Douglas Gregord10099e2012-05-04 16:32:21 +00003905 } else if (!RequireCompleteType(Loc, OrigT2, 0) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003906 IsDerivedFrom(UnqualT2, UnqualT1))
3907 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003908 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3909 UnqualT2->isObjCObjectOrInterfaceType() &&
3910 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3911 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003912 else
3913 return Ref_Incompatible;
3914
3915 // At this point, we know that T1 and T2 are reference-related (at
3916 // least).
3917
3918 // If the type is an array type, promote the element qualifiers to the type
3919 // for comparison.
3920 if (isa<ArrayType>(T1) && T1Quals)
3921 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3922 if (isa<ArrayType>(T2) && T2Quals)
3923 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3924
3925 // C++ [dcl.init.ref]p4:
3926 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3927 // reference-related to T2 and cv1 is the same cv-qualification
3928 // as, or greater cv-qualification than, cv2. For purposes of
3929 // overload resolution, cases for which cv1 is greater
3930 // cv-qualification than cv2 are identified as
3931 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003932 //
3933 // Note that we also require equivalence of Objective-C GC and address-space
3934 // qualifiers when performing these computations, so that e.g., an int in
3935 // address space 1 is not reference-compatible with an int in address
3936 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003937 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3938 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3939 T1Quals.removeObjCLifetime();
3940 T2Quals.removeObjCLifetime();
3941 ObjCLifetimeConversion = true;
3942 }
3943
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003944 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003945 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003946 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003947 return Ref_Compatible_With_Added_Qualification;
3948 else
3949 return Ref_Related;
3950}
3951
Douglas Gregor604eb652010-08-11 02:15:33 +00003952/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003953/// with DeclType. Return true if something definite is found.
3954static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003955FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3956 QualType DeclType, SourceLocation DeclLoc,
3957 Expr *Init, QualType T2, bool AllowRvalues,
3958 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003959 assert(T2->isRecordType() && "Can only find conversions of record types.");
3960 CXXRecordDecl *T2RecordDecl
3961 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3962
3963 OverloadCandidateSet CandidateSet(DeclLoc);
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00003964 std::pair<CXXRecordDecl::conversion_iterator,
3965 CXXRecordDecl::conversion_iterator>
3966 Conversions = T2RecordDecl->getVisibleConversionFunctions();
3967 for (CXXRecordDecl::conversion_iterator
3968 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003969 NamedDecl *D = *I;
3970 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3971 if (isa<UsingShadowDecl>(D))
3972 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3973
3974 FunctionTemplateDecl *ConvTemplate
3975 = dyn_cast<FunctionTemplateDecl>(D);
3976 CXXConversionDecl *Conv;
3977 if (ConvTemplate)
3978 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3979 else
3980 Conv = cast<CXXConversionDecl>(D);
3981
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003982 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003983 // explicit conversions, skip it.
3984 if (!AllowExplicit && Conv->isExplicit())
3985 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003986
Douglas Gregor604eb652010-08-11 02:15:33 +00003987 if (AllowRvalues) {
3988 bool DerivedToBase = false;
3989 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003990 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003991
3992 // If we are initializing an rvalue reference, don't permit conversion
3993 // functions that return lvalues.
3994 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3995 const ReferenceType *RefType
3996 = Conv->getConversionType()->getAs<LValueReferenceType>();
3997 if (RefType && !RefType->getPointeeType()->isFunctionType())
3998 continue;
3999 }
4000
Douglas Gregor604eb652010-08-11 02:15:33 +00004001 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00004002 S.CompareReferenceRelationship(
4003 DeclLoc,
4004 Conv->getConversionType().getNonReferenceType()
4005 .getUnqualifiedType(),
4006 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00004007 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00004008 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00004009 continue;
4010 } else {
4011 // If the conversion function doesn't return a reference type,
4012 // it can't be considered for this conversion. An rvalue reference
4013 // is only acceptable if its referencee is a function type.
4014
4015 const ReferenceType *RefType =
4016 Conv->getConversionType()->getAs<ReferenceType>();
4017 if (!RefType ||
4018 (!RefType->isLValueReferenceType() &&
4019 !RefType->getPointeeType()->isFunctionType()))
4020 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004021 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004022
Douglas Gregor604eb652010-08-11 02:15:33 +00004023 if (ConvTemplate)
4024 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004025 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00004026 else
4027 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004028 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00004029 }
4030
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004031 bool HadMultipleCandidates = (CandidateSet.size() > 1);
4032
Sebastian Redl4680bf22010-06-30 18:13:39 +00004033 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00004034 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004035 case OR_Success:
4036 // C++ [over.ics.ref]p1:
4037 //
4038 // [...] If the parameter binds directly to the result of
4039 // applying a conversion function to the argument
4040 // expression, the implicit conversion sequence is a
4041 // user-defined conversion sequence (13.3.3.1.2), with the
4042 // second standard conversion sequence either an identity
4043 // conversion or, if the conversion function returns an
4044 // entity of a type that is a derived class of the parameter
4045 // type, a derived-to-base Conversion.
4046 if (!Best->FinalConversion.DirectBinding)
4047 return false;
4048
4049 ICS.setUserDefined();
4050 ICS.UserDefined.Before = Best->Conversions[0].Standard;
4051 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004052 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004053 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00004054 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004055 ICS.UserDefined.EllipsisConversion = false;
4056 assert(ICS.UserDefined.After.ReferenceBinding &&
4057 ICS.UserDefined.After.DirectBinding &&
4058 "Expected a direct reference binding!");
4059 return true;
4060
4061 case OR_Ambiguous:
4062 ICS.setAmbiguous();
4063 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4064 Cand != CandidateSet.end(); ++Cand)
4065 if (Cand->Viable)
4066 ICS.Ambiguous.addConversion(Cand->Function);
4067 return true;
4068
4069 case OR_No_Viable_Function:
4070 case OR_Deleted:
4071 // There was no suitable conversion, or we found a deleted
4072 // conversion; continue with other checks.
4073 return false;
4074 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004075
David Blaikie7530c032012-01-17 06:56:22 +00004076 llvm_unreachable("Invalid OverloadResult!");
Sebastian Redl4680bf22010-06-30 18:13:39 +00004077}
4078
Douglas Gregorabe183d2010-04-13 16:31:36 +00004079/// \brief Compute an implicit conversion sequence for reference
4080/// initialization.
4081static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004082TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004083 SourceLocation DeclLoc,
4084 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004085 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004086 assert(DeclType->isReferenceType() && "Reference init needs a reference");
4087
4088 // Most paths end in a failed conversion.
4089 ImplicitConversionSequence ICS;
4090 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4091
4092 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
4093 QualType T2 = Init->getType();
4094
4095 // If the initializer is the address of an overloaded function, try
4096 // to resolve the overloaded function. If all goes well, T2 is the
4097 // type of the resulting function.
4098 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4099 DeclAccessPair Found;
4100 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
4101 false, Found))
4102 T2 = Fn->getType();
4103 }
4104
4105 // Compute some basic properties of the types and the initializer.
4106 bool isRValRef = DeclType->isRValueReferenceType();
4107 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00004108 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00004109 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004110 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004111 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00004112 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00004113 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004114
Douglas Gregorabe183d2010-04-13 16:31:36 +00004115
Sebastian Redl4680bf22010-06-30 18:13:39 +00004116 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00004117 // A reference to type "cv1 T1" is initialized by an expression
4118 // of type "cv2 T2" as follows:
4119
Sebastian Redl4680bf22010-06-30 18:13:39 +00004120 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004121 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00004122 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
4123 // reference-compatible with "cv2 T2," or
4124 //
4125 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
4126 if (InitCategory.isLValue() &&
4127 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00004128 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00004129 // When a parameter of reference type binds directly (8.5.3)
4130 // to an argument expression, the implicit conversion sequence
4131 // is the identity conversion, unless the argument expression
4132 // has a type that is a derived class of the parameter type,
4133 // in which case the implicit conversion sequence is a
4134 // derived-to-base Conversion (13.3.3.1).
4135 ICS.setStandard();
4136 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00004137 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
4138 : ObjCConversion? ICK_Compatible_Conversion
4139 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004140 ICS.Standard.Third = ICK_Identity;
4141 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4142 ICS.Standard.setToType(0, T2);
4143 ICS.Standard.setToType(1, T1);
4144 ICS.Standard.setToType(2, T1);
4145 ICS.Standard.ReferenceBinding = true;
4146 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004147 ICS.Standard.IsLvalueReference = !isRValRef;
4148 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4149 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004150 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004151 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004152 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004153
Sebastian Redl4680bf22010-06-30 18:13:39 +00004154 // Nothing more to do: the inaccessibility/ambiguity check for
4155 // derived-to-base conversions is suppressed when we're
4156 // computing the implicit conversion sequence (C++
4157 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00004158 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00004159 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00004160
Sebastian Redl4680bf22010-06-30 18:13:39 +00004161 // -- has a class type (i.e., T2 is a class type), where T1 is
4162 // not reference-related to T2, and can be implicitly
4163 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
4164 // is reference-compatible with "cv3 T3" 92) (this
4165 // conversion is selected by enumerating the applicable
4166 // conversion functions (13.3.1.6) and choosing the best
4167 // one through overload resolution (13.3)),
4168 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004169 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00004170 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00004171 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4172 Init, T2, /*AllowRvalues=*/false,
4173 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00004174 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004175 }
4176 }
4177
Sebastian Redl4680bf22010-06-30 18:13:39 +00004178 // -- Otherwise, the reference shall be an lvalue reference to a
4179 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004180 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004181 //
Douglas Gregor66821b52010-04-18 09:22:00 +00004182 // We actually handle one oddity of C++ [over.ics.ref] at this
4183 // point, which is that, due to p2 (which short-circuits reference
4184 // binding by only attempting a simple conversion for non-direct
4185 // bindings) and p3's strange wording, we allow a const volatile
4186 // reference to bind to an rvalue. Hence the check for the presence
4187 // of "const" rather than checking for "const" being the only
4188 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00004189 // This is also the point where rvalue references and lvalue inits no longer
4190 // go together.
Richard Smith8ab10aa2012-05-24 04:29:20 +00004191 if (!isRValRef && (!T1.isConstQualified() || T1.isVolatileQualified()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00004192 return ICS;
4193
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004194 // -- If the initializer expression
4195 //
4196 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00004197 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004198 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
4199 (InitCategory.isXValue() ||
4200 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
4201 (InitCategory.isLValue() && T2->isFunctionType()))) {
4202 ICS.setStandard();
4203 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004204 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004205 : ObjCConversion? ICK_Compatible_Conversion
4206 : ICK_Identity;
4207 ICS.Standard.Third = ICK_Identity;
4208 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
4209 ICS.Standard.setToType(0, T2);
4210 ICS.Standard.setToType(1, T1);
4211 ICS.Standard.setToType(2, T1);
4212 ICS.Standard.ReferenceBinding = true;
4213 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
4214 // binding unless we're binding to a class prvalue.
4215 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
4216 // allow the use of rvalue references in C++98/03 for the benefit of
4217 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004218 ICS.Standard.DirectBinding =
David Blaikie4e4d0842012-03-11 07:00:24 +00004219 S.getLangOpts().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004220 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00004221 ICS.Standard.IsLvalueReference = !isRValRef;
4222 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004224 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004225 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004226 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004227 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004228 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004229
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004230 // -- has a class type (i.e., T2 is a class type), where T1 is not
4231 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004232 // an xvalue, class prvalue, or function lvalue of type
4233 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004234 // "cv3 T3",
4235 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004236 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004237 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004238 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004239 // class subobject).
4240 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004241 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004242 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
4243 Init, T2, /*AllowRvalues=*/true,
4244 AllowExplicit)) {
4245 // In the second case, if the reference is an rvalue reference
4246 // and the second standard conversion sequence of the
4247 // user-defined conversion sequence includes an lvalue-to-rvalue
4248 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004249 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00004250 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
4251 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
4252
Douglas Gregor68ed68b2011-01-21 16:36:05 +00004253 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00004254 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004255
Douglas Gregorabe183d2010-04-13 16:31:36 +00004256 // -- Otherwise, a temporary of type "cv1 T1" is created and
4257 // initialized from the initializer expression using the
4258 // rules for a non-reference copy initialization (8.5). The
4259 // reference is then bound to the temporary. If T1 is
4260 // reference-related to T2, cv1 must be the same
4261 // cv-qualification as, or greater cv-qualification than,
4262 // cv2; otherwise, the program is ill-formed.
4263 if (RefRelationship == Sema::Ref_Related) {
4264 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
4265 // we would be reference-compatible or reference-compatible with
4266 // added qualification. But that wasn't the case, so the reference
4267 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00004268 //
4269 // Note that we only want to check address spaces and cvr-qualifiers here.
4270 // ObjC GC and lifetime qualifiers aren't important.
4271 Qualifiers T1Quals = T1.getQualifiers();
4272 Qualifiers T2Quals = T2.getQualifiers();
4273 T1Quals.removeObjCGCAttr();
4274 T1Quals.removeObjCLifetime();
4275 T2Quals.removeObjCGCAttr();
4276 T2Quals.removeObjCLifetime();
4277 if (!T1Quals.compatiblyIncludes(T2Quals))
4278 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004279 }
4280
4281 // If at least one of the types is a class type, the types are not
4282 // related, and we aren't allowed any user conversions, the
4283 // reference binding fails. This case is important for breaking
4284 // recursion, since TryImplicitConversion below will attempt to
4285 // create a temporary through the use of a copy constructor.
4286 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
4287 (T1->isRecordType() || T2->isRecordType()))
4288 return ICS;
4289
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004290 // If T1 is reference-related to T2 and the reference is an rvalue
4291 // reference, the initializer expression shall not be an lvalue.
4292 if (RefRelationship >= Sema::Ref_Related &&
4293 isRValRef && Init->Classify(S.Context).isLValue())
4294 return ICS;
4295
Douglas Gregorabe183d2010-04-13 16:31:36 +00004296 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00004297 // When a parameter of reference type is not bound directly to
4298 // an argument expression, the conversion sequence is the one
4299 // required to convert the argument expression to the
4300 // underlying type of the reference according to
4301 // 13.3.3.1. Conceptually, this conversion sequence corresponds
4302 // to copy-initializing a temporary of the underlying type with
4303 // the argument expression. Any difference in top-level
4304 // cv-qualification is subsumed by the initialization itself
4305 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00004306 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
4307 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004308 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004309 /*CStyle=*/false,
4310 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004311
4312 // Of course, that's still a reference binding.
4313 if (ICS.isStandard()) {
4314 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00004315 ICS.Standard.IsLvalueReference = !isRValRef;
4316 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
4317 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004318 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00004319 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004320 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00004321 // Don't allow rvalue references to bind to lvalues.
4322 if (DeclType->isRValueReferenceType()) {
4323 if (const ReferenceType *RefType
4324 = ICS.UserDefined.ConversionFunction->getResultType()
4325 ->getAs<LValueReferenceType>()) {
4326 if (!RefType->getPointeeType()->isFunctionType()) {
4327 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
4328 DeclType);
4329 return ICS;
4330 }
4331 }
4332 }
4333
Douglas Gregorabe183d2010-04-13 16:31:36 +00004334 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00004335 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
4336 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
4337 ICS.UserDefined.After.BindsToRvalue = true;
4338 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4339 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00004340 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004341
Douglas Gregorabe183d2010-04-13 16:31:36 +00004342 return ICS;
4343}
4344
Sebastian Redl5405b812011-10-16 18:19:34 +00004345static ImplicitConversionSequence
4346TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
4347 bool SuppressUserConversions,
4348 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004349 bool AllowObjCWritebackConversion,
4350 bool AllowExplicit = false);
Sebastian Redl5405b812011-10-16 18:19:34 +00004351
4352/// TryListConversion - Try to copy-initialize a value of type ToType from the
4353/// initializer list From.
4354static ImplicitConversionSequence
4355TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
4356 bool SuppressUserConversions,
4357 bool InOverloadResolution,
4358 bool AllowObjCWritebackConversion) {
4359 // C++11 [over.ics.list]p1:
4360 // When an argument is an initializer list, it is not an expression and
4361 // special rules apply for converting it to a parameter type.
4362
4363 ImplicitConversionSequence Result;
4364 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004365 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004366
Sebastian Redlb832f6d2012-01-23 22:09:39 +00004367 // We need a complete type for what follows. Incomplete types can never be
Sebastian Redlfe592282012-01-17 22:49:48 +00004368 // initialized from init lists.
Douglas Gregord10099e2012-05-04 16:32:21 +00004369 if (S.RequireCompleteType(From->getLocStart(), ToType, 0))
Sebastian Redlfe592282012-01-17 22:49:48 +00004370 return Result;
4371
Sebastian Redl5405b812011-10-16 18:19:34 +00004372 // C++11 [over.ics.list]p2:
4373 // If the parameter type is std::initializer_list<X> or "array of X" and
4374 // all the elements can be implicitly converted to X, the implicit
4375 // conversion sequence is the worst conversion necessary to convert an
4376 // element of the list to X.
Sebastian Redladfb5352012-02-27 22:38:26 +00004377 bool toStdInitializerList = false;
Sebastian Redlfe592282012-01-17 22:49:48 +00004378 QualType X;
Sebastian Redl5405b812011-10-16 18:19:34 +00004379 if (ToType->isArrayType())
Richard Smith2801d9a2012-12-09 06:48:56 +00004380 X = S.Context.getAsArrayType(ToType)->getElementType();
Sebastian Redlfe592282012-01-17 22:49:48 +00004381 else
Sebastian Redladfb5352012-02-27 22:38:26 +00004382 toStdInitializerList = S.isStdInitializerList(ToType, &X);
Sebastian Redlfe592282012-01-17 22:49:48 +00004383 if (!X.isNull()) {
4384 for (unsigned i = 0, e = From->getNumInits(); i < e; ++i) {
4385 Expr *Init = From->getInit(i);
4386 ImplicitConversionSequence ICS =
4387 TryCopyInitialization(S, Init, X, SuppressUserConversions,
4388 InOverloadResolution,
4389 AllowObjCWritebackConversion);
4390 // If a single element isn't convertible, fail.
4391 if (ICS.isBad()) {
4392 Result = ICS;
4393 break;
4394 }
4395 // Otherwise, look for the worst conversion.
4396 if (Result.isBad() ||
4397 CompareImplicitConversionSequences(S, ICS, Result) ==
4398 ImplicitConversionSequence::Worse)
4399 Result = ICS;
4400 }
Douglas Gregor5b4bf132012-04-04 23:09:20 +00004401
4402 // For an empty list, we won't have computed any conversion sequence.
4403 // Introduce the identity conversion sequence.
4404 if (From->getNumInits() == 0) {
4405 Result.setStandard();
4406 Result.Standard.setAsIdentityConversion();
4407 Result.Standard.setFromType(ToType);
4408 Result.Standard.setAllToTypes(ToType);
4409 }
4410
Sebastian Redlfe592282012-01-17 22:49:48 +00004411 Result.setListInitializationSequence();
Sebastian Redladfb5352012-02-27 22:38:26 +00004412 Result.setStdInitializerListElement(toStdInitializerList);
Sebastian Redl5405b812011-10-16 18:19:34 +00004413 return Result;
Sebastian Redlfe592282012-01-17 22:49:48 +00004414 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004415
4416 // C++11 [over.ics.list]p3:
4417 // Otherwise, if the parameter is a non-aggregate class X and overload
4418 // resolution chooses a single best constructor [...] the implicit
4419 // conversion sequence is a user-defined conversion sequence. If multiple
4420 // constructors are viable but none is better than the others, the
4421 // implicit conversion sequence is a user-defined conversion sequence.
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004422 if (ToType->isRecordType() && !ToType->isAggregateType()) {
4423 // This function can deal with initializer lists.
4424 Result = TryUserDefinedConversion(S, From, ToType, SuppressUserConversions,
4425 /*AllowExplicit=*/false,
4426 InOverloadResolution, /*CStyle=*/false,
4427 AllowObjCWritebackConversion);
4428 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004429 return Result;
Sebastian Redlcf15cef2011-12-22 18:58:38 +00004430 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004431
4432 // C++11 [over.ics.list]p4:
4433 // Otherwise, if the parameter has an aggregate type which can be
4434 // initialized from the initializer list [...] the implicit conversion
4435 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00004436 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004437 // Type is an aggregate, argument is an init list. At this point it comes
4438 // down to checking whether the initialization works.
4439 // FIXME: Find out whether this parameter is consumed or not.
4440 InitializedEntity Entity =
4441 InitializedEntity::InitializeParameter(S.Context, ToType,
4442 /*Consumed=*/false);
4443 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
4444 Result.setUserDefined();
4445 Result.UserDefined.Before.setAsIdentityConversion();
4446 // Initializer lists don't have a type.
4447 Result.UserDefined.Before.setFromType(QualType());
4448 Result.UserDefined.Before.setAllToTypes(QualType());
4449
4450 Result.UserDefined.After.setAsIdentityConversion();
4451 Result.UserDefined.After.setFromType(ToType);
4452 Result.UserDefined.After.setAllToTypes(ToType);
Benjamin Kramer83db10e2012-02-02 19:35:29 +00004453 Result.UserDefined.ConversionFunction = 0;
Sebastian Redlcc7a6482011-11-01 15:53:09 +00004454 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004455 return Result;
4456 }
4457
4458 // C++11 [over.ics.list]p5:
4459 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004460 if (ToType->isReferenceType()) {
4461 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
4462 // mention initializer lists in any way. So we go by what list-
4463 // initialization would do and try to extrapolate from that.
4464
4465 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
4466
4467 // If the initializer list has a single element that is reference-related
4468 // to the parameter type, we initialize the reference from that.
4469 if (From->getNumInits() == 1) {
4470 Expr *Init = From->getInit(0);
4471
4472 QualType T2 = Init->getType();
4473
4474 // If the initializer is the address of an overloaded function, try
4475 // to resolve the overloaded function. If all goes well, T2 is the
4476 // type of the resulting function.
4477 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
4478 DeclAccessPair Found;
4479 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
4480 Init, ToType, false, Found))
4481 T2 = Fn->getType();
4482 }
4483
4484 // Compute some basic properties of the types and the initializer.
4485 bool dummy1 = false;
4486 bool dummy2 = false;
4487 bool dummy3 = false;
4488 Sema::ReferenceCompareResult RefRelationship
4489 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
4490 dummy2, dummy3);
4491
4492 if (RefRelationship >= Sema::Ref_Related)
4493 return TryReferenceInit(S, Init, ToType,
4494 /*FIXME:*/From->getLocStart(),
4495 SuppressUserConversions,
4496 /*AllowExplicit=*/false);
4497 }
4498
4499 // Otherwise, we bind the reference to a temporary created from the
4500 // initializer list.
4501 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4502 InOverloadResolution,
4503 AllowObjCWritebackConversion);
4504 if (Result.isFailure())
4505 return Result;
4506 assert(!Result.isEllipsis() &&
4507 "Sub-initialization cannot result in ellipsis conversion.");
4508
4509 // Can we even bind to a temporary?
4510 if (ToType->isRValueReferenceType() ||
4511 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4512 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4513 Result.UserDefined.After;
4514 SCS.ReferenceBinding = true;
4515 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4516 SCS.BindsToRvalue = true;
4517 SCS.BindsToFunctionLvalue = false;
4518 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4519 SCS.ObjCLifetimeConversionBinding = false;
4520 } else
4521 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4522 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004523 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004524 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004525
4526 // C++11 [over.ics.list]p6:
4527 // Otherwise, if the parameter type is not a class:
4528 if (!ToType->isRecordType()) {
4529 // - if the initializer list has one element, the implicit conversion
4530 // sequence is the one required to convert the element to the
4531 // parameter type.
Sebastian Redl5405b812011-10-16 18:19:34 +00004532 unsigned NumInits = From->getNumInits();
4533 if (NumInits == 1)
4534 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4535 SuppressUserConversions,
4536 InOverloadResolution,
4537 AllowObjCWritebackConversion);
4538 // - if the initializer list has no elements, the implicit conversion
4539 // sequence is the identity conversion.
4540 else if (NumInits == 0) {
4541 Result.setStandard();
4542 Result.Standard.setAsIdentityConversion();
John McCalle14ba2c2012-04-04 02:40:27 +00004543 Result.Standard.setFromType(ToType);
4544 Result.Standard.setAllToTypes(ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004545 }
Sebastian Redl2422e822012-02-28 23:36:38 +00004546 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00004547 return Result;
4548 }
4549
4550 // C++11 [over.ics.list]p7:
4551 // In all cases other than those enumerated above, no conversion is possible
4552 return Result;
4553}
4554
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004555/// TryCopyInitialization - Try to copy-initialize a value of type
4556/// ToType from the expression From. Return the implicit conversion
4557/// sequence required to pass this argument, which may be a bad
4558/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004559/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004560/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004561static ImplicitConversionSequence
4562TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004563 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004564 bool InOverloadResolution,
Douglas Gregored878af2012-02-24 23:56:31 +00004565 bool AllowObjCWritebackConversion,
4566 bool AllowExplicit) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004567 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4568 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4569 InOverloadResolution,AllowObjCWritebackConversion);
4570
Douglas Gregorabe183d2010-04-13 16:31:36 +00004571 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004572 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004573 /*FIXME:*/From->getLocStart(),
4574 SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00004575 AllowExplicit);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004576
John McCall120d63c2010-08-24 20:38:10 +00004577 return TryImplicitConversion(S, From, ToType,
4578 SuppressUserConversions,
4579 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004580 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004581 /*CStyle=*/false,
4582 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004583}
4584
Anna Zaksf3546ee2011-07-28 19:46:48 +00004585static bool TryCopyInitialization(const CanQualType FromQTy,
4586 const CanQualType ToQTy,
4587 Sema &S,
4588 SourceLocation Loc,
4589 ExprValueKind FromVK) {
4590 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4591 ImplicitConversionSequence ICS =
4592 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4593
4594 return !ICS.isBad();
4595}
4596
Douglas Gregor96176b32008-11-18 23:14:02 +00004597/// TryObjectArgumentInitialization - Try to initialize the object
4598/// parameter of the given member function (@c Method) from the
4599/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004600static ImplicitConversionSequence
4601TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004602 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004603 CXXMethodDecl *Method,
4604 CXXRecordDecl *ActingContext) {
4605 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004606 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4607 // const volatile object.
4608 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4609 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004610 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004611
4612 // Set up the conversion sequence as a "bad" conversion, to allow us
4613 // to exit early.
4614 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004615
4616 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004617 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004618 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004619 FromType = PT->getPointeeType();
4620
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004621 // When we had a pointer, it's implicitly dereferenced, so we
4622 // better have an lvalue.
4623 assert(FromClassification.isLValue());
4624 }
4625
Anders Carlssona552f7c2009-05-01 18:34:30 +00004626 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004627
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004628 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004629 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004630 // parameter is
4631 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004632 // - "lvalue reference to cv X" for functions declared without a
4633 // ref-qualifier or with the & ref-qualifier
4634 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004635 // ref-qualifier
4636 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004637 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004638 // cv-qualification on the member function declaration.
4639 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004640 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004641 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004642 // (C++ [over.match.funcs]p5). We perform a simplified version of
4643 // reference binding here, that allows class rvalues to bind to
4644 // non-constant references.
4645
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004646 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004647 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004648 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004649 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004650 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004651 ICS.setBad(BadConversionSequence::bad_qualifiers,
4652 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004653 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004654 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004655
4656 // Check that we have either the same type or a derived type. It
4657 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004658 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004659 ImplicitConversionKind SecondKind;
4660 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4661 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004662 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004663 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004664 else {
John McCallb1bdc622010-02-25 01:37:24 +00004665 ICS.setBad(BadConversionSequence::unrelated_class,
4666 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004667 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004668 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004669
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004670 // Check the ref-qualifier.
4671 switch (Method->getRefQualifier()) {
4672 case RQ_None:
4673 // Do nothing; we don't care about lvalueness or rvalueness.
4674 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004675
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004676 case RQ_LValue:
4677 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4678 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004679 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004680 ImplicitParamType);
4681 return ICS;
4682 }
4683 break;
4684
4685 case RQ_RValue:
4686 if (!FromClassification.isRValue()) {
4687 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004688 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004689 ImplicitParamType);
4690 return ICS;
4691 }
4692 break;
4693 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004694
Douglas Gregor96176b32008-11-18 23:14:02 +00004695 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004696 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004697 ICS.Standard.setAsIdentityConversion();
4698 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004699 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004700 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004701 ICS.Standard.ReferenceBinding = true;
4702 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004703 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004704 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004705 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4706 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4707 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004708 return ICS;
4709}
4710
4711/// PerformObjectArgumentInitialization - Perform initialization of
4712/// the implicit object parameter for the given Method with the given
4713/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004714ExprResult
4715Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004716 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004717 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004718 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004719 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004720 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004721 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004722
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004723 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004724 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004725 FromRecordType = PT->getPointeeType();
4726 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004727 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004728 } else {
4729 FromRecordType = From->getType();
4730 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004731 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004732 }
4733
John McCall701c89e2009-12-03 04:06:58 +00004734 // Note that we always use the true parent context when performing
4735 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004736 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004737 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4738 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004739 if (ICS.isBad()) {
4740 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4741 Qualifiers FromQs = FromRecordType.getQualifiers();
4742 Qualifiers ToQs = DestType.getQualifiers();
4743 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4744 if (CVR) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004745 Diag(From->getLocStart(),
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004746 diag::err_member_function_call_bad_cvr)
4747 << Method->getDeclName() << FromRecordType << (CVR - 1)
4748 << From->getSourceRange();
4749 Diag(Method->getLocation(), diag::note_previous_decl)
4750 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004751 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004752 }
4753 }
4754
Daniel Dunbar96a00142012-03-09 18:35:03 +00004755 return Diag(From->getLocStart(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004756 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004757 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004758 }
Mike Stump1eb44332009-09-09 15:08:12 +00004759
John Wiegley429bb272011-04-08 18:41:53 +00004760 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4761 ExprResult FromRes =
4762 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4763 if (FromRes.isInvalid())
4764 return ExprError();
4765 From = FromRes.take();
4766 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004767
Douglas Gregor5fccd362010-03-03 23:55:11 +00004768 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004769 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004770 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004771 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004772}
4773
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004774/// TryContextuallyConvertToBool - Attempt to contextually convert the
4775/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004776static ImplicitConversionSequence
4777TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004778 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004779 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004780 // FIXME: Are these flags correct?
4781 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004782 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004783 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004784 /*CStyle=*/false,
4785 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004786}
4787
4788/// PerformContextuallyConvertToBool - Perform a contextual conversion
4789/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004790ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004791 if (checkPlaceholderForOverload(*this, From))
4792 return ExprError();
4793
John McCall120d63c2010-08-24 20:38:10 +00004794 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004795 if (!ICS.isBad())
4796 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004797
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004798 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004799 return Diag(From->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +00004800 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004801 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004802 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004803}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004804
Richard Smith8ef7b202012-01-18 23:55:52 +00004805/// Check that the specified conversion is permitted in a converted constant
4806/// expression, according to C++11 [expr.const]p3. Return true if the conversion
4807/// is acceptable.
4808static bool CheckConvertedConstantConversions(Sema &S,
4809 StandardConversionSequence &SCS) {
4810 // Since we know that the target type is an integral or unscoped enumeration
4811 // type, most conversion kinds are impossible. All possible First and Third
4812 // conversions are fine.
4813 switch (SCS.Second) {
4814 case ICK_Identity:
4815 case ICK_Integral_Promotion:
4816 case ICK_Integral_Conversion:
4817 return true;
4818
4819 case ICK_Boolean_Conversion:
Richard Smith2bcb9842012-09-13 22:00:12 +00004820 // Conversion from an integral or unscoped enumeration type to bool is
4821 // classified as ICK_Boolean_Conversion, but it's also an integral
4822 // conversion, so it's permitted in a converted constant expression.
4823 return SCS.getFromType()->isIntegralOrUnscopedEnumerationType() &&
4824 SCS.getToType(2)->isBooleanType();
4825
Richard Smith8ef7b202012-01-18 23:55:52 +00004826 case ICK_Floating_Integral:
4827 case ICK_Complex_Real:
4828 return false;
4829
4830 case ICK_Lvalue_To_Rvalue:
4831 case ICK_Array_To_Pointer:
4832 case ICK_Function_To_Pointer:
4833 case ICK_NoReturn_Adjustment:
4834 case ICK_Qualification:
4835 case ICK_Compatible_Conversion:
4836 case ICK_Vector_Conversion:
4837 case ICK_Vector_Splat:
4838 case ICK_Derived_To_Base:
4839 case ICK_Pointer_Conversion:
4840 case ICK_Pointer_Member:
4841 case ICK_Block_Pointer_Conversion:
4842 case ICK_Writeback_Conversion:
4843 case ICK_Floating_Promotion:
4844 case ICK_Complex_Promotion:
4845 case ICK_Complex_Conversion:
4846 case ICK_Floating_Conversion:
4847 case ICK_TransparentUnionConversion:
4848 llvm_unreachable("unexpected second conversion kind");
4849
4850 case ICK_Num_Conversion_Kinds:
4851 break;
4852 }
4853
4854 llvm_unreachable("unknown conversion kind");
4855}
4856
4857/// CheckConvertedConstantExpression - Check that the expression From is a
4858/// converted constant expression of type T, perform the conversion and produce
4859/// the converted expression, per C++11 [expr.const]p3.
4860ExprResult Sema::CheckConvertedConstantExpression(Expr *From, QualType T,
4861 llvm::APSInt &Value,
4862 CCEKind CCE) {
4863 assert(LangOpts.CPlusPlus0x && "converted constant expression outside C++11");
4864 assert(T->isIntegralOrEnumerationType() && "unexpected converted const type");
4865
4866 if (checkPlaceholderForOverload(*this, From))
4867 return ExprError();
4868
4869 // C++11 [expr.const]p3 with proposed wording fixes:
4870 // A converted constant expression of type T is a core constant expression,
4871 // implicitly converted to a prvalue of type T, where the converted
4872 // expression is a literal constant expression and the implicit conversion
4873 // sequence contains only user-defined conversions, lvalue-to-rvalue
4874 // conversions, integral promotions, and integral conversions other than
4875 // narrowing conversions.
4876 ImplicitConversionSequence ICS =
4877 TryImplicitConversion(From, T,
4878 /*SuppressUserConversions=*/false,
4879 /*AllowExplicit=*/false,
4880 /*InOverloadResolution=*/false,
4881 /*CStyle=*/false,
4882 /*AllowObjcWritebackConversion=*/false);
4883 StandardConversionSequence *SCS = 0;
4884 switch (ICS.getKind()) {
4885 case ImplicitConversionSequence::StandardConversion:
4886 if (!CheckConvertedConstantConversions(*this, ICS.Standard))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004887 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004888 diag::err_typecheck_converted_constant_expression_disallowed)
4889 << From->getType() << From->getSourceRange() << T;
4890 SCS = &ICS.Standard;
4891 break;
4892 case ImplicitConversionSequence::UserDefinedConversion:
4893 // We are converting from class type to an integral or enumeration type, so
4894 // the Before sequence must be trivial.
4895 if (!CheckConvertedConstantConversions(*this, ICS.UserDefined.After))
Daniel Dunbar96a00142012-03-09 18:35:03 +00004896 return Diag(From->getLocStart(),
Richard Smith8ef7b202012-01-18 23:55:52 +00004897 diag::err_typecheck_converted_constant_expression_disallowed)
4898 << From->getType() << From->getSourceRange() << T;
4899 SCS = &ICS.UserDefined.After;
4900 break;
4901 case ImplicitConversionSequence::AmbiguousConversion:
4902 case ImplicitConversionSequence::BadConversion:
4903 if (!DiagnoseMultipleUserDefinedConversion(From, T))
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)
4906 << From->getType() << From->getSourceRange() << T;
4907 return ExprError();
4908
4909 case ImplicitConversionSequence::EllipsisConversion:
4910 llvm_unreachable("ellipsis conversion in converted constant expression");
4911 }
4912
4913 ExprResult Result = PerformImplicitConversion(From, T, ICS, AA_Converting);
4914 if (Result.isInvalid())
4915 return Result;
4916
4917 // Check for a narrowing implicit conversion.
4918 APValue PreNarrowingValue;
Richard Smithf6028062012-03-23 23:55:39 +00004919 QualType PreNarrowingType;
Richard Smithf6028062012-03-23 23:55:39 +00004920 switch (SCS->getNarrowingKind(Context, Result.get(), PreNarrowingValue,
4921 PreNarrowingType)) {
Richard Smith8ef7b202012-01-18 23:55:52 +00004922 case NK_Variable_Narrowing:
4923 // Implicit conversion to a narrower type, and the value is not a constant
4924 // expression. We'll diagnose this in a moment.
4925 case NK_Not_Narrowing:
4926 break;
4927
4928 case NK_Constant_Narrowing:
Eli Friedman1ef28db2012-03-29 23:39:39 +00004929 Diag(From->getLocStart(),
4930 isSFINAEContext() ? diag::err_cce_narrowing_sfinae :
4931 diag::err_cce_narrowing)
Richard Smith8ef7b202012-01-18 23:55:52 +00004932 << CCE << /*Constant*/1
Richard Smithf6028062012-03-23 23:55:39 +00004933 << PreNarrowingValue.getAsString(Context, PreNarrowingType) << T;
Richard Smith8ef7b202012-01-18 23:55:52 +00004934 break;
4935
4936 case NK_Type_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*/0 << From->getType() << T;
4941 break;
4942 }
4943
4944 // Check the expression is a constant expression.
4945 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
4946 Expr::EvalResult Eval;
4947 Eval.Diag = &Notes;
4948
4949 if (!Result.get()->EvaluateAsRValue(Eval, Context)) {
4950 // The expression can't be folded, so we can't keep it at this position in
4951 // the AST.
4952 Result = ExprError();
Richard Smithf72fccf2012-01-30 22:27:01 +00004953 } else {
Richard Smith8ef7b202012-01-18 23:55:52 +00004954 Value = Eval.Val.getInt();
Richard Smithf72fccf2012-01-30 22:27:01 +00004955
4956 if (Notes.empty()) {
4957 // It's a constant expression.
4958 return Result;
4959 }
Richard Smith8ef7b202012-01-18 23:55:52 +00004960 }
4961
4962 // It's not a constant expression. Produce an appropriate diagnostic.
4963 if (Notes.size() == 1 &&
4964 Notes[0].second.getDiagID() == diag::note_invalid_subexpr_in_const_expr)
4965 Diag(Notes[0].first, diag::err_expr_not_cce) << CCE;
4966 else {
Daniel Dunbar96a00142012-03-09 18:35:03 +00004967 Diag(From->getLocStart(), diag::err_expr_not_cce)
Richard Smith8ef7b202012-01-18 23:55:52 +00004968 << CCE << From->getSourceRange();
4969 for (unsigned I = 0; I < Notes.size(); ++I)
4970 Diag(Notes[I].first, Notes[I].second);
4971 }
Richard Smithf72fccf2012-01-30 22:27:01 +00004972 return Result;
Richard Smith8ef7b202012-01-18 23:55:52 +00004973}
4974
John McCall0bcc9bc2011-09-09 06:11:02 +00004975/// dropPointerConversions - If the given standard conversion sequence
4976/// involves any pointer conversions, remove them. This may change
4977/// the result type of the conversion sequence.
4978static void dropPointerConversion(StandardConversionSequence &SCS) {
4979 if (SCS.Second == ICK_Pointer_Conversion) {
4980 SCS.Second = ICK_Identity;
4981 SCS.Third = ICK_Identity;
4982 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4983 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004984}
John McCall120d63c2010-08-24 20:38:10 +00004985
John McCall0bcc9bc2011-09-09 06:11:02 +00004986/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4987/// convert the expression From to an Objective-C pointer type.
4988static ImplicitConversionSequence
4989TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4990 // Do an implicit conversion to 'id'.
4991 QualType Ty = S.Context.getObjCIdType();
4992 ImplicitConversionSequence ICS
4993 = TryImplicitConversion(S, From, Ty,
4994 // FIXME: Are these flags correct?
4995 /*SuppressUserConversions=*/false,
4996 /*AllowExplicit=*/true,
4997 /*InOverloadResolution=*/false,
4998 /*CStyle=*/false,
4999 /*AllowObjCWritebackConversion=*/false);
5000
5001 // Strip off any final conversions to 'id'.
5002 switch (ICS.getKind()) {
5003 case ImplicitConversionSequence::BadConversion:
5004 case ImplicitConversionSequence::AmbiguousConversion:
5005 case ImplicitConversionSequence::EllipsisConversion:
5006 break;
5007
5008 case ImplicitConversionSequence::UserDefinedConversion:
5009 dropPointerConversion(ICS.UserDefined.After);
5010 break;
5011
5012 case ImplicitConversionSequence::StandardConversion:
5013 dropPointerConversion(ICS.Standard);
5014 break;
5015 }
5016
5017 return ICS;
5018}
5019
5020/// PerformContextuallyConvertToObjCPointer - Perform a contextual
5021/// conversion of the expression From to an Objective-C pointer type.
5022ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00005023 if (checkPlaceholderForOverload(*this, From))
5024 return ExprError();
5025
John McCallc12c5bb2010-05-15 11:32:37 +00005026 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00005027 ImplicitConversionSequence ICS =
5028 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005029 if (!ICS.isBad())
5030 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00005031 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00005032}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005033
Richard Smithf39aec12012-02-04 07:07:42 +00005034/// Determine whether the provided type is an integral type, or an enumeration
5035/// type of a permitted flavor.
5036static bool isIntegralOrEnumerationType(QualType T, bool AllowScopedEnum) {
5037 return AllowScopedEnum ? T->isIntegralOrEnumerationType()
5038 : T->isIntegralOrUnscopedEnumerationType();
5039}
5040
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005041/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00005042/// enumeration type.
5043///
5044/// This routine will attempt to convert an expression of class type to an
5045/// integral or enumeration type, if that class type only has a single
5046/// conversion to an integral or enumeration type.
5047///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005048/// \param Loc The source location of the construct that requires the
5049/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00005050///
James Dennett40ae6662012-06-22 08:52:37 +00005051/// \param From The expression we're converting from.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005052///
James Dennett40ae6662012-06-22 08:52:37 +00005053/// \param Diagnoser Used to output any diagnostics.
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005054///
Richard Smithf39aec12012-02-04 07:07:42 +00005055/// \param AllowScopedEnumerations Specifies whether conversions to scoped
5056/// enumerations should be considered.
5057///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005058/// \returns The expression, converted to an integral or enumeration type if
5059/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005060ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00005061Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorab41fe92012-05-04 22:38:52 +00005062 ICEConvertDiagnoser &Diagnoser,
Richard Smithf39aec12012-02-04 07:07:42 +00005063 bool AllowScopedEnumerations) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005064 // We can't perform any more checking for type-dependent expressions.
5065 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00005066 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067
Eli Friedmanceccab92012-01-26 00:26:18 +00005068 // Process placeholders immediately.
5069 if (From->hasPlaceholderType()) {
5070 ExprResult result = CheckPlaceholderExpr(From);
5071 if (result.isInvalid()) return result;
5072 From = result.take();
5073 }
5074
Douglas Gregorc30614b2010-06-29 23:17:37 +00005075 // If the expression already has integral or enumeration type, we're golden.
5076 QualType T = From->getType();
Richard Smithf39aec12012-02-04 07:07:42 +00005077 if (isIntegralOrEnumerationType(T, AllowScopedEnumerations))
Eli Friedmanceccab92012-01-26 00:26:18 +00005078 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005079
5080 // FIXME: Check for missing '()' if T is a function type?
5081
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005082 // 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 +00005083 // expression of integral or enumeration type.
5084 const RecordType *RecordTy = T->getAs<RecordType>();
David Blaikie4e4d0842012-03-11 07:00:24 +00005085 if (!RecordTy || !getLangOpts().CPlusPlus) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005086 if (!Diagnoser.Suppress)
5087 Diagnoser.diagnoseNotInt(*this, Loc, T) << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00005088 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005089 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005090
Douglas Gregorc30614b2010-06-29 23:17:37 +00005091 // We must have a complete class type.
Douglas Gregorf502d8e2012-05-04 16:48:41 +00005092 struct TypeDiagnoserPartialDiag : TypeDiagnoser {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005093 ICEConvertDiagnoser &Diagnoser;
5094 Expr *From;
Douglas Gregord10099e2012-05-04 16:32:21 +00005095
Douglas Gregorab41fe92012-05-04 22:38:52 +00005096 TypeDiagnoserPartialDiag(ICEConvertDiagnoser &Diagnoser, Expr *From)
5097 : TypeDiagnoser(Diagnoser.Suppress), Diagnoser(Diagnoser), From(From) {}
Douglas Gregord10099e2012-05-04 16:32:21 +00005098
5099 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
Douglas Gregorab41fe92012-05-04 22:38:52 +00005100 Diagnoser.diagnoseIncomplete(S, Loc, T) << From->getSourceRange();
Douglas Gregord10099e2012-05-04 16:32:21 +00005101 }
Douglas Gregorab41fe92012-05-04 22:38:52 +00005102 } IncompleteDiagnoser(Diagnoser, From);
Douglas Gregord10099e2012-05-04 16:32:21 +00005103
5104 if (RequireCompleteType(Loc, T, IncompleteDiagnoser))
John McCall9ae2f072010-08-23 23:25:46 +00005105 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005106
Douglas Gregorc30614b2010-06-29 23:17:37 +00005107 // Look for a conversion to an integral or enumeration type.
5108 UnresolvedSet<4> ViableConversions;
5109 UnresolvedSet<4> ExplicitConversions;
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005110 std::pair<CXXRecordDecl::conversion_iterator,
5111 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregorc30614b2010-06-29 23:17:37 +00005112 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005113
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005114 bool HadMultipleCandidates
5115 = (std::distance(Conversions.first, Conversions.second) > 1);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005116
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00005117 for (CXXRecordDecl::conversion_iterator
5118 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005119 if (CXXConversionDecl *Conversion
Richard Smithf39aec12012-02-04 07:07:42 +00005120 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
5121 if (isIntegralOrEnumerationType(
5122 Conversion->getConversionType().getNonReferenceType(),
5123 AllowScopedEnumerations)) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005124 if (Conversion->isExplicit())
5125 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
5126 else
5127 ViableConversions.addDecl(I.getDecl(), I.getAccess());
5128 }
Richard Smithf39aec12012-02-04 07:07:42 +00005129 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005130 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005131
Douglas Gregorc30614b2010-06-29 23:17:37 +00005132 switch (ViableConversions.size()) {
5133 case 0:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005134 if (ExplicitConversions.size() == 1 && !Diagnoser.Suppress) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00005135 DeclAccessPair Found = ExplicitConversions[0];
5136 CXXConversionDecl *Conversion
5137 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005138
Douglas Gregorc30614b2010-06-29 23:17:37 +00005139 // The user probably meant to invoke the given explicit
5140 // conversion; use it.
5141 QualType ConvTy
5142 = Conversion->getConversionType().getNonReferenceType();
5143 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00005144 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005145
Douglas Gregorab41fe92012-05-04 22:38:52 +00005146 Diagnoser.diagnoseExplicitConv(*this, Loc, T, ConvTy)
Douglas Gregorc30614b2010-06-29 23:17:37 +00005147 << FixItHint::CreateInsertion(From->getLocStart(),
5148 "static_cast<" + TypeStr + ">(")
5149 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
5150 ")");
Douglas Gregorab41fe92012-05-04 22:38:52 +00005151 Diagnoser.noteExplicitConv(*this, Conversion, ConvTy);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005152
5153 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00005154 // explicit conversion function.
5155 if (isSFINAEContext())
5156 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005157
Douglas Gregorc30614b2010-06-29 23:17:37 +00005158 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005159 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5160 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005161 if (Result.isInvalid())
5162 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005163 // Record usage of conversion in an implicit cast.
5164 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5165 CK_UserDefinedConversion,
5166 Result.get(), 0,
5167 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005168 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005169
Douglas Gregorc30614b2010-06-29 23:17:37 +00005170 // We'll complain below about a non-integral condition type.
5171 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005172
Douglas Gregorc30614b2010-06-29 23:17:37 +00005173 case 1: {
5174 // Apply this conversion.
5175 DeclAccessPair Found = ViableConversions[0];
5176 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005177
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005178 CXXConversionDecl *Conversion
5179 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
5180 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005181 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005182 if (!Diagnoser.SuppressConversion) {
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005183 if (isSFINAEContext())
5184 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005185
Douglas Gregorab41fe92012-05-04 22:38:52 +00005186 Diagnoser.diagnoseConversion(*this, Loc, T, ConvTy)
5187 << From->getSourceRange();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00005188 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005189
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005190 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
5191 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00005192 if (Result.isInvalid())
5193 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00005194 // Record usage of conversion in an implicit cast.
5195 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
5196 CK_UserDefinedConversion,
5197 Result.get(), 0,
5198 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00005199 break;
5200 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005201
Douglas Gregorc30614b2010-06-29 23:17:37 +00005202 default:
Douglas Gregorab41fe92012-05-04 22:38:52 +00005203 if (Diagnoser.Suppress)
5204 return ExprError();
Richard Smith282e7e62012-02-04 09:53:13 +00005205
Douglas Gregorab41fe92012-05-04 22:38:52 +00005206 Diagnoser.diagnoseAmbiguous(*this, Loc, T) << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00005207 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
5208 CXXConversionDecl *Conv
5209 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
5210 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
Douglas Gregorab41fe92012-05-04 22:38:52 +00005211 Diagnoser.noteAmbiguous(*this, Conv, ConvTy);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005212 }
John McCall9ae2f072010-08-23 23:25:46 +00005213 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005214 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005215
Richard Smith282e7e62012-02-04 09:53:13 +00005216 if (!isIntegralOrEnumerationType(From->getType(), AllowScopedEnumerations) &&
Douglas Gregorab41fe92012-05-04 22:38:52 +00005217 !Diagnoser.Suppress) {
5218 Diagnoser.diagnoseNotInt(*this, Loc, From->getType())
5219 << From->getSourceRange();
5220 }
Douglas Gregorc30614b2010-06-29 23:17:37 +00005221
Eli Friedmanceccab92012-01-26 00:26:18 +00005222 return DefaultLvalueConversion(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00005223}
5224
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005225/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00005226/// candidate functions, using the given function call arguments. If
5227/// @p SuppressUserConversions, then don't allow user-defined
5228/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005229///
James Dennett699c9042012-06-15 07:13:21 +00005230/// \param PartialOverloading true if we are performing "partial" overloading
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005231/// based on an incomplete set of function arguments. This feature is used by
5232/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00005233void
5234Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00005235 DeclAccessPair FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005236 llvm::ArrayRef<Expr *> Args,
Douglas Gregor225c41e2008-11-03 19:09:14 +00005237 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00005238 bool SuppressUserConversions,
Douglas Gregored878af2012-02-24 23:56:31 +00005239 bool PartialOverloading,
5240 bool AllowExplicit) {
Mike Stump1eb44332009-09-09 15:08:12 +00005241 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005242 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005243 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00005244 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00005245 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00005246
Douglas Gregor88a35142008-12-22 05:46:06 +00005247 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005248 if (!isa<CXXConstructorDecl>(Method)) {
5249 // If we get here, it's because we're calling a member function
5250 // that is named without a member access expression (e.g.,
5251 // "this->f") that was either written explicitly or created
5252 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00005253 // function, e.g., X::f(). We use an empty type for the implied
5254 // object argument (C++ [over.call.func]p3), and the acting context
5255 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00005256 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005257 QualType(), Expr::Classification::makeSimpleLValue(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005258 Args, CandidateSet, SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005259 return;
5260 }
5261 // We treat a constructor like a non-member function, since its object
5262 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00005263 }
5264
Douglas Gregorfd476482009-11-13 23:59:09 +00005265 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00005266 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00005267
Douglas Gregor7edfb692009-11-23 12:27:39 +00005268 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005269 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005270
Douglas Gregor66724ea2009-11-14 01:20:54 +00005271 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
5272 // C++ [class.copy]p3:
5273 // A member function template is never instantiated to perform the copy
5274 // of a class object to an object of its class type.
5275 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
Ahmed Charles13a140c2012-02-25 11:00:22 +00005276 if (Args.size() == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00005277 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00005278 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
5279 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00005280 return;
5281 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005282
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005283 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005284 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size());
John McCall9aa472c2010-03-19 07:35:19 +00005285 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005286 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00005287 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005288 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005289 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005290 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005291
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005292 unsigned NumArgsInProto = Proto->getNumArgs();
5293
5294 // (C++ 13.3.2p2): A candidate function having fewer than m
5295 // parameters is viable only if it has an ellipsis in its parameter
5296 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005297 if ((Args.size() + (PartialOverloading && Args.size())) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00005298 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005299 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005300 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005301 return;
5302 }
5303
5304 // (C++ 13.3.2p2): A candidate function having more than m parameters
5305 // is viable only if the (m+1)st parameter has a default argument
5306 // (8.3.6). For the purposes of overload resolution, the
5307 // parameter list is truncated on the right, so that there are
5308 // exactly m parameters.
5309 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005310 if (Args.size() < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005311 // Not enough arguments.
5312 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005313 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005314 return;
5315 }
5316
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005317 // (CUDA B.1): Check for invalid calls between targets.
David Blaikie4e4d0842012-03-11 07:00:24 +00005318 if (getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00005319 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
5320 if (CheckCUDATarget(Caller, Function)) {
5321 Candidate.Viable = false;
5322 Candidate.FailureKind = ovl_fail_bad_target;
5323 return;
5324 }
5325
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005326 // Determine the implicit conversion sequences for each of the
5327 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005328 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005329 if (ArgIdx < NumArgsInProto) {
5330 // (C++ 13.3.2p3): for F to be a viable function, there shall
5331 // exist for each argument an implicit conversion sequence
5332 // (13.3.3.1) that converts that argument to the corresponding
5333 // parameter of F.
5334 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005335 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005336 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005337 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005338 /*InOverloadResolution=*/true,
5339 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005340 getLangOpts().ObjCAutoRefCount,
Douglas Gregored878af2012-02-24 23:56:31 +00005341 AllowExplicit);
John McCall1d318332010-01-12 00:44:57 +00005342 if (Candidate.Conversions[ArgIdx].isBad()) {
5343 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005344 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00005345 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00005346 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005347 } else {
5348 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5349 // argument for which there is no corresponding parameter is
5350 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005351 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005352 }
5353 }
5354}
5355
Douglas Gregor063daf62009-03-13 18:40:31 +00005356/// \brief Add all of the function declarations in the given function set to
5357/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00005358void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005359 llvm::ArrayRef<Expr *> Args,
Douglas Gregor063daf62009-03-13 18:40:31 +00005360 OverloadCandidateSet& CandidateSet,
Richard Smith36f5cfe2012-03-09 08:00:36 +00005361 bool SuppressUserConversions,
5362 TemplateArgumentListInfo *ExplicitTemplateArgs) {
John McCall6e266892010-01-26 03:27:55 +00005363 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00005364 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
5365 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005366 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005367 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005368 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005369 Args[0]->getType(), Args[0]->Classify(Context),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005370 Args.slice(1), CandidateSet,
5371 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005372 else
Ahmed Charles13a140c2012-02-25 11:00:22 +00005373 AddOverloadCandidate(FD, F.getPair(), Args, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00005374 SuppressUserConversions);
5375 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005376 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00005377 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
5378 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00005379 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00005380 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005381 ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005382 Args[0]->getType(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00005383 Args[0]->Classify(Context), Args.slice(1),
5384 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005385 else
John McCall9aa472c2010-03-19 07:35:19 +00005386 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
Richard Smith36f5cfe2012-03-09 08:00:36 +00005387 ExplicitTemplateArgs, Args,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005388 CandidateSet, SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00005389 }
Douglas Gregor364e0212009-06-27 21:05:07 +00005390 }
Douglas Gregor063daf62009-03-13 18:40:31 +00005391}
5392
John McCall314be4e2009-11-17 07:50:12 +00005393/// AddMethodCandidate - Adds a named decl (which is some kind of
5394/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00005395void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005396 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005397 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00005398 Expr **Args, unsigned NumArgs,
5399 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005400 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00005401 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00005402 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00005403
5404 if (isa<UsingShadowDecl>(Decl))
5405 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005406
John McCall314be4e2009-11-17 07:50:12 +00005407 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
5408 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
5409 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00005410 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
5411 /*ExplicitArgs*/ 0,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005412 ObjectType, ObjectClassification,
5413 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005414 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005415 } else {
John McCall9aa472c2010-03-19 07:35:19 +00005416 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005417 ObjectType, ObjectClassification,
5418 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregor7ec77522010-04-16 17:33:27 +00005419 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00005420 }
5421}
5422
Douglas Gregor96176b32008-11-18 23:14:02 +00005423/// AddMethodCandidate - Adds the given C++ member function to the set
5424/// of candidate functions, using the given function call arguments
5425/// and the object argument (@c Object). For example, in a call
5426/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
5427/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
5428/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00005429/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00005430void
John McCall9aa472c2010-03-19 07:35:19 +00005431Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00005432 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005433 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005434 llvm::ArrayRef<Expr *> Args,
Douglas Gregor96176b32008-11-18 23:14:02 +00005435 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005436 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00005437 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00005438 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00005439 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005440 assert(!isa<CXXConstructorDecl>(Method) &&
5441 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00005442
Douglas Gregor3f396022009-09-28 04:47:19 +00005443 if (!CandidateSet.isNewCandidate(Method))
5444 return;
5445
Douglas Gregor7edfb692009-11-23 12:27:39 +00005446 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005447 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005448
Douglas Gregor96176b32008-11-18 23:14:02 +00005449 // Add this candidate
Ahmed Charles13a140c2012-02-25 11:00:22 +00005450 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005451 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00005452 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005453 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005454 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005455 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor96176b32008-11-18 23:14:02 +00005456
5457 unsigned NumArgsInProto = Proto->getNumArgs();
5458
5459 // (C++ 13.3.2p2): A candidate function having fewer than m
5460 // parameters is viable only if it has an ellipsis in its parameter
5461 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005462 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005463 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005464 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005465 return;
5466 }
5467
5468 // (C++ 13.3.2p2): A candidate function having more than m parameters
5469 // is viable only if the (m+1)st parameter has a default argument
5470 // (8.3.6). For the purposes of overload resolution, the
5471 // parameter list is truncated on the right, so that there are
5472 // exactly m parameters.
5473 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
Ahmed Charles13a140c2012-02-25 11:00:22 +00005474 if (Args.size() < MinRequiredArgs) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005475 // Not enough arguments.
5476 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005477 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00005478 return;
5479 }
5480
5481 Candidate.Viable = true;
Douglas Gregor96176b32008-11-18 23:14:02 +00005482
John McCall701c89e2009-12-03 04:06:58 +00005483 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00005484 // The implicit object argument is ignored.
5485 Candidate.IgnoreObjectArgument = true;
5486 else {
5487 // Determine the implicit conversion sequence for the object
5488 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00005489 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005490 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
5491 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005492 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00005493 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005494 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00005495 return;
5496 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005497 }
5498
5499 // Determine the implicit conversion sequences for each of the
5500 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005501 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005502 if (ArgIdx < NumArgsInProto) {
5503 // (C++ 13.3.2p3): for F to be a viable function, there shall
5504 // exist for each argument an implicit conversion sequence
5505 // (13.3.3.1) that converts that argument to the corresponding
5506 // parameter of F.
5507 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005508 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005509 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005510 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00005511 /*InOverloadResolution=*/true,
5512 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005513 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005514 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005515 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005516 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005517 break;
5518 }
5519 } else {
5520 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5521 // argument for which there is no corresponding parameter is
5522 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005523 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00005524 }
5525 }
5526}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005527
Douglas Gregor6b906862009-08-21 00:16:32 +00005528/// \brief Add a C++ member function template as a candidate to the candidate
5529/// set, using template argument deduction to produce an appropriate member
5530/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005531void
Douglas Gregor6b906862009-08-21 00:16:32 +00005532Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00005533 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005534 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00005535 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00005536 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005537 Expr::Classification ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005538 llvm::ArrayRef<Expr *> Args,
Douglas Gregor6b906862009-08-21 00:16:32 +00005539 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005540 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005541 if (!CandidateSet.isNewCandidate(MethodTmpl))
5542 return;
5543
Douglas Gregor6b906862009-08-21 00:16:32 +00005544 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005545 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00005546 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005547 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00005548 // candidate functions in the usual way.113) A given name can refer to one
5549 // or more function templates and also to a set of overloaded non-template
5550 // functions. In such a case, the candidate functions generated from each
5551 // function template are combined with the set of non-template candidate
5552 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005553 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00005554 FunctionDecl *Specialization = 0;
5555 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005556 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs, Args,
5557 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005558 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005559 Candidate.FoundDecl = FoundDecl;
5560 Candidate.Function = MethodTmpl->getTemplatedDecl();
5561 Candidate.Viable = false;
5562 Candidate.FailureKind = ovl_fail_bad_deduction;
5563 Candidate.IsSurrogate = false;
5564 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005565 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005566 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005567 Info);
5568 return;
5569 }
Mike Stump1eb44332009-09-09 15:08:12 +00005570
Douglas Gregor6b906862009-08-21 00:16:32 +00005571 // Add the function template specialization produced by template argument
5572 // deduction as a candidate.
5573 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00005574 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00005575 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00005576 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005577 ActingContext, ObjectType, ObjectClassification, Args,
5578 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00005579}
5580
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005581/// \brief Add a C++ function template specialization as a candidate
5582/// in the candidate set, using template argument deduction to produce
5583/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00005584void
Douglas Gregore53060f2009-06-25 22:08:12 +00005585Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005586 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00005587 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005588 llvm::ArrayRef<Expr *> Args,
Douglas Gregore53060f2009-06-25 22:08:12 +00005589 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005590 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005591 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5592 return;
5593
Douglas Gregore53060f2009-06-25 22:08:12 +00005594 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00005595 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00005596 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00005597 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00005598 // candidate functions in the usual way.113) A given name can refer to one
5599 // or more function templates and also to a set of overloaded non-template
5600 // functions. In such a case, the candidate functions generated from each
5601 // function template are combined with the set of non-template candidate
5602 // functions.
Craig Topper93e45992012-09-19 02:26:47 +00005603 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00005604 FunctionDecl *Specialization = 0;
5605 if (TemplateDeductionResult Result
Ahmed Charles13a140c2012-02-25 11:00:22 +00005606 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs, Args,
5607 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005608 OverloadCandidate &Candidate = CandidateSet.addCandidate();
John McCall9aa472c2010-03-19 07:35:19 +00005609 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00005610 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5611 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005612 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00005613 Candidate.IsSurrogate = false;
5614 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005615 Candidate.ExplicitCallArguments = Args.size();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005616 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005617 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00005618 return;
5619 }
Mike Stump1eb44332009-09-09 15:08:12 +00005620
Douglas Gregore53060f2009-06-25 22:08:12 +00005621 // Add the function template specialization produced by template argument
5622 // deduction as a candidate.
5623 assert(Specialization && "Missing function template specialization?");
Ahmed Charles13a140c2012-02-25 11:00:22 +00005624 AddOverloadCandidate(Specialization, FoundDecl, Args, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00005625 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00005626}
Mike Stump1eb44332009-09-09 15:08:12 +00005627
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005628/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00005629/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005630/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00005631/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005632/// (which may or may not be the same type as the type that the
5633/// conversion function produces).
5634void
5635Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005636 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005637 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005638 Expr *From, QualType ToType,
5639 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005640 assert(!Conversion->getDescribedFunctionTemplate() &&
5641 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005642 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00005643 if (!CandidateSet.isNewCandidate(Conversion))
5644 return;
5645
Douglas Gregor7edfb692009-11-23 12:27:39 +00005646 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005647 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005648
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005649 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005650 OverloadCandidate &Candidate = CandidateSet.addCandidate(1);
John McCall9aa472c2010-03-19 07:35:19 +00005651 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005652 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005653 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005654 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005655 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00005656 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00005657 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005658 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005659 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005660
Douglas Gregorbca39322010-08-19 15:37:02 +00005661 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005662 // For conversion functions, the function is considered to be a member of
5663 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00005664 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005665 //
5666 // Determine the implicit conversion sequence for the implicit
5667 // object parameter.
5668 QualType ImplicitParamType = From->getType();
5669 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
5670 ImplicitParamType = FromPtrType->getPointeeType();
5671 CXXRecordDecl *ConversionContext
5672 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005673
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005674 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005675 = TryObjectArgumentInitialization(*this, From->getType(),
5676 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005677 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005678
John McCall1d318332010-01-12 00:44:57 +00005679 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005680 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005681 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005682 return;
5683 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005684
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005685 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005686 // derived to base as such conversions are given Conversion Rank. They only
5687 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5688 QualType FromCanon
5689 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5690 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5691 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5692 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005693 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005694 return;
5695 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005696
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005697 // To determine what the conversion from the result of calling the
5698 // conversion function to the type we're eventually trying to
5699 // convert to (ToType), we need to synthesize a call to the
5700 // conversion function and attempt copy initialization from it. This
5701 // makes sure that we get the right semantics with respect to
5702 // lvalues/rvalues and the type. Fortunately, we can allocate this
5703 // call on the stack and we don't need its arguments to be
5704 // well-formed.
John McCallf4b88a42012-03-10 09:33:50 +00005705 DeclRefExpr ConversionRef(Conversion, false, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005706 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005707 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5708 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005709 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005710 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005711
Richard Smith87c1f1f2011-07-13 22:53:21 +00005712 QualType ConversionType = Conversion->getConversionType();
5713 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005714 Candidate.Viable = false;
5715 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5716 return;
5717 }
5718
Richard Smith87c1f1f2011-07-13 22:53:21 +00005719 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005720
Mike Stump1eb44332009-09-09 15:08:12 +00005721 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005722 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5723 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005724 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005725 CallExpr Call(Context, &ConversionFn, MultiExprArg(), CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005726 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005727 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005728 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005729 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005730 /*InOverloadResolution=*/false,
5731 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005732
John McCall1d318332010-01-12 00:44:57 +00005733 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005734 case ImplicitConversionSequence::StandardConversion:
5735 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005736
Douglas Gregorc520c842010-04-12 23:42:09 +00005737 // C++ [over.ics.user]p3:
5738 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005739 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005740 // shall have exact match rank.
5741 if (Conversion->getPrimaryTemplate() &&
5742 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5743 Candidate.Viable = false;
5744 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5745 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005746
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005747 // C++0x [dcl.init.ref]p5:
5748 // In the second case, if the reference is an rvalue reference and
5749 // the second standard conversion sequence of the user-defined
5750 // conversion sequence includes an lvalue-to-rvalue conversion, the
5751 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005752 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005753 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5754 Candidate.Viable = false;
5755 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5756 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005757 break;
5758
5759 case ImplicitConversionSequence::BadConversion:
5760 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005761 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005762 break;
5763
5764 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005765 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005766 "Can only end up with a standard conversion sequence or failure");
5767 }
5768}
5769
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005770/// \brief Adds a conversion function template specialization
5771/// candidate to the overload set, using template argument deduction
5772/// to deduce the template arguments of the conversion function
5773/// template from the type that we are converting to (C++
5774/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005775void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005776Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005777 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005778 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005779 Expr *From, QualType ToType,
5780 OverloadCandidateSet &CandidateSet) {
5781 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5782 "Only conversion function templates permitted here");
5783
Douglas Gregor3f396022009-09-28 04:47:19 +00005784 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5785 return;
5786
Craig Topper93e45992012-09-19 02:26:47 +00005787 TemplateDeductionInfo Info(CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005788 CXXConversionDecl *Specialization = 0;
5789 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005790 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005791 Specialization, Info)) {
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005792 OverloadCandidate &Candidate = CandidateSet.addCandidate();
Douglas Gregorff5adac2010-05-08 20:18:54 +00005793 Candidate.FoundDecl = FoundDecl;
5794 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5795 Candidate.Viable = false;
5796 Candidate.FailureKind = ovl_fail_bad_deduction;
5797 Candidate.IsSurrogate = false;
5798 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005799 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005800 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005801 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005802 return;
5803 }
Mike Stump1eb44332009-09-09 15:08:12 +00005804
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005805 // Add the conversion function template specialization produced by
5806 // template argument deduction as a candidate.
5807 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005808 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005809 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005810}
5811
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005812/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5813/// converts the given @c Object to a function pointer via the
5814/// conversion function @c Conversion, and then attempts to call it
5815/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5816/// the type of function that we'll eventually be calling.
5817void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005818 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005819 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005820 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005821 Expr *Object,
Ahmed Charles13a140c2012-02-25 11:00:22 +00005822 llvm::ArrayRef<Expr *> Args,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005823 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005824 if (!CandidateSet.isNewCandidate(Conversion))
5825 return;
5826
Douglas Gregor7edfb692009-11-23 12:27:39 +00005827 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005828 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005829
Ahmed Charles13a140c2012-02-25 11:00:22 +00005830 OverloadCandidate &Candidate = CandidateSet.addCandidate(Args.size() + 1);
John McCall9aa472c2010-03-19 07:35:19 +00005831 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005832 Candidate.Function = 0;
5833 Candidate.Surrogate = Conversion;
5834 Candidate.Viable = true;
5835 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005836 Candidate.IgnoreObjectArgument = false;
Ahmed Charles13a140c2012-02-25 11:00:22 +00005837 Candidate.ExplicitCallArguments = Args.size();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005838
5839 // Determine the implicit conversion sequence for the implicit
5840 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005841 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005842 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005843 Object->Classify(Context),
5844 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005845 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005846 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005847 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005848 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005849 return;
5850 }
5851
5852 // The first conversion is actually a user-defined conversion whose
5853 // first conversion is ObjectInit's standard conversion (which is
5854 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005855 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005856 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005857 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005858 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005859 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005860 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005861 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005862 = Candidate.Conversions[0].UserDefined.Before;
5863 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5864
Mike Stump1eb44332009-09-09 15:08:12 +00005865 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005866 unsigned NumArgsInProto = Proto->getNumArgs();
5867
5868 // (C++ 13.3.2p2): A candidate function having fewer than m
5869 // parameters is viable only if it has an ellipsis in its parameter
5870 // list (8.3.5).
Ahmed Charles13a140c2012-02-25 11:00:22 +00005871 if (Args.size() > NumArgsInProto && !Proto->isVariadic()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005872 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005873 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005874 return;
5875 }
5876
5877 // Function types don't have any default arguments, so just check if
5878 // we have enough arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005879 if (Args.size() < NumArgsInProto) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005880 // Not enough arguments.
5881 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005882 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005883 return;
5884 }
5885
5886 // Determine the implicit conversion sequences for each of the
5887 // arguments.
Ahmed Charles13a140c2012-02-25 11:00:22 +00005888 for (unsigned ArgIdx = 0; ArgIdx < Args.size(); ++ArgIdx) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005889 if (ArgIdx < NumArgsInProto) {
5890 // (C++ 13.3.2p3): for F to be a viable function, there shall
5891 // exist for each argument an implicit conversion sequence
5892 // (13.3.3.1) that converts that argument to the corresponding
5893 // parameter of F.
5894 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005895 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005896 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005897 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005898 /*InOverloadResolution=*/false,
5899 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00005900 getLangOpts().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005901 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005902 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005903 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005904 break;
5905 }
5906 } else {
5907 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5908 // argument for which there is no corresponding parameter is
5909 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005910 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005911 }
5912 }
5913}
5914
Douglas Gregor063daf62009-03-13 18:40:31 +00005915/// \brief Add overload candidates for overloaded operators that are
5916/// member functions.
5917///
5918/// Add the overloaded operator candidates that are member functions
5919/// for the operator Op that was used in an operator expression such
5920/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5921/// CandidateSet will store the added overload candidates. (C++
5922/// [over.match.oper]).
5923void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5924 SourceLocation OpLoc,
5925 Expr **Args, unsigned NumArgs,
5926 OverloadCandidateSet& CandidateSet,
5927 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005928 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5929
5930 // C++ [over.match.oper]p3:
5931 // For a unary operator @ with an operand of a type whose
5932 // cv-unqualified version is T1, and for a binary operator @ with
5933 // a left operand of a type whose cv-unqualified version is T1 and
5934 // a right operand of a type whose cv-unqualified version is T2,
5935 // three sets of candidate functions, designated member
5936 // candidates, non-member candidates and built-in candidates, are
5937 // constructed as follows:
5938 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005939
5940 // -- If T1 is a class type, the set of member candidates is the
5941 // result of the qualified lookup of T1::operator@
5942 // (13.3.1.1.1); otherwise, the set of member candidates is
5943 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005944 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005945 // Complete the type if it can be completed. Otherwise, we're done.
Douglas Gregord10099e2012-05-04 16:32:21 +00005946 if (RequireCompleteType(OpLoc, T1, 0))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005947 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005948
John McCalla24dc2e2009-11-17 02:14:36 +00005949 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5950 LookupQualifiedName(Operators, T1Rec->getDecl());
5951 Operators.suppressDiagnostics();
5952
Mike Stump1eb44332009-09-09 15:08:12 +00005953 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005954 OperEnd = Operators.end();
5955 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005956 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005957 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005958 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005959 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005960 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005961 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005962}
5963
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005964/// AddBuiltinCandidate - Add a candidate for a built-in
5965/// operator. ResultTy and ParamTys are the result and parameter types
5966/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005967/// arguments being passed to the candidate. IsAssignmentOperator
5968/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005969/// operator. NumContextualBoolArguments is the number of arguments
5970/// (at the beginning of the argument list) that will be contextually
5971/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005972void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005973 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005974 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005975 bool IsAssignmentOperator,
5976 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005977 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005978 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005979
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005980 // Add this candidate
Benjamin Kramer0e6a16f2012-01-14 16:31:55 +00005981 OverloadCandidate &Candidate = CandidateSet.addCandidate(NumArgs);
John McCall9aa472c2010-03-19 07:35:19 +00005982 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005983 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005984 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005985 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005986 Candidate.BuiltinTypes.ResultTy = ResultTy;
5987 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5988 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5989
5990 // Determine the implicit conversion sequences for each of the
5991 // arguments.
5992 Candidate.Viable = true;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005993 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005994 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005995 // C++ [over.match.oper]p4:
5996 // For the built-in assignment operators, conversions of the
5997 // left operand are restricted as follows:
5998 // -- no temporaries are introduced to hold the left operand, and
5999 // -- no user-defined conversions are applied to the left
6000 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00006001 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00006002 //
6003 // We block these conversions by turning off user-defined
6004 // conversions, since that is the only way that initialization of
6005 // a reference to a non-class type can occur from something that
6006 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006007 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00006008 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006009 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00006010 Candidate.Conversions[ArgIdx]
6011 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006012 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00006013 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006014 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00006015 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00006016 /*InOverloadResolution=*/false,
6017 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00006018 getLangOpts().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006019 }
John McCall1d318332010-01-12 00:44:57 +00006020 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006021 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00006022 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00006023 break;
6024 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006025 }
6026}
6027
6028/// BuiltinCandidateTypeSet - A set of types that will be used for the
6029/// candidate operator functions for built-in operators (C++
6030/// [over.built]). The types are separated into pointer types and
6031/// enumeration types.
6032class BuiltinCandidateTypeSet {
6033 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006034 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006035
6036 /// PointerTypes - The set of pointer types that will be used in the
6037 /// built-in candidates.
6038 TypeSet PointerTypes;
6039
Sebastian Redl78eb8742009-04-19 21:53:20 +00006040 /// MemberPointerTypes - The set of member pointer types that will be
6041 /// used in the built-in candidates.
6042 TypeSet MemberPointerTypes;
6043
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006044 /// EnumerationTypes - The set of enumeration types that will be
6045 /// used in the built-in candidates.
6046 TypeSet EnumerationTypes;
6047
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006048 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00006049 /// candidates.
6050 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00006051
6052 /// \brief A flag indicating non-record types are viable candidates
6053 bool HasNonRecordTypes;
6054
6055 /// \brief A flag indicating whether either arithmetic or enumeration types
6056 /// were present in the candidate set.
6057 bool HasArithmeticOrEnumeralTypes;
6058
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006059 /// \brief A flag indicating whether the nullptr type was present in the
6060 /// candidate set.
6061 bool HasNullPtrType;
6062
Douglas Gregor5842ba92009-08-24 15:23:48 +00006063 /// Sema - The semantic analysis instance where we are building the
6064 /// candidate type set.
6065 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00006066
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006067 /// Context - The AST context in which we will build the type sets.
6068 ASTContext &Context;
6069
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006070 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6071 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00006072 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006073
6074public:
6075 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006076 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006077
Mike Stump1eb44332009-09-09 15:08:12 +00006078 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00006079 : HasNonRecordTypes(false),
6080 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006081 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00006082 SemaRef(SemaRef),
6083 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006084
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006085 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006086 SourceLocation Loc,
6087 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006088 bool AllowExplicitConversions,
6089 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006090
6091 /// pointer_begin - First pointer type found;
6092 iterator pointer_begin() { return PointerTypes.begin(); }
6093
Sebastian Redl78eb8742009-04-19 21:53:20 +00006094 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006095 iterator pointer_end() { return PointerTypes.end(); }
6096
Sebastian Redl78eb8742009-04-19 21:53:20 +00006097 /// member_pointer_begin - First member pointer type found;
6098 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
6099
6100 /// member_pointer_end - Past the last member pointer type found;
6101 iterator member_pointer_end() { return MemberPointerTypes.end(); }
6102
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006103 /// enumeration_begin - First enumeration type found;
6104 iterator enumeration_begin() { return EnumerationTypes.begin(); }
6105
Sebastian Redl78eb8742009-04-19 21:53:20 +00006106 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006107 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006108
Douglas Gregor26bcf672010-05-19 03:21:00 +00006109 iterator vector_begin() { return VectorTypes.begin(); }
6110 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00006111
6112 bool hasNonRecordTypes() { return HasNonRecordTypes; }
6113 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006114 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006115};
6116
Sebastian Redl78eb8742009-04-19 21:53:20 +00006117/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006118/// the set of pointer types along with any more-qualified variants of
6119/// that type. For example, if @p Ty is "int const *", this routine
6120/// will add "int const *", "int const volatile *", "int const
6121/// restrict *", and "int const volatile restrict *" to the set of
6122/// pointer types. Returns true if the add of @p Ty itself succeeded,
6123/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006124///
6125/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006126bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00006127BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
6128 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00006129
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006130 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00006131 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006132 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006133
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006134 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00006135 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006136 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006137 if (!PointerTy) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006138 const ObjCObjectPointerType *PTy = Ty->castAs<ObjCObjectPointerType>();
6139 PointeeTy = PTy->getPointeeType();
6140 buildObjCPtr = true;
6141 } else {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006142 PointeeTy = PointerTy->getPointeeType();
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006143 }
6144
Sebastian Redla9efada2009-11-18 20:39:26 +00006145 // Don't add qualified variants of arrays. For one, they're not allowed
6146 // (the qualifier would sink to the element type), and for another, the
6147 // only overload situation where it matters is subscript or pointer +- int,
6148 // and those shouldn't have qualifier variants anyway.
6149 if (PointeeTy->isArrayType())
6150 return true;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006151
John McCall0953e762009-09-24 19:53:00 +00006152 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006153 bool hasVolatile = VisibleQuals.hasVolatile();
6154 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006155
John McCall0953e762009-09-24 19:53:00 +00006156 // Iterate through all strict supersets of BaseCVR.
6157 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6158 if ((CVR | BaseCVR) != CVR) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006159 // Skip over volatile if no volatile found anywhere in the types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006160 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006161
6162 // Skip over restrict if no restrict found anywhere in the types, or if
6163 // the type cannot be restrict-qualified.
6164 if ((CVR & Qualifiers::Restrict) &&
6165 (!hasRestrict ||
6166 (!(PointeeTy->isAnyPointerType() || PointeeTy->isReferenceType()))))
6167 continue;
6168
6169 // Build qualified pointee type.
John McCall0953e762009-09-24 19:53:00 +00006170 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006171
6172 // Build qualified pointer type.
6173 QualType QPointerTy;
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006174 if (!buildObjCPtr)
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006175 QPointerTy = Context.getPointerType(QPointeeTy);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00006176 else
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006177 QPointerTy = Context.getObjCObjectPointerType(QPointeeTy);
6178
6179 // Insert qualified pointer type.
6180 PointerTypes.insert(QPointerTy);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006181 }
6182
6183 return true;
6184}
6185
Sebastian Redl78eb8742009-04-19 21:53:20 +00006186/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
6187/// to the set of pointer types along with any more-qualified variants of
6188/// that type. For example, if @p Ty is "int const *", this routine
6189/// will add "int const *", "int const volatile *", "int const
6190/// restrict *", and "int const volatile restrict *" to the set of
6191/// pointer types. Returns true if the add of @p Ty itself succeeded,
6192/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00006193///
6194/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00006195bool
6196BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
6197 QualType Ty) {
6198 // Insert this type.
6199 if (!MemberPointerTypes.insert(Ty))
6200 return false;
6201
John McCall0953e762009-09-24 19:53:00 +00006202 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
6203 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00006204
John McCall0953e762009-09-24 19:53:00 +00006205 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00006206 // Don't add qualified variants of arrays. For one, they're not allowed
6207 // (the qualifier would sink to the element type), and for another, the
6208 // only overload situation where it matters is subscript or pointer +- int,
6209 // and those shouldn't have qualifier variants anyway.
6210 if (PointeeTy->isArrayType())
6211 return true;
John McCall0953e762009-09-24 19:53:00 +00006212 const Type *ClassTy = PointerTy->getClass();
6213
6214 // Iterate through all strict supersets of the pointee type's CVR
6215 // qualifiers.
6216 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
6217 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
6218 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006219
John McCall0953e762009-09-24 19:53:00 +00006220 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006221 MemberPointerTypes.insert(
6222 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00006223 }
6224
6225 return true;
6226}
6227
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006228/// AddTypesConvertedFrom - Add each of the types to which the type @p
6229/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00006230/// primarily interested in pointer types and enumeration types. We also
6231/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006232/// AllowUserConversions is true if we should look at the conversion
6233/// functions of a class type, and AllowExplicitConversions if we
6234/// should also include the explicit conversion functions of a class
6235/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00006236void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006237BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00006238 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00006239 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006240 bool AllowExplicitConversions,
6241 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006242 // Only deal with canonical types.
6243 Ty = Context.getCanonicalType(Ty);
6244
6245 // Look through reference types; they aren't part of the type of an
6246 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00006247 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006248 Ty = RefTy->getPointeeType();
6249
John McCall3b657512011-01-19 10:06:00 +00006250 // If we're dealing with an array type, decay to the pointer.
6251 if (Ty->isArrayType())
6252 Ty = SemaRef.Context.getArrayDecayedType(Ty);
6253
6254 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00006255 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006256
Chandler Carruth6a577462010-12-13 01:44:01 +00006257 // Flag if we ever add a non-record type.
6258 const RecordType *TyRec = Ty->getAs<RecordType>();
6259 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
6260
Chandler Carruth6a577462010-12-13 01:44:01 +00006261 // Flag if we encounter an arithmetic type.
6262 HasArithmeticOrEnumeralTypes =
6263 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
6264
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00006265 if (Ty->isObjCIdType() || Ty->isObjCClassType())
6266 PointerTypes.insert(Ty);
6267 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006268 // Insert our type, and its more-qualified variants, into the set
6269 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006270 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006271 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00006272 } else if (Ty->isMemberPointerType()) {
6273 // Member pointers are far easier, since the pointee can't be converted.
6274 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
6275 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006276 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006277 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00006278 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00006279 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006280 // We treat vector types as arithmetic types in many contexts as an
6281 // extension.
6282 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00006283 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006284 } else if (Ty->isNullPtrType()) {
6285 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00006286 } else if (AllowUserConversions && TyRec) {
6287 // No conversion functions in incomplete types.
6288 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
6289 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006290
Chandler Carruth6a577462010-12-13 01:44:01 +00006291 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006292 std::pair<CXXRecordDecl::conversion_iterator,
6293 CXXRecordDecl::conversion_iterator>
6294 Conversions = ClassDecl->getVisibleConversionFunctions();
6295 for (CXXRecordDecl::conversion_iterator
6296 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006297 NamedDecl *D = I.getDecl();
6298 if (isa<UsingShadowDecl>(D))
6299 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006300
Chandler Carruth6a577462010-12-13 01:44:01 +00006301 // Skip conversion function templates; they don't tell us anything
6302 // about which builtin types we can convert to.
6303 if (isa<FunctionTemplateDecl>(D))
6304 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006305
Chandler Carruth6a577462010-12-13 01:44:01 +00006306 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
6307 if (AllowExplicitConversions || !Conv->isExplicit()) {
6308 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
6309 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006310 }
6311 }
6312 }
6313}
6314
Douglas Gregor19b7b152009-08-24 13:43:27 +00006315/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
6316/// the volatile- and non-volatile-qualified assignment operators for the
6317/// given type to the candidate set.
6318static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
6319 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00006320 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00006321 unsigned NumArgs,
6322 OverloadCandidateSet &CandidateSet) {
6323 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00006324
Douglas Gregor19b7b152009-08-24 13:43:27 +00006325 // T& operator=(T&, T)
6326 ParamTypes[0] = S.Context.getLValueReferenceType(T);
6327 ParamTypes[1] = T;
6328 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6329 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00006330
Douglas Gregor19b7b152009-08-24 13:43:27 +00006331 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
6332 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00006333 ParamTypes[0]
6334 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00006335 ParamTypes[1] = T;
6336 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00006337 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00006338 }
6339}
Mike Stump1eb44332009-09-09 15:08:12 +00006340
Sebastian Redl9994a342009-10-25 17:03:50 +00006341/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
6342/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006343static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
6344 Qualifiers VRQuals;
6345 const RecordType *TyRec;
6346 if (const MemberPointerType *RHSMPType =
6347 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00006348 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006349 else
6350 TyRec = ArgExpr->getType()->getAs<RecordType>();
6351 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00006352 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006353 VRQuals.addVolatile();
6354 VRQuals.addRestrict();
6355 return VRQuals;
6356 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006357
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006358 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00006359 if (!ClassDecl->hasDefinition())
6360 return VRQuals;
6361
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006362 std::pair<CXXRecordDecl::conversion_iterator,
6363 CXXRecordDecl::conversion_iterator>
6364 Conversions = ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006365
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +00006366 for (CXXRecordDecl::conversion_iterator
6367 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00006368 NamedDecl *D = I.getDecl();
6369 if (isa<UsingShadowDecl>(D))
6370 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6371 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006372 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
6373 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
6374 CanTy = ResTypeRef->getPointeeType();
6375 // Need to go down the pointer/mempointer chain and add qualifiers
6376 // as see them.
6377 bool done = false;
6378 while (!done) {
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006379 if (CanTy.isRestrictQualified())
6380 VRQuals.addRestrict();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006381 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
6382 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006383 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006384 CanTy->getAs<MemberPointerType>())
6385 CanTy = ResTypeMPtr->getPointeeType();
6386 else
6387 done = true;
6388 if (CanTy.isVolatileQualified())
6389 VRQuals.addVolatile();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006390 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
6391 return VRQuals;
6392 }
6393 }
6394 }
6395 return VRQuals;
6396}
John McCall00071ec2010-11-13 05:51:15 +00006397
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006398namespace {
John McCall00071ec2010-11-13 05:51:15 +00006399
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006400/// \brief Helper class to manage the addition of builtin operator overload
6401/// candidates. It provides shared state and utility methods used throughout
6402/// the process, as well as a helper method to add each group of builtin
6403/// operator overloads from the standard to a candidate set.
6404class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00006405 // Common instance state available to all overload candidate addition methods.
6406 Sema &S;
6407 Expr **Args;
6408 unsigned NumArgs;
6409 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00006410 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006411 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00006412 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006413
Chandler Carruth6d695582010-12-12 10:35:00 +00006414 // Define some constants used to index and iterate over the arithemetic types
6415 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00006416 // The "promoted arithmetic types" are the arithmetic
6417 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00006418 static const unsigned FirstIntegralType = 3;
Richard Smith3c2fcf82012-06-10 08:00:26 +00006419 static const unsigned LastIntegralType = 20;
John McCall00071ec2010-11-13 05:51:15 +00006420 static const unsigned FirstPromotedIntegralType = 3,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006421 LastPromotedIntegralType = 11;
John McCall00071ec2010-11-13 05:51:15 +00006422 static const unsigned FirstPromotedArithmeticType = 0,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006423 LastPromotedArithmeticType = 11;
6424 static const unsigned NumArithmeticTypes = 20;
John McCall00071ec2010-11-13 05:51:15 +00006425
Chandler Carruth6d695582010-12-12 10:35:00 +00006426 /// \brief Get the canonical type for a given arithmetic type index.
6427 CanQualType getArithmeticType(unsigned index) {
6428 assert(index < NumArithmeticTypes);
6429 static CanQualType ASTContext::* const
6430 ArithmeticTypes[NumArithmeticTypes] = {
6431 // Start of promoted types.
6432 &ASTContext::FloatTy,
6433 &ASTContext::DoubleTy,
6434 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00006435
Chandler Carruth6d695582010-12-12 10:35:00 +00006436 // Start of integral types.
6437 &ASTContext::IntTy,
6438 &ASTContext::LongTy,
6439 &ASTContext::LongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006440 &ASTContext::Int128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006441 &ASTContext::UnsignedIntTy,
6442 &ASTContext::UnsignedLongTy,
6443 &ASTContext::UnsignedLongLongTy,
Richard Smith3c2fcf82012-06-10 08:00:26 +00006444 &ASTContext::UnsignedInt128Ty,
Chandler Carruth6d695582010-12-12 10:35:00 +00006445 // End of promoted types.
6446
6447 &ASTContext::BoolTy,
6448 &ASTContext::CharTy,
6449 &ASTContext::WCharTy,
6450 &ASTContext::Char16Ty,
6451 &ASTContext::Char32Ty,
6452 &ASTContext::SignedCharTy,
6453 &ASTContext::ShortTy,
6454 &ASTContext::UnsignedCharTy,
6455 &ASTContext::UnsignedShortTy,
6456 // End of integral types.
Richard Smith3c2fcf82012-06-10 08:00:26 +00006457 // FIXME: What about complex? What about half?
Chandler Carruth6d695582010-12-12 10:35:00 +00006458 };
6459 return S.Context.*ArithmeticTypes[index];
6460 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006461
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006462 /// \brief Gets the canonical type resulting from the usual arithemetic
6463 /// converions for the given arithmetic types.
6464 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
6465 // Accelerator table for performing the usual arithmetic conversions.
6466 // The rules are basically:
6467 // - if either is floating-point, use the wider floating-point
6468 // - if same signedness, use the higher rank
6469 // - if same size, use unsigned of the higher rank
6470 // - use the larger type
6471 // These rules, together with the axiom that higher ranks are
6472 // never smaller, are sufficient to precompute all of these results
6473 // *except* when dealing with signed types of higher rank.
6474 // (we could precompute SLL x UI for all known platforms, but it's
6475 // better not to make any assumptions).
Richard Smith3c2fcf82012-06-10 08:00:26 +00006476 // We assume that int128 has a higher rank than long long on all platforms.
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006477 enum PromotedType {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006478 Dep=-1,
6479 Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006480 };
Nuno Lopes79e244f2012-04-21 14:45:25 +00006481 static const PromotedType ConversionsTable[LastPromotedArithmeticType]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006482 [LastPromotedArithmeticType] = {
Richard Smith3c2fcf82012-06-10 08:00:26 +00006483/* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt, Flt, Flt },
6484/* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
6485/*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
6486/* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, S128, UI, UL, ULL, U128 },
6487/* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, S128, Dep, UL, ULL, U128 },
6488/* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, S128, Dep, Dep, ULL, U128 },
6489/*S128*/ { Flt, Dbl, LDbl, S128, S128, S128, S128, S128, S128, S128, U128 },
6490/* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, S128, UI, UL, ULL, U128 },
6491/* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, S128, UL, UL, ULL, U128 },
6492/* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, S128, ULL, ULL, ULL, U128 },
6493/*U128*/ { Flt, Dbl, LDbl, U128, U128, U128, U128, U128, U128, U128, U128 },
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006494 };
6495
6496 assert(L < LastPromotedArithmeticType);
6497 assert(R < LastPromotedArithmeticType);
6498 int Idx = ConversionsTable[L][R];
6499
6500 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00006501 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006502
6503 // Slow path: we need to compare widths.
6504 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00006505 CanQualType LT = getArithmeticType(L),
6506 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006507 unsigned LW = S.Context.getIntWidth(LT),
6508 RW = S.Context.getIntWidth(RT);
6509
6510 // If they're different widths, use the signed type.
6511 if (LW > RW) return LT;
6512 else if (LW < RW) return RT;
6513
6514 // Otherwise, use the unsigned type of the signed type's rank.
6515 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
6516 assert(L == SLL || R == SLL);
6517 return S.Context.UnsignedLongLongTy;
6518 }
6519
Chandler Carruth3c69dc42010-12-12 09:22:45 +00006520 /// \brief Helper method to factor out the common pattern of adding overloads
6521 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006522 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006523 bool HasVolatile,
6524 bool HasRestrict) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006525 QualType ParamTypes[2] = {
6526 S.Context.getLValueReferenceType(CandidateTy),
6527 S.Context.IntTy
6528 };
6529
6530 // Non-volatile version.
6531 if (NumArgs == 1)
6532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6533 else
6534 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6535
6536 // Use a heuristic to reduce number of builtin candidates in the set:
6537 // add volatile version only if there are conversions to a volatile type.
6538 if (HasVolatile) {
6539 ParamTypes[0] =
6540 S.Context.getLValueReferenceType(
6541 S.Context.getVolatileType(CandidateTy));
6542 if (NumArgs == 1)
6543 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6544 else
6545 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6546 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006547
6548 // Add restrict version only if there are conversions to a restrict type
6549 // and our candidate type is a non-restrict-qualified pointer.
6550 if (HasRestrict && CandidateTy->isAnyPointerType() &&
6551 !CandidateTy.isRestrictQualified()) {
6552 ParamTypes[0]
6553 = S.Context.getLValueReferenceType(
6554 S.Context.getCVRQualifiedType(CandidateTy, Qualifiers::Restrict));
6555 if (NumArgs == 1)
6556 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
6557 else
6558 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6559
6560 if (HasVolatile) {
6561 ParamTypes[0]
6562 = S.Context.getLValueReferenceType(
6563 S.Context.getCVRQualifiedType(CandidateTy,
6564 (Qualifiers::Volatile |
6565 Qualifiers::Restrict)));
6566 if (NumArgs == 1)
6567 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1,
6568 CandidateSet);
6569 else
6570 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
6571 }
6572 }
6573
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006574 }
6575
6576public:
6577 BuiltinOperatorOverloadBuilder(
6578 Sema &S, Expr **Args, unsigned NumArgs,
6579 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006580 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00006581 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006582 OverloadCandidateSet &CandidateSet)
6583 : S(S), Args(Args), NumArgs(NumArgs),
6584 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00006585 HasArithmeticOrEnumeralCandidateType(
6586 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006587 CandidateTypes(CandidateTypes),
6588 CandidateSet(CandidateSet) {
6589 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00006590 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006591 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006592 assert(getArithmeticType(LastPromotedIntegralType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006593 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006594 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006595 assert(getArithmeticType(FirstPromotedArithmeticType)
6596 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006597 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00006598 assert(getArithmeticType(LastPromotedArithmeticType - 1)
Richard Smith3c2fcf82012-06-10 08:00:26 +00006599 == S.Context.UnsignedInt128Ty &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006600 "Invalid last promoted arithmetic type");
6601 }
6602
6603 // C++ [over.built]p3:
6604 //
6605 // For every pair (T, VQ), where T is an arithmetic type, and VQ
6606 // is either volatile or empty, there exist candidate operator
6607 // functions of the form
6608 //
6609 // VQ T& operator++(VQ T&);
6610 // T operator++(VQ T&, int);
6611 //
6612 // C++ [over.built]p4:
6613 //
6614 // For every pair (T, VQ), where T is an arithmetic type other
6615 // than bool, and VQ is either volatile or empty, there exist
6616 // candidate operator functions of the form
6617 //
6618 // VQ T& operator--(VQ T&);
6619 // T operator--(VQ T&, int);
6620 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006621 if (!HasArithmeticOrEnumeralCandidateType)
6622 return;
6623
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006624 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
6625 Arith < NumArithmeticTypes; ++Arith) {
6626 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00006627 getArithmeticType(Arith),
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006628 VisibleTypeConversionsQuals.hasVolatile(),
6629 VisibleTypeConversionsQuals.hasRestrict());
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006630 }
6631 }
6632
6633 // C++ [over.built]p5:
6634 //
6635 // For every pair (T, VQ), where T is a cv-qualified or
6636 // cv-unqualified object type, and VQ is either volatile or
6637 // empty, there exist candidate operator functions of the form
6638 //
6639 // T*VQ& operator++(T*VQ&);
6640 // T*VQ& operator--(T*VQ&);
6641 // T* operator++(T*VQ&, int);
6642 // T* operator--(T*VQ&, int);
6643 void addPlusPlusMinusMinusPointerOverloads() {
6644 for (BuiltinCandidateTypeSet::iterator
6645 Ptr = CandidateTypes[0].pointer_begin(),
6646 PtrEnd = CandidateTypes[0].pointer_end();
6647 Ptr != PtrEnd; ++Ptr) {
6648 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006649 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006650 continue;
6651
6652 addPlusPlusMinusMinusStyleOverloads(*Ptr,
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00006653 (!(*Ptr).isVolatileQualified() &&
6654 VisibleTypeConversionsQuals.hasVolatile()),
6655 (!(*Ptr).isRestrictQualified() &&
6656 VisibleTypeConversionsQuals.hasRestrict()));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006657 }
6658 }
6659
6660 // C++ [over.built]p6:
6661 // For every cv-qualified or cv-unqualified object type T, there
6662 // exist candidate operator functions of the form
6663 //
6664 // T& operator*(T*);
6665 //
6666 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006667 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006668 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006669 // T& operator*(T*);
6670 void addUnaryStarPointerOverloads() {
6671 for (BuiltinCandidateTypeSet::iterator
6672 Ptr = CandidateTypes[0].pointer_begin(),
6673 PtrEnd = CandidateTypes[0].pointer_end();
6674 Ptr != PtrEnd; ++Ptr) {
6675 QualType ParamTy = *Ptr;
6676 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006677 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
6678 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006679
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00006680 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
6681 if (Proto->getTypeQuals() || Proto->getRefQualifier())
6682 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006683
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006684 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
6685 &ParamTy, Args, 1, CandidateSet);
6686 }
6687 }
6688
6689 // C++ [over.built]p9:
6690 // For every promoted arithmetic type T, there exist candidate
6691 // operator functions of the form
6692 //
6693 // T operator+(T);
6694 // T operator-(T);
6695 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006696 if (!HasArithmeticOrEnumeralCandidateType)
6697 return;
6698
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006699 for (unsigned Arith = FirstPromotedArithmeticType;
6700 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006701 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006702 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
6703 }
6704
6705 // Extension: We also add these operators for vector types.
6706 for (BuiltinCandidateTypeSet::iterator
6707 Vec = CandidateTypes[0].vector_begin(),
6708 VecEnd = CandidateTypes[0].vector_end();
6709 Vec != VecEnd; ++Vec) {
6710 QualType VecTy = *Vec;
6711 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6712 }
6713 }
6714
6715 // C++ [over.built]p8:
6716 // For every type T, there exist candidate operator functions of
6717 // the form
6718 //
6719 // T* operator+(T*);
6720 void addUnaryPlusPointerOverloads() {
6721 for (BuiltinCandidateTypeSet::iterator
6722 Ptr = CandidateTypes[0].pointer_begin(),
6723 PtrEnd = CandidateTypes[0].pointer_end();
6724 Ptr != PtrEnd; ++Ptr) {
6725 QualType ParamTy = *Ptr;
6726 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6727 }
6728 }
6729
6730 // C++ [over.built]p10:
6731 // For every promoted integral type T, there exist candidate
6732 // operator functions of the form
6733 //
6734 // T operator~(T);
6735 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006736 if (!HasArithmeticOrEnumeralCandidateType)
6737 return;
6738
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006739 for (unsigned Int = FirstPromotedIntegralType;
6740 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006741 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006742 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6743 }
6744
6745 // Extension: We also add this operator for vector types.
6746 for (BuiltinCandidateTypeSet::iterator
6747 Vec = CandidateTypes[0].vector_begin(),
6748 VecEnd = CandidateTypes[0].vector_end();
6749 Vec != VecEnd; ++Vec) {
6750 QualType VecTy = *Vec;
6751 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6752 }
6753 }
6754
6755 // C++ [over.match.oper]p16:
6756 // For every pointer to member type T, there exist candidate operator
6757 // functions of the form
6758 //
6759 // bool operator==(T,T);
6760 // bool operator!=(T,T);
6761 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6762 /// Set of (canonical) types that we've already handled.
6763 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6764
6765 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6766 for (BuiltinCandidateTypeSet::iterator
6767 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6768 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6769 MemPtr != MemPtrEnd;
6770 ++MemPtr) {
6771 // Don't add the same builtin candidate twice.
6772 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6773 continue;
6774
6775 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6776 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6777 CandidateSet);
6778 }
6779 }
6780 }
6781
6782 // C++ [over.built]p15:
6783 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006784 // For every T, where T is an enumeration type, a pointer type, or
6785 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006786 //
6787 // bool operator<(T, T);
6788 // bool operator>(T, T);
6789 // bool operator<=(T, T);
6790 // bool operator>=(T, T);
6791 // bool operator==(T, T);
6792 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006793 void addRelationalPointerOrEnumeralOverloads() {
Eli Friedman97c67392012-09-18 21:52:24 +00006794 // C++ [over.match.oper]p3:
6795 // [...]the built-in candidates include all of the candidate operator
6796 // functions defined in 13.6 that, compared to the given operator, [...]
6797 // do not have the same parameter-type-list as any non-template non-member
6798 // candidate.
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006799 //
Eli Friedman97c67392012-09-18 21:52:24 +00006800 // Note that in practice, this only affects enumeration types because there
6801 // aren't any built-in candidates of record type, and a user-defined operator
6802 // must have an operand of record or enumeration type. Also, the only other
6803 // overloaded operator with enumeration arguments, operator=,
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006804 // cannot be overloaded for enumeration types, so this is the only place
6805 // where we must suppress candidates like this.
6806 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6807 UserDefinedBinaryOperators;
6808
6809 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6810 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6811 CandidateTypes[ArgIdx].enumeration_end()) {
6812 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6813 CEnd = CandidateSet.end();
6814 C != CEnd; ++C) {
6815 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6816 continue;
6817
Eli Friedman97c67392012-09-18 21:52:24 +00006818 if (C->Function->isFunctionTemplateSpecialization())
6819 continue;
6820
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006821 QualType FirstParamType =
6822 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6823 QualType SecondParamType =
6824 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6825
6826 // Skip if either parameter isn't of enumeral type.
6827 if (!FirstParamType->isEnumeralType() ||
6828 !SecondParamType->isEnumeralType())
6829 continue;
6830
6831 // Add this operator to the set of known user-defined operators.
6832 UserDefinedBinaryOperators.insert(
6833 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6834 S.Context.getCanonicalType(SecondParamType)));
6835 }
6836 }
6837 }
6838
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006839 /// Set of (canonical) types that we've already handled.
6840 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6841
6842 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6843 for (BuiltinCandidateTypeSet::iterator
6844 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6845 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6846 Ptr != PtrEnd; ++Ptr) {
6847 // Don't add the same builtin candidate twice.
6848 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6849 continue;
6850
6851 QualType ParamTypes[2] = { *Ptr, *Ptr };
6852 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6853 CandidateSet);
6854 }
6855 for (BuiltinCandidateTypeSet::iterator
6856 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6857 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6858 Enum != EnumEnd; ++Enum) {
6859 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6860
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006861 // Don't add the same builtin candidate twice, or if a user defined
6862 // candidate exists.
6863 if (!AddedTypes.insert(CanonType) ||
6864 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6865 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006866 continue;
6867
6868 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006869 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6870 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006871 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006872
6873 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6874 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6875 if (AddedTypes.insert(NullPtrTy) &&
6876 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6877 NullPtrTy))) {
6878 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6879 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6880 CandidateSet);
6881 }
6882 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006883 }
6884 }
6885
6886 // C++ [over.built]p13:
6887 //
6888 // For every cv-qualified or cv-unqualified object type T
6889 // there exist candidate operator functions of the form
6890 //
6891 // T* operator+(T*, ptrdiff_t);
6892 // T& operator[](T*, ptrdiff_t); [BELOW]
6893 // T* operator-(T*, ptrdiff_t);
6894 // T* operator+(ptrdiff_t, T*);
6895 // T& operator[](ptrdiff_t, T*); [BELOW]
6896 //
6897 // C++ [over.built]p14:
6898 //
6899 // For every T, where T is a pointer to object type, there
6900 // exist candidate operator functions of the form
6901 //
6902 // ptrdiff_t operator-(T, T);
6903 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6904 /// Set of (canonical) types that we've already handled.
6905 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6906
6907 for (int Arg = 0; Arg < 2; ++Arg) {
6908 QualType AsymetricParamTypes[2] = {
6909 S.Context.getPointerDiffType(),
6910 S.Context.getPointerDiffType(),
6911 };
6912 for (BuiltinCandidateTypeSet::iterator
6913 Ptr = CandidateTypes[Arg].pointer_begin(),
6914 PtrEnd = CandidateTypes[Arg].pointer_end();
6915 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006916 QualType PointeeTy = (*Ptr)->getPointeeType();
6917 if (!PointeeTy->isObjectType())
6918 continue;
6919
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006920 AsymetricParamTypes[Arg] = *Ptr;
6921 if (Arg == 0 || Op == OO_Plus) {
6922 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6923 // T* operator+(ptrdiff_t, T*);
6924 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6925 CandidateSet);
6926 }
6927 if (Op == OO_Minus) {
6928 // ptrdiff_t operator-(T, T);
6929 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6930 continue;
6931
6932 QualType ParamTypes[2] = { *Ptr, *Ptr };
6933 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6934 Args, 2, CandidateSet);
6935 }
6936 }
6937 }
6938 }
6939
6940 // C++ [over.built]p12:
6941 //
6942 // For every pair of promoted arithmetic types L and R, there
6943 // exist candidate operator functions of the form
6944 //
6945 // LR operator*(L, R);
6946 // LR operator/(L, R);
6947 // LR operator+(L, R);
6948 // LR operator-(L, R);
6949 // bool operator<(L, R);
6950 // bool operator>(L, R);
6951 // bool operator<=(L, R);
6952 // bool operator>=(L, R);
6953 // bool operator==(L, R);
6954 // bool operator!=(L, R);
6955 //
6956 // where LR is the result of the usual arithmetic conversions
6957 // between types L and R.
6958 //
6959 // C++ [over.built]p24:
6960 //
6961 // For every pair of promoted arithmetic types L and R, there exist
6962 // candidate operator functions of the form
6963 //
6964 // LR operator?(bool, L, R);
6965 //
6966 // where LR is the result of the usual arithmetic conversions
6967 // between types L and R.
6968 // Our candidates ignore the first parameter.
6969 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006970 if (!HasArithmeticOrEnumeralCandidateType)
6971 return;
6972
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006973 for (unsigned Left = FirstPromotedArithmeticType;
6974 Left < LastPromotedArithmeticType; ++Left) {
6975 for (unsigned Right = FirstPromotedArithmeticType;
6976 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006977 QualType LandR[2] = { getArithmeticType(Left),
6978 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006979 QualType Result =
6980 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006981 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006982 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6983 }
6984 }
6985
6986 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6987 // conditional operator for vector types.
6988 for (BuiltinCandidateTypeSet::iterator
6989 Vec1 = CandidateTypes[0].vector_begin(),
6990 Vec1End = CandidateTypes[0].vector_end();
6991 Vec1 != Vec1End; ++Vec1) {
6992 for (BuiltinCandidateTypeSet::iterator
6993 Vec2 = CandidateTypes[1].vector_begin(),
6994 Vec2End = CandidateTypes[1].vector_end();
6995 Vec2 != Vec2End; ++Vec2) {
6996 QualType LandR[2] = { *Vec1, *Vec2 };
6997 QualType Result = S.Context.BoolTy;
6998 if (!isComparison) {
6999 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
7000 Result = *Vec1;
7001 else
7002 Result = *Vec2;
7003 }
7004
7005 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7006 }
7007 }
7008 }
7009
7010 // C++ [over.built]p17:
7011 //
7012 // For every pair of promoted integral types L and R, there
7013 // exist candidate operator functions of the form
7014 //
7015 // LR operator%(L, R);
7016 // LR operator&(L, R);
7017 // LR operator^(L, R);
7018 // LR operator|(L, R);
7019 // L operator<<(L, R);
7020 // L operator>>(L, R);
7021 //
7022 // where LR is the result of the usual arithmetic conversions
7023 // between types L and R.
7024 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007025 if (!HasArithmeticOrEnumeralCandidateType)
7026 return;
7027
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007028 for (unsigned Left = FirstPromotedIntegralType;
7029 Left < LastPromotedIntegralType; ++Left) {
7030 for (unsigned Right = FirstPromotedIntegralType;
7031 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00007032 QualType LandR[2] = { getArithmeticType(Left),
7033 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007034 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
7035 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00007036 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007037 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
7038 }
7039 }
7040 }
7041
7042 // C++ [over.built]p20:
7043 //
7044 // For every pair (T, VQ), where T is an enumeration or
7045 // pointer to member type and VQ is either volatile or
7046 // empty, there exist candidate operator functions of the form
7047 //
7048 // VQ T& operator=(VQ T&, T);
7049 void addAssignmentMemberPointerOrEnumeralOverloads() {
7050 /// Set of (canonical) types that we've already handled.
7051 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7052
7053 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7054 for (BuiltinCandidateTypeSet::iterator
7055 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7056 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7057 Enum != EnumEnd; ++Enum) {
7058 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7059 continue;
7060
7061 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
7062 CandidateSet);
7063 }
7064
7065 for (BuiltinCandidateTypeSet::iterator
7066 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7067 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7068 MemPtr != MemPtrEnd; ++MemPtr) {
7069 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7070 continue;
7071
7072 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
7073 CandidateSet);
7074 }
7075 }
7076 }
7077
7078 // C++ [over.built]p19:
7079 //
7080 // For every pair (T, VQ), where T is any type and VQ is either
7081 // volatile or empty, there exist candidate operator functions
7082 // of the form
7083 //
7084 // T*VQ& operator=(T*VQ&, T*);
7085 //
7086 // C++ [over.built]p21:
7087 //
7088 // For every pair (T, VQ), where T is a cv-qualified or
7089 // cv-unqualified object type and VQ is either volatile or
7090 // empty, there exist candidate operator functions of the form
7091 //
7092 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
7093 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
7094 void addAssignmentPointerOverloads(bool isEqualOp) {
7095 /// Set of (canonical) types that we've already handled.
7096 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7097
7098 for (BuiltinCandidateTypeSet::iterator
7099 Ptr = CandidateTypes[0].pointer_begin(),
7100 PtrEnd = CandidateTypes[0].pointer_end();
7101 Ptr != PtrEnd; ++Ptr) {
7102 // If this is operator=, keep track of the builtin candidates we added.
7103 if (isEqualOp)
7104 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007105 else if (!(*Ptr)->getPointeeType()->isObjectType())
7106 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007107
7108 // non-volatile version
7109 QualType ParamTypes[2] = {
7110 S.Context.getLValueReferenceType(*Ptr),
7111 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
7112 };
7113 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7114 /*IsAssigmentOperator=*/ isEqualOp);
7115
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007116 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7117 VisibleTypeConversionsQuals.hasVolatile();
7118 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007119 // volatile version
7120 ParamTypes[0] =
7121 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
7122 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7123 /*IsAssigmentOperator=*/isEqualOp);
7124 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007125
7126 if (!(*Ptr).isRestrictQualified() &&
7127 VisibleTypeConversionsQuals.hasRestrict()) {
7128 // restrict version
7129 ParamTypes[0]
7130 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7131 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7132 /*IsAssigmentOperator=*/isEqualOp);
7133
7134 if (NeedVolatile) {
7135 // volatile restrict version
7136 ParamTypes[0]
7137 = S.Context.getLValueReferenceType(
7138 S.Context.getCVRQualifiedType(*Ptr,
7139 (Qualifiers::Volatile |
7140 Qualifiers::Restrict)));
7141 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7142 CandidateSet,
7143 /*IsAssigmentOperator=*/isEqualOp);
7144 }
7145 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007146 }
7147
7148 if (isEqualOp) {
7149 for (BuiltinCandidateTypeSet::iterator
7150 Ptr = CandidateTypes[1].pointer_begin(),
7151 PtrEnd = CandidateTypes[1].pointer_end();
7152 Ptr != PtrEnd; ++Ptr) {
7153 // Make sure we don't add the same candidate twice.
7154 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7155 continue;
7156
Chandler Carruth6df868e2010-12-12 08:17:55 +00007157 QualType ParamTypes[2] = {
7158 S.Context.getLValueReferenceType(*Ptr),
7159 *Ptr,
7160 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007161
7162 // non-volatile version
7163 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7164 /*IsAssigmentOperator=*/true);
7165
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007166 bool NeedVolatile = !(*Ptr).isVolatileQualified() &&
7167 VisibleTypeConversionsQuals.hasVolatile();
7168 if (NeedVolatile) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007169 // volatile version
7170 ParamTypes[0] =
7171 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00007172 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7173 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007174 }
Douglas Gregorb1c6f5f2012-06-04 00:15:09 +00007175
7176 if (!(*Ptr).isRestrictQualified() &&
7177 VisibleTypeConversionsQuals.hasRestrict()) {
7178 // restrict version
7179 ParamTypes[0]
7180 = S.Context.getLValueReferenceType(S.Context.getRestrictType(*Ptr));
7181 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7182 CandidateSet, /*IsAssigmentOperator=*/true);
7183
7184 if (NeedVolatile) {
7185 // volatile restrict version
7186 ParamTypes[0]
7187 = S.Context.getLValueReferenceType(
7188 S.Context.getCVRQualifiedType(*Ptr,
7189 (Qualifiers::Volatile |
7190 Qualifiers::Restrict)));
7191 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7192 CandidateSet, /*IsAssigmentOperator=*/true);
7193
7194 }
7195 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007196 }
7197 }
7198 }
7199
7200 // C++ [over.built]p18:
7201 //
7202 // For every triple (L, VQ, R), where L is an arithmetic type,
7203 // VQ is either volatile or empty, and R is a promoted
7204 // arithmetic type, there exist candidate operator functions of
7205 // the form
7206 //
7207 // VQ L& operator=(VQ L&, R);
7208 // VQ L& operator*=(VQ L&, R);
7209 // VQ L& operator/=(VQ L&, R);
7210 // VQ L& operator+=(VQ L&, R);
7211 // VQ L& operator-=(VQ L&, R);
7212 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00007213 if (!HasArithmeticOrEnumeralCandidateType)
7214 return;
7215
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007216 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
7217 for (unsigned Right = FirstPromotedArithmeticType;
7218 Right < LastPromotedArithmeticType; ++Right) {
7219 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007220 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007221
7222 // Add this built-in operator as a candidate (VQ is empty).
7223 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007224 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007225 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7226 /*IsAssigmentOperator=*/isEqualOp);
7227
7228 // Add this built-in operator as a candidate (VQ is 'volatile').
7229 if (VisibleTypeConversionsQuals.hasVolatile()) {
7230 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007231 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007232 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007233 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7234 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007235 /*IsAssigmentOperator=*/isEqualOp);
7236 }
7237 }
7238 }
7239
7240 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
7241 for (BuiltinCandidateTypeSet::iterator
7242 Vec1 = CandidateTypes[0].vector_begin(),
7243 Vec1End = CandidateTypes[0].vector_end();
7244 Vec1 != Vec1End; ++Vec1) {
7245 for (BuiltinCandidateTypeSet::iterator
7246 Vec2 = CandidateTypes[1].vector_begin(),
7247 Vec2End = CandidateTypes[1].vector_end();
7248 Vec2 != Vec2End; ++Vec2) {
7249 QualType ParamTypes[2];
7250 ParamTypes[1] = *Vec2;
7251 // Add this built-in operator as a candidate (VQ is empty).
7252 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
7253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
7254 /*IsAssigmentOperator=*/isEqualOp);
7255
7256 // Add this built-in operator as a candidate (VQ is 'volatile').
7257 if (VisibleTypeConversionsQuals.hasVolatile()) {
7258 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
7259 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007260 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7261 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007262 /*IsAssigmentOperator=*/isEqualOp);
7263 }
7264 }
7265 }
7266 }
7267
7268 // C++ [over.built]p22:
7269 //
7270 // For every triple (L, VQ, R), where L is an integral type, VQ
7271 // is either volatile or empty, and R is a promoted integral
7272 // type, there exist candidate operator functions of the form
7273 //
7274 // VQ L& operator%=(VQ L&, R);
7275 // VQ L& operator<<=(VQ L&, R);
7276 // VQ L& operator>>=(VQ L&, R);
7277 // VQ L& operator&=(VQ L&, R);
7278 // VQ L& operator^=(VQ L&, R);
7279 // VQ L& operator|=(VQ L&, R);
7280 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00007281 if (!HasArithmeticOrEnumeralCandidateType)
7282 return;
7283
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007284 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
7285 for (unsigned Right = FirstPromotedIntegralType;
7286 Right < LastPromotedIntegralType; ++Right) {
7287 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00007288 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007289
7290 // Add this built-in operator as a candidate (VQ is empty).
7291 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00007292 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007293 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
7294 if (VisibleTypeConversionsQuals.hasVolatile()) {
7295 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00007296 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007297 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
7298 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
7299 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
7300 CandidateSet);
7301 }
7302 }
7303 }
7304 }
7305
7306 // C++ [over.operator]p23:
7307 //
7308 // There also exist candidate operator functions of the form
7309 //
7310 // bool operator!(bool);
7311 // bool operator&&(bool, bool);
7312 // bool operator||(bool, bool);
7313 void addExclaimOverload() {
7314 QualType ParamTy = S.Context.BoolTy;
7315 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
7316 /*IsAssignmentOperator=*/false,
7317 /*NumContextualBoolArguments=*/1);
7318 }
7319 void addAmpAmpOrPipePipeOverload() {
7320 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
7321 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
7322 /*IsAssignmentOperator=*/false,
7323 /*NumContextualBoolArguments=*/2);
7324 }
7325
7326 // C++ [over.built]p13:
7327 //
7328 // For every cv-qualified or cv-unqualified object type T there
7329 // exist candidate operator functions of the form
7330 //
7331 // T* operator+(T*, ptrdiff_t); [ABOVE]
7332 // T& operator[](T*, ptrdiff_t);
7333 // T* operator-(T*, ptrdiff_t); [ABOVE]
7334 // T* operator+(ptrdiff_t, T*); [ABOVE]
7335 // T& operator[](ptrdiff_t, T*);
7336 void addSubscriptOverloads() {
7337 for (BuiltinCandidateTypeSet::iterator
7338 Ptr = CandidateTypes[0].pointer_begin(),
7339 PtrEnd = CandidateTypes[0].pointer_end();
7340 Ptr != PtrEnd; ++Ptr) {
7341 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
7342 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007343 if (!PointeeType->isObjectType())
7344 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007345
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007346 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7347
7348 // T& operator[](T*, ptrdiff_t)
7349 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7350 }
7351
7352 for (BuiltinCandidateTypeSet::iterator
7353 Ptr = CandidateTypes[1].pointer_begin(),
7354 PtrEnd = CandidateTypes[1].pointer_end();
7355 Ptr != PtrEnd; ++Ptr) {
7356 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
7357 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00007358 if (!PointeeType->isObjectType())
7359 continue;
7360
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007361 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
7362
7363 // T& operator[](ptrdiff_t, T*)
7364 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7365 }
7366 }
7367
7368 // C++ [over.built]p11:
7369 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
7370 // C1 is the same type as C2 or is a derived class of C2, T is an object
7371 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
7372 // there exist candidate operator functions of the form
7373 //
7374 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
7375 //
7376 // where CV12 is the union of CV1 and CV2.
7377 void addArrowStarOverloads() {
7378 for (BuiltinCandidateTypeSet::iterator
7379 Ptr = CandidateTypes[0].pointer_begin(),
7380 PtrEnd = CandidateTypes[0].pointer_end();
7381 Ptr != PtrEnd; ++Ptr) {
7382 QualType C1Ty = (*Ptr);
7383 QualType C1;
7384 QualifierCollector Q1;
7385 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
7386 if (!isa<RecordType>(C1))
7387 continue;
7388 // heuristic to reduce number of builtin candidates in the set.
7389 // Add volatile/restrict version only if there are conversions to a
7390 // volatile/restrict type.
7391 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
7392 continue;
7393 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
7394 continue;
7395 for (BuiltinCandidateTypeSet::iterator
7396 MemPtr = CandidateTypes[1].member_pointer_begin(),
7397 MemPtrEnd = CandidateTypes[1].member_pointer_end();
7398 MemPtr != MemPtrEnd; ++MemPtr) {
7399 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
7400 QualType C2 = QualType(mptr->getClass(), 0);
7401 C2 = C2.getUnqualifiedType();
7402 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
7403 break;
7404 QualType ParamTypes[2] = { *Ptr, *MemPtr };
7405 // build CV12 T&
7406 QualType T = mptr->getPointeeType();
7407 if (!VisibleTypeConversionsQuals.hasVolatile() &&
7408 T.isVolatileQualified())
7409 continue;
7410 if (!VisibleTypeConversionsQuals.hasRestrict() &&
7411 T.isRestrictQualified())
7412 continue;
7413 T = Q1.apply(S.Context, T);
7414 QualType ResultTy = S.Context.getLValueReferenceType(T);
7415 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
7416 }
7417 }
7418 }
7419
7420 // Note that we don't consider the first argument, since it has been
7421 // contextually converted to bool long ago. The candidates below are
7422 // therefore added as binary.
7423 //
7424 // C++ [over.built]p25:
7425 // For every type T, where T is a pointer, pointer-to-member, or scoped
7426 // enumeration type, there exist candidate operator functions of the form
7427 //
7428 // T operator?(bool, T, T);
7429 //
7430 void addConditionalOperatorOverloads() {
7431 /// Set of (canonical) types that we've already handled.
7432 llvm::SmallPtrSet<QualType, 8> AddedTypes;
7433
7434 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
7435 for (BuiltinCandidateTypeSet::iterator
7436 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
7437 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
7438 Ptr != PtrEnd; ++Ptr) {
7439 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
7440 continue;
7441
7442 QualType ParamTypes[2] = { *Ptr, *Ptr };
7443 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
7444 }
7445
7446 for (BuiltinCandidateTypeSet::iterator
7447 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
7448 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
7449 MemPtr != MemPtrEnd; ++MemPtr) {
7450 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
7451 continue;
7452
7453 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
7454 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
7455 }
7456
David Blaikie4e4d0842012-03-11 07:00:24 +00007457 if (S.getLangOpts().CPlusPlus0x) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007458 for (BuiltinCandidateTypeSet::iterator
7459 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
7460 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
7461 Enum != EnumEnd; ++Enum) {
7462 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
7463 continue;
7464
7465 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
7466 continue;
7467
7468 QualType ParamTypes[2] = { *Enum, *Enum };
7469 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
7470 }
7471 }
7472 }
7473 }
7474};
7475
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007476} // end anonymous namespace
7477
7478/// AddBuiltinOperatorCandidates - Add the appropriate built-in
7479/// operator overloads to the candidate set (C++ [over.built]), based
7480/// on the operator @p Op and the arguments given. For example, if the
7481/// operator is a binary '+', this routine might add "int
7482/// operator+(int, int)" to cover integer addition.
7483void
7484Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
7485 SourceLocation OpLoc,
7486 Expr **Args, unsigned NumArgs,
7487 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007488 // Find all of the types that the arguments can convert to, but only
7489 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00007490 // that make use of these types. Also record whether we encounter non-record
7491 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00007492 Qualifiers VisibleTypeConversionsQuals;
7493 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00007494 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7495 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00007496
7497 bool HasNonRecordCandidateType = false;
7498 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007499 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00007500 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
7501 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
7502 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
7503 OpLoc,
7504 true,
7505 (Op == OO_Exclaim ||
7506 Op == OO_AmpAmp ||
7507 Op == OO_PipePipe),
7508 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00007509 HasNonRecordCandidateType = HasNonRecordCandidateType ||
7510 CandidateTypes[ArgIdx].hasNonRecordTypes();
7511 HasArithmeticOrEnumeralCandidateType =
7512 HasArithmeticOrEnumeralCandidateType ||
7513 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00007514 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007515
Chandler Carruth6a577462010-12-13 01:44:01 +00007516 // Exit early when no non-record types have been added to the candidate set
7517 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00007518 //
7519 // We can't exit early for !, ||, or &&, since there we have always have
7520 // 'bool' overloads.
7521 if (!HasNonRecordCandidateType &&
7522 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00007523 return;
7524
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007525 // Setup an object to manage the common state for building overloads.
7526 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
7527 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00007528 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007529 CandidateTypes, CandidateSet);
7530
7531 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007532 switch (Op) {
7533 case OO_None:
7534 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00007535 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007536
Chandler Carruthabb71842010-12-12 08:51:33 +00007537 case OO_New:
7538 case OO_Delete:
7539 case OO_Array_New:
7540 case OO_Array_Delete:
7541 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00007542 llvm_unreachable(
7543 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00007544
7545 case OO_Comma:
7546 case OO_Arrow:
7547 // C++ [over.match.oper]p3:
7548 // -- For the operator ',', the unary operator '&', or the
7549 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00007550 break;
7551
7552 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007553 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007554 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00007555 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00007556
7557 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00007558 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007559 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007560 } else {
7561 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
7562 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7563 }
Douglas Gregor74253732008-11-19 15:42:04 +00007564 break;
7565
Chandler Carruthabb71842010-12-12 08:51:33 +00007566 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00007567 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00007568 OpBuilder.addUnaryStarPointerOverloads();
7569 else
7570 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7571 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007572
Chandler Carruthabb71842010-12-12 08:51:33 +00007573 case OO_Slash:
7574 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00007575 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007576
7577 case OO_PlusPlus:
7578 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007579 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
7580 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00007581 break;
7582
Douglas Gregor19b7b152009-08-24 13:43:27 +00007583 case OO_EqualEqual:
7584 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007585 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007586 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00007587
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007588 case OO_Less:
7589 case OO_Greater:
7590 case OO_LessEqual:
7591 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00007592 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00007593 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
7594 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007595
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007596 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007597 case OO_Caret:
7598 case OO_Pipe:
7599 case OO_LessLess:
7600 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007601 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007602 break;
7603
Chandler Carruthabb71842010-12-12 08:51:33 +00007604 case OO_Amp: // '&' is either unary or binary
7605 if (NumArgs == 1)
7606 // C++ [over.match.oper]p3:
7607 // -- For the operator ',', the unary operator '&', or the
7608 // operator '->', the built-in candidates set is empty.
7609 break;
7610
7611 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
7612 break;
7613
7614 case OO_Tilde:
7615 OpBuilder.addUnaryTildePromotedIntegralOverloads();
7616 break;
7617
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007618 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007619 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00007620 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007621
7622 case OO_PlusEqual:
7623 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007624 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007625 // Fall through.
7626
7627 case OO_StarEqual:
7628 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007629 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007630 break;
7631
7632 case OO_PercentEqual:
7633 case OO_LessLessEqual:
7634 case OO_GreaterGreaterEqual:
7635 case OO_AmpEqual:
7636 case OO_CaretEqual:
7637 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007638 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007639 break;
7640
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007641 case OO_Exclaim:
7642 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00007643 break;
Douglas Gregor74253732008-11-19 15:42:04 +00007644
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007645 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007646 case OO_PipePipe:
7647 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007648 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007649
7650 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007651 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007652 break;
7653
7654 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007655 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007656 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007657
7658 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00007659 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00007660 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
7661 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007662 }
7663}
7664
Douglas Gregorfa047642009-02-04 00:32:51 +00007665/// \brief Add function candidates found via argument-dependent lookup
7666/// to the set of overloading candidates.
7667///
7668/// This routine performs argument-dependent name lookup based on the
7669/// given function name (which may also be an operator name) and adds
7670/// all of the overload candidates found by ADL to the overload
7671/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00007672void
Douglas Gregorfa047642009-02-04 00:32:51 +00007673Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00007674 bool Operator, SourceLocation Loc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007675 llvm::ArrayRef<Expr *> Args,
Douglas Gregor67714232011-03-03 02:41:12 +00007676 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007677 OverloadCandidateSet& CandidateSet,
Richard Smithb1502bc2012-10-18 17:56:02 +00007678 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00007679 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00007680
John McCalla113e722010-01-26 06:04:06 +00007681 // FIXME: This approach for uniquing ADL results (and removing
7682 // redundant candidates from the set) relies on pointer-equality,
7683 // which means we need to key off the canonical decl. However,
7684 // always going back to the canonical decl might not get us the
7685 // right set of default arguments. What default arguments are
7686 // we supposed to consider on ADL candidates, anyway?
7687
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007688 // FIXME: Pass in the explicit template arguments?
Richard Smithb1502bc2012-10-18 17:56:02 +00007689 ArgumentDependentLookup(Name, Operator, Loc, Args, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00007690
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007691 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007692 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
7693 CandEnd = CandidateSet.end();
7694 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00007695 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00007696 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00007697 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00007698 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00007699 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00007700
7701 // For each of the ADL candidates we found, add it to the overload
7702 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00007703 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00007704 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00007705 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00007706 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007707 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007708
Ahmed Charles13a140c2012-02-25 11:00:22 +00007709 AddOverloadCandidate(FD, FoundDecl, Args, CandidateSet, false,
7710 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007711 } else
John McCall6e266892010-01-26 03:27:55 +00007712 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00007713 FoundDecl, ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00007714 Args, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00007715 }
Douglas Gregorfa047642009-02-04 00:32:51 +00007716}
7717
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007718/// isBetterOverloadCandidate - Determines whether the first overload
7719/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00007720bool
John McCall120d63c2010-08-24 20:38:10 +00007721isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00007722 const OverloadCandidate &Cand1,
7723 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007724 SourceLocation Loc,
7725 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007726 // Define viable functions to be better candidates than non-viable
7727 // functions.
7728 if (!Cand2.Viable)
7729 return Cand1.Viable;
7730 else if (!Cand1.Viable)
7731 return false;
7732
Douglas Gregor88a35142008-12-22 05:46:06 +00007733 // C++ [over.match.best]p1:
7734 //
7735 // -- if F is a static member function, ICS1(F) is defined such
7736 // that ICS1(F) is neither better nor worse than ICS1(G) for
7737 // any function G, and, symmetrically, ICS1(G) is neither
7738 // better nor worse than ICS1(F).
7739 unsigned StartArg = 0;
7740 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
7741 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007742
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007743 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00007744 // A viable function F1 is defined to be a better function than another
7745 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007746 // conversion sequence than ICSi(F2), and then...
Benjamin Kramer09dd3792012-01-14 16:32:05 +00007747 unsigned NumArgs = Cand1.NumConversions;
7748 assert(Cand2.NumConversions == NumArgs && "Overload candidate mismatch");
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007749 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00007750 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00007751 switch (CompareImplicitConversionSequences(S,
7752 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007753 Cand2.Conversions[ArgIdx])) {
7754 case ImplicitConversionSequence::Better:
7755 // Cand1 has a better conversion sequence.
7756 HasBetterConversion = true;
7757 break;
7758
7759 case ImplicitConversionSequence::Worse:
7760 // Cand1 can't be better than Cand2.
7761 return false;
7762
7763 case ImplicitConversionSequence::Indistinguishable:
7764 // Do nothing.
7765 break;
7766 }
7767 }
7768
Mike Stump1eb44332009-09-09 15:08:12 +00007769 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007770 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007771 if (HasBetterConversion)
7772 return true;
7773
Mike Stump1eb44332009-09-09 15:08:12 +00007774 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007775 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007776 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007777 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7778 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007779
7780 // -- F1 and F2 are function template specializations, and the function
7781 // template for F1 is more specialized than the template for F2
7782 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007783 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007784 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007785 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007786 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007787 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7788 Cand2.Function->getPrimaryTemplate(),
7789 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007790 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007791 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007792 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007793 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007794 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007795
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007796 // -- the context is an initialization by user-defined conversion
7797 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7798 // from the return type of F1 to the destination type (i.e.,
7799 // the type of the entity being initialized) is a better
7800 // conversion sequence than the standard conversion sequence
7801 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007802 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007803 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007804 isa<CXXConversionDecl>(Cand2.Function)) {
Douglas Gregorb734e242012-02-22 17:32:19 +00007805 // First check whether we prefer one of the conversion functions over the
7806 // other. This only distinguishes the results in non-standard, extension
7807 // cases such as the conversion from a lambda closure type to a function
7808 // pointer or block.
7809 ImplicitConversionSequence::CompareKind FuncResult
7810 = compareConversionFunctions(S, Cand1.Function, Cand2.Function);
7811 if (FuncResult != ImplicitConversionSequence::Indistinguishable)
7812 return FuncResult;
7813
John McCall120d63c2010-08-24 20:38:10 +00007814 switch (CompareStandardConversionSequences(S,
7815 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007816 Cand2.FinalConversion)) {
7817 case ImplicitConversionSequence::Better:
7818 // Cand1 has a better conversion sequence.
7819 return true;
7820
7821 case ImplicitConversionSequence::Worse:
7822 // Cand1 can't be better than Cand2.
7823 return false;
7824
7825 case ImplicitConversionSequence::Indistinguishable:
7826 // Do nothing
7827 break;
7828 }
7829 }
7830
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007831 return false;
7832}
7833
Mike Stump1eb44332009-09-09 15:08:12 +00007834/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007835/// within an overload candidate set.
7836///
James Dennettefce31f2012-06-22 08:10:18 +00007837/// \param Loc The location of the function name (or operator symbol) for
Douglas Gregore0762c92009-06-19 23:52:42 +00007838/// which overload resolution occurs.
7839///
James Dennettefce31f2012-06-22 08:10:18 +00007840/// \param Best If overload resolution was successful or found a deleted
7841/// function, \p Best points to the candidate function found.
Douglas Gregore0762c92009-06-19 23:52:42 +00007842///
7843/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007844OverloadingResult
7845OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007846 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007847 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007848 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007849 Best = end();
7850 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7851 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007852 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007853 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007854 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007855 }
7856
7857 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007858 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007859 return OR_No_Viable_Function;
7860
7861 // Make sure that this function is better than every other viable
7862 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007863 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007864 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007865 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007866 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007867 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007868 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007869 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007870 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007871 }
Mike Stump1eb44332009-09-09 15:08:12 +00007872
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007873 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007874 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007875 (Best->Function->isDeleted() ||
7876 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007877 return OR_Deleted;
7878
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007879 return OR_Success;
7880}
7881
John McCall3c80f572010-01-12 02:15:36 +00007882namespace {
7883
7884enum OverloadCandidateKind {
7885 oc_function,
7886 oc_method,
7887 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007888 oc_function_template,
7889 oc_method_template,
7890 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007891 oc_implicit_default_constructor,
7892 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007893 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007894 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007895 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007896 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007897};
7898
John McCall220ccbf2010-01-13 00:25:19 +00007899OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7900 FunctionDecl *Fn,
7901 std::string &Description) {
7902 bool isTemplate = false;
7903
7904 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7905 isTemplate = true;
7906 Description = S.getTemplateArgumentBindingsText(
7907 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7908 }
John McCallb1622a12010-01-06 09:43:14 +00007909
7910 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007911 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007912 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007913
Sebastian Redlf677ea32011-02-05 19:23:19 +00007914 if (Ctor->getInheritedConstructor())
7915 return oc_implicit_inherited_constructor;
7916
Sean Hunt82713172011-05-25 23:16:36 +00007917 if (Ctor->isDefaultConstructor())
7918 return oc_implicit_default_constructor;
7919
7920 if (Ctor->isMoveConstructor())
7921 return oc_implicit_move_constructor;
7922
7923 assert(Ctor->isCopyConstructor() &&
7924 "unexpected sort of implicit constructor");
7925 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007926 }
7927
7928 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7929 // This actually gets spelled 'candidate function' for now, but
7930 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007931 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007932 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007933
Sean Hunt82713172011-05-25 23:16:36 +00007934 if (Meth->isMoveAssignmentOperator())
7935 return oc_implicit_move_assignment;
7936
Douglas Gregoref7d78b2012-02-10 08:36:38 +00007937 if (Meth->isCopyAssignmentOperator())
7938 return oc_implicit_copy_assignment;
7939
7940 assert(isa<CXXConversionDecl>(Meth) && "expected conversion");
7941 return oc_method;
John McCall3c80f572010-01-12 02:15:36 +00007942 }
7943
John McCall220ccbf2010-01-13 00:25:19 +00007944 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007945}
7946
Sebastian Redlf677ea32011-02-05 19:23:19 +00007947void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7948 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7949 if (!Ctor) return;
7950
7951 Ctor = Ctor->getInheritedConstructor();
7952 if (!Ctor) return;
7953
7954 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7955}
7956
John McCall3c80f572010-01-12 02:15:36 +00007957} // end anonymous namespace
7958
7959// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007960void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007961 std::string FnDesc;
7962 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007963 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7964 << (unsigned) K << FnDesc;
7965 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7966 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007967 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007968}
7969
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007970//Notes the location of all overload candidates designated through
7971// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007972void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007973 assert(OverloadedExpr->getType() == Context.OverloadTy);
7974
7975 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7976 OverloadExpr *OvlExpr = Ovl.Expression;
7977
7978 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7979 IEnd = OvlExpr->decls_end();
7980 I != IEnd; ++I) {
7981 if (FunctionTemplateDecl *FunTmpl =
7982 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007983 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007984 } else if (FunctionDecl *Fun
7985 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007986 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007987 }
7988 }
7989}
7990
John McCall1d318332010-01-12 00:44:57 +00007991/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7992/// "lead" diagnostic; it will be given two arguments, the source and
7993/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007994void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7995 Sema &S,
7996 SourceLocation CaretLoc,
7997 const PartialDiagnostic &PDiag) const {
7998 S.Diag(CaretLoc, PDiag)
7999 << Ambiguous.getFromType() << Ambiguous.getToType();
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008000 // FIXME: The note limiting machinery is borrowed from
8001 // OverloadCandidateSet::NoteCandidates; there's an opportunity for
8002 // refactoring here.
8003 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
8004 unsigned CandsShown = 0;
8005 AmbiguousConversionSequence::const_iterator I, E;
8006 for (I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
8007 if (CandsShown >= 4 && ShowOverloads == Ovl_Best)
8008 break;
8009 ++CandsShown;
John McCall120d63c2010-08-24 20:38:10 +00008010 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00008011 }
Matt Beaumont-Gay45a37da2012-11-08 20:50:02 +00008012 if (I != E)
8013 S.Diag(SourceLocation(), diag::note_ovl_too_many_candidates) << int(E - I);
John McCall81201622010-01-08 04:41:39 +00008014}
8015
John McCall1d318332010-01-12 00:44:57 +00008016namespace {
8017
John McCalladbb8f82010-01-13 09:16:55 +00008018void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
8019 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
8020 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00008021 assert(Cand->Function && "for now, candidate must be a function");
8022 FunctionDecl *Fn = Cand->Function;
8023
8024 // There's a conversion slot for the object argument if this is a
8025 // non-constructor method. Note that 'I' corresponds the
8026 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00008027 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00008028 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00008029 if (I == 0)
8030 isObjectArgument = true;
8031 else
8032 I--;
John McCall220ccbf2010-01-13 00:25:19 +00008033 }
8034
John McCall220ccbf2010-01-13 00:25:19 +00008035 std::string FnDesc;
8036 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
8037
John McCalladbb8f82010-01-13 09:16:55 +00008038 Expr *FromExpr = Conv.Bad.FromExpr;
8039 QualType FromTy = Conv.Bad.getFromType();
8040 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00008041
John McCall5920dbb2010-02-02 02:42:52 +00008042 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00008043 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00008044 Expr *E = FromExpr->IgnoreParens();
8045 if (isa<UnaryOperator>(E))
8046 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00008047 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00008048
8049 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
8050 << (unsigned) FnKind << FnDesc
8051 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8052 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008053 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00008054 return;
8055 }
8056
John McCall258b2032010-01-23 08:10:49 +00008057 // Do some hand-waving analysis to see if the non-viability is due
8058 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00008059 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
8060 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
8061 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
8062 CToTy = RT->getPointeeType();
8063 else {
8064 // TODO: detect and diagnose the full richness of const mismatches.
8065 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
8066 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
8067 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
8068 }
8069
8070 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
8071 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
John McCall651f3ee2010-01-14 03:28:57 +00008072 Qualifiers FromQs = CFromTy.getQualifiers();
8073 Qualifiers ToQs = CToTy.getQualifiers();
8074
8075 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
8076 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
8077 << (unsigned) FnKind << FnDesc
8078 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8079 << FromTy
8080 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
8081 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008082 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008083 return;
8084 }
8085
John McCallf85e1932011-06-15 23:02:42 +00008086 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00008087 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00008088 << (unsigned) FnKind << FnDesc
8089 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8090 << FromTy
8091 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
8092 << (unsigned) isObjectArgument << I+1;
8093 MaybeEmitInheritedConstructorNote(S, Fn);
8094 return;
8095 }
8096
Douglas Gregor028ea4b2011-04-26 23:16:46 +00008097 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
8098 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
8099 << (unsigned) FnKind << FnDesc
8100 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8101 << FromTy
8102 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
8103 << (unsigned) isObjectArgument << I+1;
8104 MaybeEmitInheritedConstructorNote(S, Fn);
8105 return;
8106 }
8107
John McCall651f3ee2010-01-14 03:28:57 +00008108 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
8109 assert(CVR && "unexpected qualifiers mismatch");
8110
8111 if (isObjectArgument) {
8112 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
8113 << (unsigned) FnKind << FnDesc
8114 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8115 << FromTy << (CVR - 1);
8116 } else {
8117 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
8118 << (unsigned) FnKind << FnDesc
8119 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8120 << FromTy << (CVR - 1) << I+1;
8121 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008122 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00008123 return;
8124 }
8125
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00008126 // Special diagnostic for failure to convert an initializer list, since
8127 // telling the user that it has type void is not useful.
8128 if (FromExpr && isa<InitListExpr>(FromExpr)) {
8129 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
8130 << (unsigned) FnKind << FnDesc
8131 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8132 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8133 MaybeEmitInheritedConstructorNote(S, Fn);
8134 return;
8135 }
8136
John McCall258b2032010-01-23 08:10:49 +00008137 // Diagnose references or pointers to incomplete types differently,
8138 // since it's far from impossible that the incompleteness triggered
8139 // the failure.
8140 QualType TempFromTy = FromTy.getNonReferenceType();
8141 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
8142 TempFromTy = PTy->getPointeeType();
8143 if (TempFromTy->isIncompleteType()) {
8144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
8145 << (unsigned) FnKind << FnDesc
8146 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8147 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008148 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00008149 return;
8150 }
8151
Douglas Gregor85789812010-06-30 23:01:39 +00008152 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008153 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00008154 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
8155 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
8156 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8157 FromPtrTy->getPointeeType()) &&
8158 !FromPtrTy->getPointeeType()->isIncompleteType() &&
8159 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008160 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00008161 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008162 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00008163 }
8164 } else if (const ObjCObjectPointerType *FromPtrTy
8165 = FromTy->getAs<ObjCObjectPointerType>()) {
8166 if (const ObjCObjectPointerType *ToPtrTy
8167 = ToTy->getAs<ObjCObjectPointerType>())
8168 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
8169 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
8170 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
8171 FromPtrTy->getPointeeType()) &&
8172 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008173 BaseToDerivedConversion = 2;
8174 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008175 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
8176 !FromTy->isIncompleteType() &&
8177 !ToRefTy->getPointeeType()->isIncompleteType() &&
8178 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy)) {
8179 BaseToDerivedConversion = 3;
8180 } else if (ToTy->isLValueReferenceType() && !FromExpr->isLValue() &&
8181 ToTy.getNonReferenceType().getCanonicalType() ==
8182 FromTy.getNonReferenceType().getCanonicalType()) {
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008183 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_lvalue)
8184 << (unsigned) FnKind << FnDesc
8185 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8186 << (unsigned) isObjectArgument << I + 1;
8187 MaybeEmitInheritedConstructorNote(S, Fn);
8188 return;
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008189 }
Kaelyn Uhrain0d3317e2012-06-19 00:37:47 +00008190 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008191
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008192 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008193 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008194 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00008195 << (unsigned) FnKind << FnDesc
8196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00008197 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008198 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008199 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00008200 return;
8201 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008202
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00008203 if (isa<ObjCObjectPointerType>(CFromTy) &&
8204 isa<PointerType>(CToTy)) {
8205 Qualifiers FromQs = CFromTy.getQualifiers();
8206 Qualifiers ToQs = CToTy.getQualifiers();
8207 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
8208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
8209 << (unsigned) FnKind << FnDesc
8210 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
8211 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
8212 MaybeEmitInheritedConstructorNote(S, Fn);
8213 return;
8214 }
8215 }
8216
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008217 // Emit the generic diagnostic and, optionally, add the hints to it.
8218 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
8219 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00008220 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008221 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
8222 << (unsigned) (Cand->Fix.Kind);
8223
8224 // If we can fix the conversion, suggest the FixIts.
Benjamin Kramer1136ef02012-01-14 21:05:10 +00008225 for (std::vector<FixItHint>::iterator HI = Cand->Fix.Hints.begin(),
8226 HE = Cand->Fix.Hints.end(); HI != HE; ++HI)
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008227 FDiag << *HI;
8228 S.Diag(Fn->getLocation(), FDiag);
8229
Sebastian Redlf677ea32011-02-05 19:23:19 +00008230 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00008231}
8232
8233void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
8234 unsigned NumFormalArgs) {
8235 // TODO: treat calls to a missing default constructor as a special case
8236
8237 FunctionDecl *Fn = Cand->Function;
8238 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
8239
8240 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008241
Douglas Gregor439d3c32011-05-05 00:13:13 +00008242 // With invalid overloaded operators, it's possible that we think we
8243 // have an arity mismatch when it fact it looks like we have the
8244 // right number of arguments, because only overloaded operators have
8245 // the weird behavior of overloading member and non-member functions.
8246 // Just don't report anything.
8247 if (Fn->isInvalidDecl() &&
8248 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
8249 return;
8250
John McCalladbb8f82010-01-13 09:16:55 +00008251 // at least / at most / exactly
8252 unsigned mode, modeCount;
8253 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00008254 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
8255 (Cand->FailureKind == ovl_fail_bad_deduction &&
8256 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008257 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00008258 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00008259 mode = 0; // "at least"
8260 else
8261 mode = 2; // "exactly"
8262 modeCount = MinParams;
8263 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00008264 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
8265 (Cand->FailureKind == ovl_fail_bad_deduction &&
8266 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00008267 if (MinParams != FnTy->getNumArgs())
8268 mode = 1; // "at most"
8269 else
8270 mode = 2; // "exactly"
8271 modeCount = FnTy->getNumArgs();
8272 }
8273
8274 std::string Description;
8275 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
8276
Richard Smithf7b80562012-05-11 05:16:41 +00008277 if (modeCount == 1 && Fn->getParamDecl(0)->getDeclName())
8278 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity_one)
8279 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8280 << Fn->getParamDecl(0) << NumFormalArgs;
8281 else
8282 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
8283 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
8284 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008285 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008286}
8287
John McCall342fec42010-02-01 18:53:26 +00008288/// Diagnose a failed template-argument deduction.
8289void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008290 unsigned NumArgs) {
John McCall342fec42010-02-01 18:53:26 +00008291 FunctionDecl *Fn = Cand->Function; // pattern
8292
Douglas Gregora9333192010-05-08 17:41:32 +00008293 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00008294 NamedDecl *ParamD;
8295 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
8296 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
8297 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00008298 switch (Cand->DeductionFailure.Result) {
8299 case Sema::TDK_Success:
8300 llvm_unreachable("TDK_success while diagnosing bad deduction");
8301
8302 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00008303 assert(ParamD && "no parameter found for incomplete deduction result");
8304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
8305 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008306 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008307 return;
8308 }
8309
John McCall57e97782010-08-05 09:05:08 +00008310 case Sema::TDK_Underqualified: {
8311 assert(ParamD && "no parameter found for bad qualifiers deduction result");
8312 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
8313
8314 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
8315
8316 // Param will have been canonicalized, but it should just be a
8317 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00008318 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00008319 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00008320 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00008321 assert(S.Context.hasSameType(Param, NonCanonParam));
8322
8323 // Arg has also been canonicalized, but there's nothing we can do
8324 // about that. It also doesn't matter as much, because it won't
8325 // have any template parameters in it (because deduction isn't
8326 // done on dependent types).
8327 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
8328
8329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
8330 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008331 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00008332 return;
8333 }
8334
8335 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008336 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00008337 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008338 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008339 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00008340 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00008341 which = 1;
8342 else {
Douglas Gregora9333192010-05-08 17:41:32 +00008343 which = 2;
8344 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008345
Douglas Gregora9333192010-05-08 17:41:32 +00008346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008347 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00008348 << *Cand->DeductionFailure.getFirstArg()
8349 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00008350 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00008351 return;
8352 }
Douglas Gregora18592e2010-05-08 18:13:28 +00008353
Douglas Gregorf1a84452010-05-08 19:15:54 +00008354 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008355 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00008356 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008357 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008358 diag::note_ovl_candidate_explicit_arg_mismatch_named)
8359 << ParamD->getDeclName();
8360 else {
8361 int index = 0;
8362 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
8363 index = TTP->getIndex();
8364 else if (NonTypeTemplateParmDecl *NTTP
8365 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
8366 index = NTTP->getIndex();
8367 else
8368 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008369 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00008370 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
8371 << (index + 1);
8372 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00008373 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00008374 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008375
Douglas Gregora18592e2010-05-08 18:13:28 +00008376 case Sema::TDK_TooManyArguments:
8377 case Sema::TDK_TooFewArguments:
8378 DiagnoseArityMismatch(S, Cand, NumArgs);
8379 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00008380
8381 case Sema::TDK_InstantiationDepth:
8382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008383 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008384 return;
8385
8386 case Sema::TDK_SubstitutionFailure: {
Richard Smithb8590f32012-05-07 09:03:25 +00008387 // Format the template argument list into the argument string.
8388 llvm::SmallString<128> TemplateArgString;
8389 if (TemplateArgumentList *Args =
8390 Cand->DeductionFailure.getTemplateArgumentList()) {
8391 TemplateArgString = " ";
8392 TemplateArgString += S.getTemplateArgumentBindingsText(
8393 Fn->getDescribedFunctionTemplate()->getTemplateParameters(), *Args);
8394 }
8395
Richard Smith4493c0a2012-05-09 05:17:00 +00008396 // If this candidate was disabled by enable_if, say so.
8397 PartialDiagnosticAt *PDiag = Cand->DeductionFailure.getSFINAEDiagnostic();
8398 if (PDiag && PDiag->second.getDiagID() ==
8399 diag::err_typename_nested_not_found_enable_if) {
8400 // FIXME: Use the source range of the condition, and the fully-qualified
8401 // name of the enable_if template. These are both present in PDiag.
8402 S.Diag(PDiag->first, diag::note_ovl_candidate_disabled_by_enable_if)
8403 << "'enable_if'" << TemplateArgString;
8404 return;
8405 }
8406
Richard Smithb8590f32012-05-07 09:03:25 +00008407 // Format the SFINAE diagnostic into the argument string.
8408 // FIXME: Add a general mechanism to include a PartialDiagnostic *'s
8409 // formatted message in another diagnostic.
8410 llvm::SmallString<128> SFINAEArgString;
8411 SourceRange R;
Richard Smith4493c0a2012-05-09 05:17:00 +00008412 if (PDiag) {
Richard Smithb8590f32012-05-07 09:03:25 +00008413 SFINAEArgString = ": ";
8414 R = SourceRange(PDiag->first, PDiag->first);
8415 PDiag->second.EmitToString(S.getDiagnostics(), SFINAEArgString);
8416 }
8417
Douglas Gregorec20f462010-05-08 20:07:26 +00008418 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
Richard Smithb8590f32012-05-07 09:03:25 +00008419 << TemplateArgString << SFINAEArgString << R;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008420 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00008421 return;
8422 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008423
John McCall342fec42010-02-01 18:53:26 +00008424 // TODO: diagnose these individually, then kill off
8425 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00008426 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00008427 case Sema::TDK_FailedOverloadResolution:
8428 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008429 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00008430 return;
8431 }
8432}
8433
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008434/// CUDA: diagnose an invalid call across targets.
8435void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
8436 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
8437 FunctionDecl *Callee = Cand->Function;
8438
8439 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
8440 CalleeTarget = S.IdentifyCUDATarget(Callee);
8441
8442 std::string FnDesc;
8443 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
8444
8445 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
8446 << (unsigned) FnKind << CalleeTarget << CallerTarget;
8447}
8448
John McCall342fec42010-02-01 18:53:26 +00008449/// Generates a 'note' diagnostic for an overload candidate. We've
8450/// already generated a primary error at the call site.
8451///
8452/// It really does need to be a single diagnostic with its caret
8453/// pointed at the candidate declaration. Yes, this creates some
8454/// major challenges of technical writing. Yes, this makes pointing
8455/// out problems with specific arguments quite awkward. It's still
8456/// better than generating twenty screens of text for every failed
8457/// overload.
8458///
8459/// It would be great to be able to express per-candidate problems
8460/// more richly for those diagnostic clients that cared, but we'd
8461/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00008462void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008463 unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00008464 FunctionDecl *Fn = Cand->Function;
8465
John McCall81201622010-01-08 04:41:39 +00008466 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00008467 if (Cand->Viable && (Fn->isDeleted() ||
8468 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00008469 std::string FnDesc;
8470 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00008471
8472 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
Richard Smith5bdaac52012-04-02 20:59:25 +00008473 << FnKind << FnDesc
8474 << (Fn->isDeleted() ? (Fn->isDeletedAsWritten() ? 1 : 2) : 0);
Sebastian Redlf677ea32011-02-05 19:23:19 +00008475 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00008476 return;
John McCall81201622010-01-08 04:41:39 +00008477 }
8478
John McCall220ccbf2010-01-13 00:25:19 +00008479 // We don't really have anything else to say about viable candidates.
8480 if (Cand->Viable) {
8481 S.NoteOverloadCandidate(Fn);
8482 return;
8483 }
John McCall1d318332010-01-12 00:44:57 +00008484
John McCalladbb8f82010-01-13 09:16:55 +00008485 switch (Cand->FailureKind) {
8486 case ovl_fail_too_many_arguments:
8487 case ovl_fail_too_few_arguments:
8488 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00008489
John McCalladbb8f82010-01-13 09:16:55 +00008490 case ovl_fail_bad_deduction:
Ahmed Charles13a140c2012-02-25 11:00:22 +00008491 return DiagnoseBadDeduction(S, Cand, NumArgs);
John McCall342fec42010-02-01 18:53:26 +00008492
John McCall717e8912010-01-23 05:17:32 +00008493 case ovl_fail_trivial_conversion:
8494 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00008495 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00008496 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008497
John McCallb1bdc622010-02-25 01:37:24 +00008498 case ovl_fail_bad_conversion: {
8499 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008500 for (unsigned N = Cand->NumConversions; I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00008501 if (Cand->Conversions[I].isBad())
8502 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008503
John McCalladbb8f82010-01-13 09:16:55 +00008504 // FIXME: this currently happens when we're called from SemaInit
8505 // when user-conversion overload fails. Figure out how to handle
8506 // those conditions and diagnose them well.
8507 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00008508 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008509
8510 case ovl_fail_bad_target:
8511 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00008512 }
John McCalla1d7d622010-01-08 00:58:21 +00008513}
8514
8515void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
8516 // Desugar the type of the surrogate down to a function type,
8517 // retaining as many typedefs as possible while still showing
8518 // the function type (and, therefore, its parameter types).
8519 QualType FnType = Cand->Surrogate->getConversionType();
8520 bool isLValueReference = false;
8521 bool isRValueReference = false;
8522 bool isPointer = false;
8523 if (const LValueReferenceType *FnTypeRef =
8524 FnType->getAs<LValueReferenceType>()) {
8525 FnType = FnTypeRef->getPointeeType();
8526 isLValueReference = true;
8527 } else if (const RValueReferenceType *FnTypeRef =
8528 FnType->getAs<RValueReferenceType>()) {
8529 FnType = FnTypeRef->getPointeeType();
8530 isRValueReference = true;
8531 }
8532 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
8533 FnType = FnTypePtr->getPointeeType();
8534 isPointer = true;
8535 }
8536 // Desugar down to a function type.
8537 FnType = QualType(FnType->getAs<FunctionType>(), 0);
8538 // Reconstruct the pointer/reference as appropriate.
8539 if (isPointer) FnType = S.Context.getPointerType(FnType);
8540 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
8541 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
8542
8543 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
8544 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00008545 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00008546}
8547
8548void NoteBuiltinOperatorCandidate(Sema &S,
David Blaikie0bea8632012-10-08 01:11:04 +00008549 StringRef Opc,
John McCalla1d7d622010-01-08 00:58:21 +00008550 SourceLocation OpLoc,
8551 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008552 assert(Cand->NumConversions <= 2 && "builtin operator is not binary");
John McCalla1d7d622010-01-08 00:58:21 +00008553 std::string TypeStr("operator");
8554 TypeStr += Opc;
8555 TypeStr += "(";
8556 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008557 if (Cand->NumConversions == 1) {
John McCalla1d7d622010-01-08 00:58:21 +00008558 TypeStr += ")";
8559 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
8560 } else {
8561 TypeStr += ", ";
8562 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
8563 TypeStr += ")";
8564 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
8565 }
8566}
8567
8568void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
8569 OverloadCandidate *Cand) {
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008570 unsigned NoOperands = Cand->NumConversions;
John McCalla1d7d622010-01-08 00:58:21 +00008571 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
8572 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00008573 if (ICS.isBad()) break; // all meaningless after first invalid
8574 if (!ICS.isAmbiguous()) continue;
8575
John McCall120d63c2010-08-24 20:38:10 +00008576 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008577 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00008578 }
8579}
8580
John McCall1b77e732010-01-15 23:32:50 +00008581SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
8582 if (Cand->Function)
8583 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00008584 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00008585 return Cand->Surrogate->getLocation();
8586 return SourceLocation();
8587}
8588
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008589static unsigned
8590RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00008591 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008592 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00008593 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008594
Douglas Gregorae19fbb2012-09-13 21:01:57 +00008595 case Sema::TDK_Invalid:
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008596 case Sema::TDK_Incomplete:
8597 return 1;
8598
8599 case Sema::TDK_Underqualified:
8600 case Sema::TDK_Inconsistent:
8601 return 2;
8602
8603 case Sema::TDK_SubstitutionFailure:
8604 case Sema::TDK_NonDeducedMismatch:
8605 return 3;
8606
8607 case Sema::TDK_InstantiationDepth:
8608 case Sema::TDK_FailedOverloadResolution:
8609 return 4;
8610
8611 case Sema::TDK_InvalidExplicitArguments:
8612 return 5;
8613
8614 case Sema::TDK_TooManyArguments:
8615 case Sema::TDK_TooFewArguments:
8616 return 6;
8617 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00008618 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008619}
8620
John McCallbf65c0b2010-01-12 00:48:53 +00008621struct CompareOverloadCandidatesForDisplay {
8622 Sema &S;
8623 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00008624
8625 bool operator()(const OverloadCandidate *L,
8626 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00008627 // Fast-path this check.
8628 if (L == R) return false;
8629
John McCall81201622010-01-08 04:41:39 +00008630 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00008631 if (L->Viable) {
8632 if (!R->Viable) return true;
8633
8634 // TODO: introduce a tri-valued comparison for overload
8635 // candidates. Would be more worthwhile if we had a sort
8636 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00008637 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
8638 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00008639 } else if (R->Viable)
8640 return false;
John McCall81201622010-01-08 04:41:39 +00008641
John McCall1b77e732010-01-15 23:32:50 +00008642 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00008643
John McCall1b77e732010-01-15 23:32:50 +00008644 // Criteria by which we can sort non-viable candidates:
8645 if (!L->Viable) {
8646 // 1. Arity mismatches come after other candidates.
8647 if (L->FailureKind == ovl_fail_too_many_arguments ||
8648 L->FailureKind == ovl_fail_too_few_arguments)
8649 return false;
8650 if (R->FailureKind == ovl_fail_too_many_arguments ||
8651 R->FailureKind == ovl_fail_too_few_arguments)
8652 return true;
John McCall81201622010-01-08 04:41:39 +00008653
John McCall717e8912010-01-23 05:17:32 +00008654 // 2. Bad conversions come first and are ordered by the number
8655 // of bad conversions and quality of good conversions.
8656 if (L->FailureKind == ovl_fail_bad_conversion) {
8657 if (R->FailureKind != ovl_fail_bad_conversion)
8658 return true;
8659
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008660 // The conversion that can be fixed with a smaller number of changes,
8661 // comes first.
8662 unsigned numLFixes = L->Fix.NumConversionsFixed;
8663 unsigned numRFixes = R->Fix.NumConversionsFixed;
8664 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
8665 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008666 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008667 if (numLFixes < numRFixes)
8668 return true;
8669 else
8670 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00008671 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008672
John McCall717e8912010-01-23 05:17:32 +00008673 // If there's any ordering between the defined conversions...
8674 // FIXME: this might not be transitive.
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008675 assert(L->NumConversions == R->NumConversions);
John McCall717e8912010-01-23 05:17:32 +00008676
8677 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00008678 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008679 for (unsigned E = L->NumConversions; I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00008680 switch (CompareImplicitConversionSequences(S,
8681 L->Conversions[I],
8682 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00008683 case ImplicitConversionSequence::Better:
8684 leftBetter++;
8685 break;
8686
8687 case ImplicitConversionSequence::Worse:
8688 leftBetter--;
8689 break;
8690
8691 case ImplicitConversionSequence::Indistinguishable:
8692 break;
8693 }
8694 }
8695 if (leftBetter > 0) return true;
8696 if (leftBetter < 0) return false;
8697
8698 } else if (R->FailureKind == ovl_fail_bad_conversion)
8699 return false;
8700
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008701 if (L->FailureKind == ovl_fail_bad_deduction) {
8702 if (R->FailureKind != ovl_fail_bad_deduction)
8703 return true;
8704
8705 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
8706 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00008707 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00008708 } else if (R->FailureKind == ovl_fail_bad_deduction)
8709 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00008710
John McCall1b77e732010-01-15 23:32:50 +00008711 // TODO: others?
8712 }
8713
8714 // Sort everything else by location.
8715 SourceLocation LLoc = GetLocationForCandidate(L);
8716 SourceLocation RLoc = GetLocationForCandidate(R);
8717
8718 // Put candidates without locations (e.g. builtins) at the end.
8719 if (LLoc.isInvalid()) return false;
8720 if (RLoc.isInvalid()) return true;
8721
8722 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00008723 }
8724};
8725
John McCall717e8912010-01-23 05:17:32 +00008726/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008727/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00008728void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008729 llvm::ArrayRef<Expr *> Args) {
John McCall717e8912010-01-23 05:17:32 +00008730 assert(!Cand->Viable);
8731
8732 // Don't do anything on failures other than bad conversion.
8733 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
8734
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008735 // We only want the FixIts if all the arguments can be corrected.
8736 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00008737 // Use a implicit copy initialization to check conversion fixes.
8738 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008739
John McCall717e8912010-01-23 05:17:32 +00008740 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00008741 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
Benjamin Kramer09dd3792012-01-14 16:32:05 +00008742 unsigned ConvCount = Cand->NumConversions;
John McCall717e8912010-01-23 05:17:32 +00008743 while (true) {
8744 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
8745 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008746 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00008747 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00008748 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008749 }
John McCall717e8912010-01-23 05:17:32 +00008750 }
8751
8752 if (ConvIdx == ConvCount)
8753 return;
8754
John McCallb1bdc622010-02-25 01:37:24 +00008755 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
8756 "remaining conversion is initialized?");
8757
Douglas Gregor23ef6c02010-04-16 17:45:54 +00008758 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00008759 // operation somehow.
8760 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00008761
8762 const FunctionProtoType* Proto;
8763 unsigned ArgIdx = ConvIdx;
8764
8765 if (Cand->IsSurrogate) {
8766 QualType ConvType
8767 = Cand->Surrogate->getConversionType().getNonReferenceType();
8768 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8769 ConvType = ConvPtrType->getPointeeType();
8770 Proto = ConvType->getAs<FunctionProtoType>();
8771 ArgIdx--;
8772 } else if (Cand->Function) {
8773 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
8774 if (isa<CXXMethodDecl>(Cand->Function) &&
8775 !isa<CXXConstructorDecl>(Cand->Function))
8776 ArgIdx--;
8777 } else {
8778 // Builtin binary operator with a bad first conversion.
8779 assert(ConvCount <= 3);
8780 for (; ConvIdx != ConvCount; ++ConvIdx)
8781 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008782 = TryCopyInitialization(S, Args[ConvIdx],
8783 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008784 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008785 /*InOverloadResolution*/ true,
8786 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008787 S.getLangOpts().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00008788 return;
8789 }
8790
8791 // Fill in the rest of the conversions.
8792 unsigned NumArgsInProto = Proto->getNumArgs();
8793 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008794 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00008795 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00008796 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008797 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00008798 /*InOverloadResolution=*/true,
8799 /*AllowObjCWritebackConversion=*/
David Blaikie4e4d0842012-03-11 07:00:24 +00008800 S.getLangOpts().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008801 // Store the FixIt in the candidate if it exists.
8802 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00008803 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00008804 }
John McCall717e8912010-01-23 05:17:32 +00008805 else
8806 Cand->Conversions[ConvIdx].setEllipsis();
8807 }
8808}
8809
John McCalla1d7d622010-01-08 00:58:21 +00008810} // end anonymous namespace
8811
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008812/// PrintOverloadCandidates - When overload resolution fails, prints
8813/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008814/// set.
John McCall120d63c2010-08-24 20:38:10 +00008815void OverloadCandidateSet::NoteCandidates(Sema &S,
8816 OverloadCandidateDisplayKind OCD,
Ahmed Charles13a140c2012-02-25 11:00:22 +00008817 llvm::ArrayRef<Expr *> Args,
David Blaikie0bea8632012-10-08 01:11:04 +00008818 StringRef Opc,
John McCall120d63c2010-08-24 20:38:10 +00008819 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008820 // Sort the candidates by viability and position. Sorting directly would
8821 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008822 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008823 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8824 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008825 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008826 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008827 else if (OCD == OCD_AllCandidates) {
Ahmed Charles13a140c2012-02-25 11:00:22 +00008828 CompleteNonViableCandidate(S, Cand, Args);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008829 if (Cand->Function || Cand->IsSurrogate)
8830 Cands.push_back(Cand);
8831 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8832 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008833 }
8834 }
8835
John McCallbf65c0b2010-01-12 00:48:53 +00008836 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008837 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008838
John McCall1d318332010-01-12 00:44:57 +00008839 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008840
Chris Lattner5f9e2722011-07-23 10:55:15 +00008841 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Douglas Gregordc7b6412012-10-23 23:11:23 +00008842 const OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008843 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008844 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8845 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008846
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008847 // Set an arbitrary limit on the number of candidate functions we'll spam
8848 // the user with. FIXME: This limit should depend on details of the
8849 // candidate list.
Douglas Gregordc7b6412012-10-23 23:11:23 +00008850 if (CandsShown >= 4 && ShowOverloads == Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008851 break;
8852 }
8853 ++CandsShown;
8854
John McCalla1d7d622010-01-08 00:58:21 +00008855 if (Cand->Function)
Ahmed Charles13a140c2012-02-25 11:00:22 +00008856 NoteFunctionCandidate(S, Cand, Args.size());
John McCalla1d7d622010-01-08 00:58:21 +00008857 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008858 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008859 else {
8860 assert(Cand->Viable &&
8861 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008862 // Generally we only see ambiguities including viable builtin
8863 // operators if overload resolution got screwed up by an
8864 // ambiguous user-defined conversion.
8865 //
8866 // FIXME: It's quite possible for different conversions to see
8867 // different ambiguities, though.
8868 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008869 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008870 ReportedAmbiguousConversions = true;
8871 }
John McCalla1d7d622010-01-08 00:58:21 +00008872
John McCall1d318332010-01-12 00:44:57 +00008873 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008874 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008875 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008876 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008877
8878 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008879 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008880}
8881
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008882// [PossiblyAFunctionType] --> [Return]
8883// NonFunctionType --> NonFunctionType
8884// R (A) --> R(A)
8885// R (*)(A) --> R (A)
8886// R (&)(A) --> R (A)
8887// R (S::*)(A) --> R (A)
8888QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8889 QualType Ret = PossiblyAFunctionType;
8890 if (const PointerType *ToTypePtr =
8891 PossiblyAFunctionType->getAs<PointerType>())
8892 Ret = ToTypePtr->getPointeeType();
8893 else if (const ReferenceType *ToTypeRef =
8894 PossiblyAFunctionType->getAs<ReferenceType>())
8895 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008896 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008897 PossiblyAFunctionType->getAs<MemberPointerType>())
8898 Ret = MemTypePtr->getPointeeType();
8899 Ret =
8900 Context.getCanonicalType(Ret).getUnqualifiedType();
8901 return Ret;
8902}
Douglas Gregor904eed32008-11-10 20:40:00 +00008903
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008904// A helper class to help with address of function resolution
8905// - allows us to avoid passing around all those ugly parameters
8906class AddressOfFunctionResolver
8907{
8908 Sema& S;
8909 Expr* SourceExpr;
8910 const QualType& TargetType;
8911 QualType TargetFunctionType; // Extracted function type from target type
8912
8913 bool Complain;
8914 //DeclAccessPair& ResultFunctionAccessPair;
8915 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008916
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008917 bool TargetTypeIsNonStaticMemberFunction;
8918 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008919
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008920 OverloadExpr::FindResult OvlExprInfo;
8921 OverloadExpr *OvlExpr;
8922 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008923 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008924
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008925public:
8926 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8927 const QualType& TargetType, bool Complain)
8928 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8929 Complain(Complain), Context(S.getASTContext()),
8930 TargetTypeIsNonStaticMemberFunction(
8931 !!TargetType->getAs<MemberPointerType>()),
8932 FoundNonTemplateFunction(false),
8933 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8934 OvlExpr(OvlExprInfo.Expression)
8935 {
8936 ExtractUnqualifiedFunctionTypeFromTargetType();
8937
8938 if (!TargetFunctionType->isFunctionType()) {
8939 if (OvlExpr->hasExplicitTemplateArgs()) {
8940 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008941 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008942 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008943
8944 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8945 if (!Method->isStatic()) {
8946 // If the target type is a non-function type and the function
8947 // found is a non-static member function, pretend as if that was
8948 // the target, it's the only possible type to end up with.
8949 TargetTypeIsNonStaticMemberFunction = true;
8950
8951 // And skip adding the function if its not in the proper form.
8952 // We'll diagnose this due to an empty set of functions.
8953 if (!OvlExprInfo.HasFormOfMemberPointer)
8954 return;
8955 }
8956 }
8957
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008958 Matches.push_back(std::make_pair(dap,Fn));
8959 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008960 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008961 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008962 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008963
8964 if (OvlExpr->hasExplicitTemplateArgs())
8965 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008966
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008967 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8968 // C++ [over.over]p4:
8969 // If more than one function is selected, [...]
8970 if (Matches.size() > 1) {
8971 if (FoundNonTemplateFunction)
8972 EliminateAllTemplateMatches();
8973 else
8974 EliminateAllExceptMostSpecializedTemplate();
8975 }
8976 }
8977 }
8978
8979private:
8980 bool isTargetTypeAFunction() const {
8981 return TargetFunctionType->isFunctionType();
8982 }
8983
8984 // [ToType] [Return]
8985
8986 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8987 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8988 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8989 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8990 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8991 }
8992
8993 // return true if any matching specializations were found
8994 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8995 const DeclAccessPair& CurAccessFunPair) {
8996 if (CXXMethodDecl *Method
8997 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8998 // Skip non-static function templates when converting to pointer, and
8999 // static when converting to member pointer.
9000 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9001 return false;
9002 }
9003 else if (TargetTypeIsNonStaticMemberFunction)
9004 return false;
9005
9006 // C++ [over.over]p2:
9007 // If the name is a function template, template argument deduction is
9008 // done (14.8.2.2), and if the argument deduction succeeds, the
9009 // resulting template argument list is used to generate a single
9010 // function template specialization, which is added to the set of
9011 // overloaded functions considered.
9012 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009013 TemplateDeductionInfo Info(OvlExpr->getNameLoc());
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009014 if (Sema::TemplateDeductionResult Result
9015 = S.DeduceTemplateArguments(FunctionTemplate,
9016 &OvlExplicitTemplateArgs,
9017 TargetFunctionType, Specialization,
9018 Info)) {
9019 // FIXME: make a note of the failed deduction for diagnostics.
9020 (void)Result;
9021 return false;
9022 }
9023
9024 // Template argument deduction ensures that we have an exact match.
9025 // This function template specicalization works.
9026 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
9027 assert(TargetFunctionType
9028 == Context.getCanonicalType(Specialization->getType()));
9029 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
9030 return true;
9031 }
9032
9033 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
9034 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00009035 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00009036 // Skip non-static functions when converting to pointer, and static
9037 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009038 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
9039 return false;
9040 }
9041 else if (TargetTypeIsNonStaticMemberFunction)
9042 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00009043
Chandler Carruthbd647292009-12-29 06:17:27 +00009044 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009045 if (S.getLangOpts().CUDA)
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00009046 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
9047 if (S.CheckCUDATarget(Caller, FunDecl))
9048 return false;
9049
Douglas Gregor43c79c22009-12-09 00:47:37 +00009050 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009051 if (Context.hasSameUnqualifiedType(TargetFunctionType,
9052 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00009053 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
9054 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009055 Matches.push_back(std::make_pair(CurAccessFunPair,
9056 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00009057 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009058 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00009059 }
Mike Stump1eb44332009-09-09 15:08:12 +00009060 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009061
9062 return false;
9063 }
9064
9065 bool FindAllFunctionsThatMatchTargetTypeExactly() {
9066 bool Ret = false;
9067
9068 // If the overload expression doesn't have the form of a pointer to
9069 // member, don't try to convert it to a pointer-to-member type.
9070 if (IsInvalidFormOfPointerToMemberFunction())
9071 return false;
9072
9073 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
9074 E = OvlExpr->decls_end();
9075 I != E; ++I) {
9076 // Look through any using declarations to find the underlying function.
9077 NamedDecl *Fn = (*I)->getUnderlyingDecl();
9078
9079 // C++ [over.over]p3:
9080 // Non-member functions and static member functions match
9081 // targets of type "pointer-to-function" or "reference-to-function."
9082 // Nonstatic member functions match targets of
9083 // type "pointer-to-member-function."
9084 // Note that according to DR 247, the containing class does not matter.
9085 if (FunctionTemplateDecl *FunctionTemplate
9086 = dyn_cast<FunctionTemplateDecl>(Fn)) {
9087 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
9088 Ret = true;
9089 }
9090 // If we have explicit template arguments supplied, skip non-templates.
9091 else if (!OvlExpr->hasExplicitTemplateArgs() &&
9092 AddMatchingNonTemplateFunction(Fn, I.getPair()))
9093 Ret = true;
9094 }
9095 assert(Ret || Matches.empty());
9096 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00009097 }
9098
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009099 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009100 // [...] and any given function template specialization F1 is
9101 // eliminated if the set contains a second function template
9102 // specialization whose function template is more specialized
9103 // than the function template of F1 according to the partial
9104 // ordering rules of 14.5.5.2.
9105
9106 // The algorithm specified above is quadratic. We instead use a
9107 // two-pass algorithm (similar to the one used to identify the
9108 // best viable function in an overload set) that identifies the
9109 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00009110
9111 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
9112 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
9113 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009114
John McCallc373d482010-01-27 01:50:18 +00009115 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009116 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
9117 TPOC_Other, 0, SourceExpr->getLocStart(),
9118 S.PDiag(),
9119 S.PDiag(diag::err_addr_ovl_ambiguous)
9120 << Matches[0].second->getDeclName(),
9121 S.PDiag(diag::note_ovl_candidate)
9122 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00009123 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009124
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009125 if (Result != MatchesCopy.end()) {
9126 // Make it the first and only element
9127 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
9128 Matches[0].second = cast<FunctionDecl>(*Result);
9129 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00009130 }
9131 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009132
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009133 void EliminateAllTemplateMatches() {
9134 // [...] any function template specializations in the set are
9135 // eliminated if the set also contains a non-template function, [...]
9136 for (unsigned I = 0, N = Matches.size(); I != N; ) {
9137 if (Matches[I].second->getPrimaryTemplate() == 0)
9138 ++I;
9139 else {
9140 Matches[I] = Matches[--N];
9141 Matches.set_size(N);
9142 }
9143 }
9144 }
9145
9146public:
9147 void ComplainNoMatchesFound() const {
9148 assert(Matches.empty());
9149 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
9150 << OvlExpr->getName() << TargetFunctionType
9151 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009152 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009153 }
9154
9155 bool IsInvalidFormOfPointerToMemberFunction() const {
9156 return TargetTypeIsNonStaticMemberFunction &&
9157 !OvlExprInfo.HasFormOfMemberPointer;
9158 }
9159
9160 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
9161 // TODO: Should we condition this on whether any functions might
9162 // have matched, or is it more appropriate to do that in callers?
9163 // TODO: a fixit wouldn't hurt.
9164 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
9165 << TargetType << OvlExpr->getSourceRange();
9166 }
9167
9168 void ComplainOfInvalidConversion() const {
9169 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
9170 << OvlExpr->getName() << TargetType;
9171 }
9172
9173 void ComplainMultipleMatchesFound() const {
9174 assert(Matches.size() > 1);
9175 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
9176 << OvlExpr->getName()
9177 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00009178 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009179 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009180
9181 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
9182
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009183 int getNumMatches() const { return Matches.size(); }
9184
9185 FunctionDecl* getMatchingFunctionDecl() const {
9186 if (Matches.size() != 1) return 0;
9187 return Matches[0].second;
9188 }
9189
9190 const DeclAccessPair* getMatchingFunctionAccessPair() const {
9191 if (Matches.size() != 1) return 0;
9192 return &Matches[0].first;
9193 }
9194};
9195
9196/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
9197/// an overloaded function (C++ [over.over]), where @p From is an
9198/// expression with overloaded function type and @p ToType is the type
9199/// we're trying to resolve to. For example:
9200///
9201/// @code
9202/// int f(double);
9203/// int f(int);
9204///
9205/// int (*pfd)(double) = f; // selects f(double)
9206/// @endcode
9207///
9208/// This routine returns the resulting FunctionDecl if it could be
9209/// resolved, and NULL otherwise. When @p Complain is true, this
9210/// routine will emit diagnostics if there is an error.
9211FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009212Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
9213 QualType TargetType,
9214 bool Complain,
9215 DeclAccessPair &FoundResult,
9216 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009217 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009218
9219 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
9220 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009221 int NumMatches = Resolver.getNumMatches();
9222 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009223 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009224 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
9225 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
9226 else
9227 Resolver.ComplainNoMatchesFound();
9228 }
9229 else if (NumMatches > 1 && Complain)
9230 Resolver.ComplainMultipleMatchesFound();
9231 else if (NumMatches == 1) {
9232 Fn = Resolver.getMatchingFunctionDecl();
9233 assert(Fn);
9234 FoundResult = *Resolver.getMatchingFunctionAccessPair();
Douglas Gregor9b623632010-10-12 23:32:35 +00009235 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009236 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00009237 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00009238
9239 if (pHadMultipleCandidates)
9240 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009241 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00009242}
9243
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009244/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00009245/// resolve that overloaded function expression down to a single function.
9246///
9247/// This routine can only resolve template-ids that refer to a single function
9248/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009249/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00009250/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00009251FunctionDecl *
9252Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
9253 bool Complain,
9254 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009255 // C++ [over.over]p1:
9256 // [...] [Note: any redundant set of parentheses surrounding the
9257 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00009258 // C++ [over.over]p1:
9259 // [...] The overloaded function name can be preceded by the &
9260 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009261
Douglas Gregor4b52e252009-12-21 23:17:24 +00009262 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00009263 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00009264 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00009265
9266 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00009267 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009268
Douglas Gregor4b52e252009-12-21 23:17:24 +00009269 // Look through all of the overloaded functions, searching for one
9270 // whose type matches exactly.
9271 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00009272 for (UnresolvedSetIterator I = ovl->decls_begin(),
9273 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00009274 // C++0x [temp.arg.explicit]p3:
9275 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009276 // where deduction is not done, if a template argument list is
9277 // specified and it, along with any default template arguments,
9278 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00009279 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00009280 FunctionTemplateDecl *FunctionTemplate
9281 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009282
Douglas Gregor4b52e252009-12-21 23:17:24 +00009283 // C++ [over.over]p2:
9284 // If the name is a function template, template argument deduction is
9285 // done (14.8.2.2), and if the argument deduction succeeds, the
9286 // resulting template argument list is used to generate a single
9287 // function template specialization, which is added to the set of
9288 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00009289 FunctionDecl *Specialization = 0;
Craig Topper93e45992012-09-19 02:26:47 +00009290 TemplateDeductionInfo Info(ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00009291 if (TemplateDeductionResult Result
9292 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
9293 Specialization, Info)) {
9294 // FIXME: make a note of the failed deduction for diagnostics.
9295 (void)Result;
9296 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009297 }
9298
John McCall864c0412011-04-26 20:42:42 +00009299 assert(Specialization && "no specialization and no error?");
9300
Douglas Gregor4b52e252009-12-21 23:17:24 +00009301 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009302 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009303 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00009304 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
9305 << ovl->getName();
9306 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009307 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00009308 return 0;
John McCall864c0412011-04-26 20:42:42 +00009309 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00009310
John McCall864c0412011-04-26 20:42:42 +00009311 Matched = Specialization;
9312 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00009313 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009314
Douglas Gregor4b52e252009-12-21 23:17:24 +00009315 return Matched;
9316}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009317
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009318
9319
9320
John McCall6dbba4f2011-10-11 23:14:30 +00009321// Resolve and fix an overloaded expression that can be resolved
9322// because it identifies a single function template specialization.
9323//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009324// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00009325//
9326// Return true if it was logically possible to so resolve the
9327// expression, regardless of whether or not it succeeded. Always
9328// returns true if 'complain' is set.
9329bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
9330 ExprResult &SrcExpr, bool doFunctionPointerConverion,
9331 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009332 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00009333 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00009334 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009335
John McCall6dbba4f2011-10-11 23:14:30 +00009336 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009337
John McCall864c0412011-04-26 20:42:42 +00009338 DeclAccessPair found;
9339 ExprResult SingleFunctionExpression;
9340 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
9341 ovl.Expression, /*complain*/ false, &found)) {
Daniel Dunbar96a00142012-03-09 18:35:03 +00009342 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getLocStart())) {
John McCall6dbba4f2011-10-11 23:14:30 +00009343 SrcExpr = ExprError();
9344 return true;
9345 }
John McCall864c0412011-04-26 20:42:42 +00009346
9347 // It is only correct to resolve to an instance method if we're
9348 // resolving a form that's permitted to be a pointer to member.
9349 // Otherwise we'll end up making a bound member expression, which
9350 // is illegal in all the contexts we resolve like this.
9351 if (!ovl.HasFormOfMemberPointer &&
9352 isa<CXXMethodDecl>(fn) &&
9353 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00009354 if (!complain) return false;
9355
9356 Diag(ovl.Expression->getExprLoc(),
9357 diag::err_bound_member_function)
9358 << 0 << ovl.Expression->getSourceRange();
9359
9360 // TODO: I believe we only end up here if there's a mix of
9361 // static and non-static candidates (otherwise the expression
9362 // would have 'bound member' type, not 'overload' type).
9363 // Ideally we would note which candidate was chosen and why
9364 // the static candidates were rejected.
9365 SrcExpr = ExprError();
9366 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009367 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00009368
Sylvestre Ledru43e3dee2012-07-31 06:56:50 +00009369 // Fix the expression to refer to 'fn'.
John McCall864c0412011-04-26 20:42:42 +00009370 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00009371 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00009372
9373 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00009374 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00009375 SingleFunctionExpression =
9376 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00009377 if (SingleFunctionExpression.isInvalid()) {
9378 SrcExpr = ExprError();
9379 return true;
9380 }
9381 }
John McCall864c0412011-04-26 20:42:42 +00009382 }
9383
9384 if (!SingleFunctionExpression.isUsable()) {
9385 if (complain) {
9386 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
9387 << ovl.Expression->getName()
9388 << DestTypeForComplaining
9389 << OpRangeForComplaining
9390 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00009391 NoteAllOverloadCandidates(SrcExpr.get());
9392
9393 SrcExpr = ExprError();
9394 return true;
9395 }
9396
9397 return false;
John McCall864c0412011-04-26 20:42:42 +00009398 }
9399
John McCall6dbba4f2011-10-11 23:14:30 +00009400 SrcExpr = SingleFunctionExpression;
9401 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00009402}
9403
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009404/// \brief Add a single candidate to the overload set.
9405static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00009406 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00009407 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009408 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009409 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00009410 bool PartialOverloading,
9411 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00009412 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00009413 if (isa<UsingShadowDecl>(Callee))
9414 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
9415
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009416 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00009417 if (ExplicitTemplateArgs) {
9418 assert(!KnownValid && "Explicit template arguments?");
9419 return;
9420 }
Ahmed Charles13a140c2012-02-25 11:00:22 +00009421 S.AddOverloadCandidate(Func, FoundDecl, Args, CandidateSet, false,
9422 PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009423 return;
John McCallba135432009-11-21 08:51:07 +00009424 }
9425
9426 if (FunctionTemplateDecl *FuncTemplate
9427 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00009428 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009429 ExplicitTemplateArgs, Args, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00009430 return;
9431 }
9432
Richard Smith2ced0442011-06-26 22:19:54 +00009433 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009434}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009435
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009436/// \brief Add the overload candidates named by callee and/or found by argument
9437/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00009438void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009439 llvm::ArrayRef<Expr *> Args,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009440 OverloadCandidateSet &CandidateSet,
9441 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00009442
9443#ifndef NDEBUG
9444 // Verify that ArgumentDependentLookup is consistent with the rules
9445 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009446 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009447 // Let X be the lookup set produced by unqualified lookup (3.4.1)
9448 // and let Y be the lookup set produced by argument dependent
9449 // lookup (defined as follows). If X contains
9450 //
9451 // -- a declaration of a class member, or
9452 //
9453 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00009454 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009455 //
9456 // -- a declaration that is neither a function or a function
9457 // template
9458 //
9459 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00009460
John McCall3b4294e2009-12-16 12:17:52 +00009461 if (ULE->requiresADL()) {
9462 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9463 E = ULE->decls_end(); I != E; ++I) {
9464 assert(!(*I)->getDeclContext()->isRecord());
9465 assert(isa<UsingShadowDecl>(*I) ||
9466 !(*I)->getDeclContext()->isFunctionOrMethod());
9467 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00009468 }
9469 }
9470#endif
9471
John McCall3b4294e2009-12-16 12:17:52 +00009472 // It would be nice to avoid this copy.
9473 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00009474 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009475 if (ULE->hasExplicitTemplateArgs()) {
9476 ULE->copyTemplateArgumentsInto(TABuffer);
9477 ExplicitTemplateArgs = &TABuffer;
9478 }
9479
9480 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
9481 E = ULE->decls_end(); I != E; ++I)
Ahmed Charles13a140c2012-02-25 11:00:22 +00009482 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs, Args,
9483 CandidateSet, PartialOverloading,
9484 /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00009485
John McCall3b4294e2009-12-16 12:17:52 +00009486 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00009487 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
Richard Smithf5cd5cc2012-02-25 06:24:24 +00009488 ULE->getExprLoc(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009489 Args, ExplicitTemplateArgs,
Richard Smithb1502bc2012-10-18 17:56:02 +00009490 CandidateSet, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00009491}
John McCall578b69b2009-12-16 08:11:27 +00009492
Richard Smithf50e88a2011-06-05 22:42:48 +00009493/// Attempt to recover from an ill-formed use of a non-dependent name in a
9494/// template, where the non-dependent name was declared after the template
9495/// was defined. This is common in code written for a compilers which do not
9496/// correctly implement two-stage name lookup.
9497///
9498/// Returns true if a viable candidate was found and a diagnostic was issued.
9499static bool
9500DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
9501 const CXXScopeSpec &SS, LookupResult &R,
9502 TemplateArgumentListInfo *ExplicitTemplateArgs,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009503 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009504 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
9505 return false;
9506
9507 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
Nick Lewycky5a7120c2012-03-14 20:41:00 +00009508 if (DC->isTransparentContext())
9509 continue;
9510
Richard Smithf50e88a2011-06-05 22:42:48 +00009511 SemaRef.LookupQualifiedName(R, DC);
9512
9513 if (!R.empty()) {
9514 R.suppressDiagnostics();
9515
9516 if (isa<CXXRecordDecl>(DC)) {
9517 // Don't diagnose names we find in classes; we get much better
9518 // diagnostics for these from DiagnoseEmptyLookup.
9519 R.clear();
9520 return false;
9521 }
9522
9523 OverloadCandidateSet Candidates(FnLoc);
9524 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9525 AddOverloadedCallCandidate(SemaRef, I.getPair(),
Ahmed Charles13a140c2012-02-25 11:00:22 +00009526 ExplicitTemplateArgs, Args,
Richard Smith2ced0442011-06-26 22:19:54 +00009527 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00009528
9529 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00009530 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009531 // No viable functions. Don't bother the user with notes for functions
9532 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00009533 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00009534 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00009535 }
Richard Smithf50e88a2011-06-05 22:42:48 +00009536
9537 // Find the namespaces where ADL would have looked, and suggest
9538 // declaring the function there instead.
9539 Sema::AssociatedNamespaceSet AssociatedNamespaces;
9540 Sema::AssociatedClassSet AssociatedClasses;
John McCall42f48fb2012-08-24 20:38:34 +00009541 SemaRef.FindAssociatedClassesAndNamespaces(FnLoc, Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009542 AssociatedNamespaces,
9543 AssociatedClasses);
Chandler Carruth74d487e2011-06-05 23:36:55 +00009544 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Nick Lewyckyd05df512012-11-13 00:08:34 +00009545 DeclContext *Std = SemaRef.getStdNamespace();
9546 for (Sema::AssociatedNamespaceSet::iterator
9547 it = AssociatedNamespaces.begin(),
9548 end = AssociatedNamespaces.end(); it != end; ++it) {
Richard Smith19e0d952012-12-22 02:46:14 +00009549 // Never suggest declaring a function within namespace 'std'.
9550 if (Std && Std->Encloses(*it))
9551 continue;
9552
9553 // Never suggest declaring a function within a namespace with a reserved
9554 // name, like __gnu_cxx.
9555 NamespaceDecl *NS = dyn_cast<NamespaceDecl>(*it);
9556 if (NS &&
9557 NS->getQualifiedNameAsString().find("__") != std::string::npos)
9558 continue;
9559
9560 SuggestedNamespaces.insert(*it);
Richard Smithf50e88a2011-06-05 22:42:48 +00009561 }
9562
9563 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
9564 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00009565 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009566 SemaRef.Diag(Best->Function->getLocation(),
9567 diag::note_not_found_by_two_phase_lookup)
9568 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00009569 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009570 SemaRef.Diag(Best->Function->getLocation(),
9571 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00009572 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00009573 } else {
9574 // FIXME: It would be useful to list the associated namespaces here,
9575 // but the diagnostics infrastructure doesn't provide a way to produce
9576 // a localized representation of a list of items.
9577 SemaRef.Diag(Best->Function->getLocation(),
9578 diag::note_not_found_by_two_phase_lookup)
9579 << R.getLookupName() << 2;
9580 }
9581
9582 // Try to recover by calling this function.
9583 return true;
9584 }
9585
9586 R.clear();
9587 }
9588
9589 return false;
9590}
9591
9592/// Attempt to recover from ill-formed use of a non-dependent operator in a
9593/// template, where the non-dependent operator was declared after the template
9594/// was defined.
9595///
9596/// Returns true if a viable candidate was found and a diagnostic was issued.
9597static bool
9598DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
9599 SourceLocation OpLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009600 llvm::ArrayRef<Expr *> Args) {
Richard Smithf50e88a2011-06-05 22:42:48 +00009601 DeclarationName OpName =
9602 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
9603 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
9604 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009605 /*ExplicitTemplateArgs=*/0, Args);
Richard Smithf50e88a2011-06-05 22:42:48 +00009606}
9607
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009608namespace {
9609// Callback to limit the allowed keywords and to only accept typo corrections
9610// that are keywords or whose decls refer to functions (or template functions)
9611// that accept the given number of arguments.
9612class RecoveryCallCCC : public CorrectionCandidateCallback {
9613 public:
9614 RecoveryCallCCC(Sema &SemaRef, unsigned NumArgs, bool HasExplicitTemplateArgs)
9615 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs) {
David Blaikie4e4d0842012-03-11 07:00:24 +00009616 WantTypeSpecifiers = SemaRef.getLangOpts().CPlusPlus;
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009617 WantRemainingKeywords = false;
9618 }
9619
9620 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9621 if (!candidate.getCorrectionDecl())
9622 return candidate.isKeyword();
9623
9624 for (TypoCorrection::const_decl_iterator DI = candidate.begin(),
9625 DIEnd = candidate.end(); DI != DIEnd; ++DI) {
9626 FunctionDecl *FD = 0;
9627 NamedDecl *ND = (*DI)->getUnderlyingDecl();
9628 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
9629 FD = FTD->getTemplatedDecl();
9630 if (!HasExplicitTemplateArgs && !FD) {
9631 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
9632 // If the Decl is neither a function nor a template function,
9633 // determine if it is a pointer or reference to a function. If so,
9634 // check against the number of arguments expected for the pointee.
9635 QualType ValType = cast<ValueDecl>(ND)->getType();
9636 if (ValType->isAnyPointerType() || ValType->isReferenceType())
9637 ValType = ValType->getPointeeType();
9638 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
9639 if (FPT->getNumArgs() == NumArgs)
9640 return true;
9641 }
9642 }
9643 if (FD && FD->getNumParams() >= NumArgs &&
9644 FD->getMinRequiredArguments() <= NumArgs)
9645 return true;
9646 }
9647 return false;
9648 }
9649
9650 private:
9651 unsigned NumArgs;
9652 bool HasExplicitTemplateArgs;
9653};
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009654
9655// Callback that effectively disabled typo correction
9656class NoTypoCorrectionCCC : public CorrectionCandidateCallback {
9657 public:
9658 NoTypoCorrectionCCC() {
9659 WantTypeSpecifiers = false;
9660 WantExpressionKeywords = false;
9661 WantCXXNamedCasts = false;
9662 WantRemainingKeywords = false;
9663 }
9664
9665 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
9666 return false;
9667 }
9668};
Richard Smithe49ff3e2012-09-25 04:46:05 +00009669
9670class BuildRecoveryCallExprRAII {
9671 Sema &SemaRef;
9672public:
9673 BuildRecoveryCallExprRAII(Sema &S) : SemaRef(S) {
9674 assert(SemaRef.IsBuildingRecoveryCallExpr == false);
9675 SemaRef.IsBuildingRecoveryCallExpr = true;
9676 }
9677
9678 ~BuildRecoveryCallExprRAII() {
9679 SemaRef.IsBuildingRecoveryCallExpr = false;
9680 }
9681};
9682
Kaelyn Uhrain60a09dc2012-01-25 18:37:44 +00009683}
9684
John McCall578b69b2009-12-16 08:11:27 +00009685/// Attempts to recover from a call where no functions were found.
9686///
9687/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00009688static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00009689BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00009690 UnresolvedLookupExpr *ULE,
9691 SourceLocation LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009692 llvm::MutableArrayRef<Expr *> Args,
Richard Smithf50e88a2011-06-05 22:42:48 +00009693 SourceLocation RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009694 bool EmptyLookup, bool AllowTypoCorrection) {
Richard Smithe49ff3e2012-09-25 04:46:05 +00009695 // Do not try to recover if it is already building a recovery call.
9696 // This stops infinite loops for template instantiations like
9697 //
9698 // template <typename T> auto foo(T t) -> decltype(foo(t)) {}
9699 // template <typename T> auto foo(T t) -> decltype(foo(&t)) {}
9700 //
9701 if (SemaRef.IsBuildingRecoveryCallExpr)
9702 return ExprError();
9703 BuildRecoveryCallExprRAII RCE(SemaRef);
John McCall578b69b2009-12-16 08:11:27 +00009704
9705 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00009706 SS.Adopt(ULE->getQualifierLoc());
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009707 SourceLocation TemplateKWLoc = ULE->getTemplateKeywordLoc();
John McCall578b69b2009-12-16 08:11:27 +00009708
John McCall3b4294e2009-12-16 12:17:52 +00009709 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00009710 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00009711 if (ULE->hasExplicitTemplateArgs()) {
9712 ULE->copyTemplateArgumentsInto(TABuffer);
9713 ExplicitTemplateArgs = &TABuffer;
9714 }
9715
John McCall578b69b2009-12-16 08:11:27 +00009716 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
9717 Sema::LookupOrdinaryName);
Ahmed Charles13a140c2012-02-25 11:00:22 +00009718 RecoveryCallCCC Validator(SemaRef, Args.size(), ExplicitTemplateArgs != 0);
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009719 NoTypoCorrectionCCC RejectAll;
9720 CorrectionCandidateCallback *CCC = AllowTypoCorrection ?
9721 (CorrectionCandidateCallback*)&Validator :
9722 (CorrectionCandidateCallback*)&RejectAll;
Richard Smithf50e88a2011-06-05 22:42:48 +00009723 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009724 ExplicitTemplateArgs, Args) &&
Richard Smithf50e88a2011-06-05 22:42:48 +00009725 (!EmptyLookup ||
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009726 SemaRef.DiagnoseEmptyLookup(S, SS, R, *CCC,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009727 ExplicitTemplateArgs, Args)))
John McCallf312b1e2010-08-26 23:41:50 +00009728 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00009729
John McCall3b4294e2009-12-16 12:17:52 +00009730 assert(!R.empty() && "lookup results empty despite recovery");
9731
9732 // Build an implicit member call if appropriate. Just drop the
9733 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00009734 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009735 if ((*R.begin())->isCXXClassMember())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009736 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
9737 R, ExplicitTemplateArgs);
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009738 else if (ExplicitTemplateArgs || TemplateKWLoc.isValid())
Abramo Bagnarae4b92762012-01-27 09:46:47 +00009739 NewFn = SemaRef.BuildTemplateIdExpr(SS, TemplateKWLoc, R, false,
Abramo Bagnara9d9922a2012-02-06 14:31:00 +00009740 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00009741 else
9742 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
9743
9744 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00009745 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00009746
9747 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00009748 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00009749 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00009750 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009751 MultiExprArg(Args.data(), Args.size()),
9752 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00009753}
Douglas Gregord7a95972010-06-08 17:35:15 +00009754
Sam Panzere1715b62012-08-21 00:52:01 +00009755/// \brief Constructs and populates an OverloadedCandidateSet from
9756/// the given function.
9757/// \returns true when an the ExprResult output parameter has been set.
9758bool Sema::buildOverloadedCallSet(Scope *S, Expr *Fn,
9759 UnresolvedLookupExpr *ULE,
9760 Expr **Args, unsigned NumArgs,
9761 SourceLocation RParenLoc,
9762 OverloadCandidateSet *CandidateSet,
9763 ExprResult *Result) {
John McCall3b4294e2009-12-16 12:17:52 +00009764#ifndef NDEBUG
9765 if (ULE->requiresADL()) {
9766 // To do ADL, we must have found an unqualified name.
9767 assert(!ULE->getQualifier() && "qualified name with ADL");
9768
9769 // We don't perform ADL for implicit declarations of builtins.
9770 // Verify that this was correctly set up.
9771 FunctionDecl *F;
9772 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
9773 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
9774 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00009775 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009776
John McCall3b4294e2009-12-16 12:17:52 +00009777 // We don't perform ADL in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00009778 assert(getLangOpts().CPlusPlus && "ADL enabled in C");
Richard Smithb1502bc2012-10-18 17:56:02 +00009779 }
John McCall3b4294e2009-12-16 12:17:52 +00009780#endif
9781
John McCall5acb0c92011-10-17 18:40:02 +00009782 UnbridgedCastsSet UnbridgedCasts;
Sam Panzere1715b62012-08-21 00:52:01 +00009783 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts)) {
9784 *Result = ExprError();
9785 return true;
9786 }
Douglas Gregor17330012009-02-04 15:01:18 +00009787
John McCall3b4294e2009-12-16 12:17:52 +00009788 // Add the functions denoted by the callee to the set of candidate
9789 // functions, including those from argument-dependent lookup.
Ahmed Charles13a140c2012-02-25 11:00:22 +00009790 AddOverloadedCallCandidates(ULE, llvm::makeArrayRef(Args, NumArgs),
Sam Panzere1715b62012-08-21 00:52:01 +00009791 *CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00009792
9793 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00009794 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
9795 // out if it fails.
Sam Panzere1715b62012-08-21 00:52:01 +00009796 if (CandidateSet->empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00009797 // In Microsoft mode, if we are inside a template class member function then
9798 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009799 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00009800 // classes.
David Blaikie4e4d0842012-03-11 07:00:24 +00009801 if (getLangOpts().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00009802 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009803 CallExpr *CE = new (Context) CallExpr(Context, Fn,
9804 llvm::makeArrayRef(Args, NumArgs),
9805 Context.DependentTy, VK_RValue,
9806 RParenLoc);
Sebastian Redl14b0c192011-09-24 17:48:00 +00009807 CE->setTypeDependent(true);
Sam Panzere1715b62012-08-21 00:52:01 +00009808 *Result = Owned(CE);
9809 return true;
Sebastian Redl14b0c192011-09-24 17:48:00 +00009810 }
Sam Panzere1715b62012-08-21 00:52:01 +00009811 return false;
Francois Pichet0f74d1e2011-09-07 00:14:57 +00009812 }
John McCall578b69b2009-12-16 08:11:27 +00009813
John McCall5acb0c92011-10-17 18:40:02 +00009814 UnbridgedCasts.restore();
Sam Panzere1715b62012-08-21 00:52:01 +00009815 return false;
9816}
John McCall5acb0c92011-10-17 18:40:02 +00009817
Sam Panzere1715b62012-08-21 00:52:01 +00009818/// FinishOverloadedCallExpr - given an OverloadCandidateSet, builds and returns
9819/// the completed call expression. If overload resolution fails, emits
9820/// diagnostics and returns ExprError()
9821static ExprResult FinishOverloadedCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
9822 UnresolvedLookupExpr *ULE,
9823 SourceLocation LParenLoc,
9824 Expr **Args, unsigned NumArgs,
9825 SourceLocation RParenLoc,
9826 Expr *ExecConfig,
9827 OverloadCandidateSet *CandidateSet,
9828 OverloadCandidateSet::iterator *Best,
9829 OverloadingResult OverloadResult,
9830 bool AllowTypoCorrection) {
9831 if (CandidateSet->empty())
9832 return BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
9833 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9834 RParenLoc, /*EmptyLookup=*/true,
9835 AllowTypoCorrection);
9836
9837 switch (OverloadResult) {
John McCall3b4294e2009-12-16 12:17:52 +00009838 case OR_Success: {
Sam Panzere1715b62012-08-21 00:52:01 +00009839 FunctionDecl *FDecl = (*Best)->Function;
9840 SemaRef.MarkFunctionReferenced(Fn->getExprLoc(), FDecl);
9841 SemaRef.CheckUnresolvedLookupAccess(ULE, (*Best)->FoundDecl);
9842 SemaRef.DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
9843 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9844 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9845 RParenLoc, ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00009846 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009847
Richard Smithf50e88a2011-06-05 22:42:48 +00009848 case OR_No_Viable_Function: {
9849 // Try to recover by looking for viable functions which the user might
9850 // have meant to call.
Sam Panzere1715b62012-08-21 00:52:01 +00009851 ExprResult Recovery = BuildRecoveryCallExpr(SemaRef, S, Fn, ULE, LParenLoc,
Ahmed Charles13a140c2012-02-25 11:00:22 +00009852 llvm::MutableArrayRef<Expr *>(Args, NumArgs),
9853 RParenLoc,
Kaelyn Uhrain3943b1c2012-01-25 21:11:35 +00009854 /*EmptyLookup=*/false,
9855 AllowTypoCorrection);
Richard Smithf50e88a2011-06-05 22:42:48 +00009856 if (!Recovery.isInvalid())
9857 return Recovery;
9858
Sam Panzere1715b62012-08-21 00:52:01 +00009859 SemaRef.Diag(Fn->getLocStart(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00009860 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00009861 << ULE->getName() << Fn->getSourceRange();
Sam Panzere1715b62012-08-21 00:52:01 +00009862 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9863 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009864 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00009865 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009866
9867 case OR_Ambiguous:
Sam Panzere1715b62012-08-21 00:52:01 +00009868 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_ambiguous_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_ViableCandidates,
9871 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf6b89692008-11-26 05:54:23 +00009872 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009873
Sam Panzere1715b62012-08-21 00:52:01 +00009874 case OR_Deleted: {
9875 SemaRef.Diag(Fn->getLocStart(), diag::err_ovl_deleted_call)
9876 << (*Best)->Function->isDeleted()
9877 << ULE->getName()
9878 << SemaRef.getDeletedOrUnavailableSuffix((*Best)->Function)
9879 << Fn->getSourceRange();
9880 CandidateSet->NoteCandidates(SemaRef, OCD_AllCandidates,
9881 llvm::makeArrayRef(Args, NumArgs));
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00009882
Sam Panzere1715b62012-08-21 00:52:01 +00009883 // We emitted an error for the unvailable/deleted function call but keep
9884 // the call in the AST.
9885 FunctionDecl *FDecl = (*Best)->Function;
9886 Fn = SemaRef.FixOverloadedFunctionReference(Fn, (*Best)->FoundDecl, FDecl);
9887 return SemaRef.BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
9888 RParenLoc, ExecConfig);
9889 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00009890 }
9891
Douglas Gregorff331c12010-07-25 18:17:45 +00009892 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00009893 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00009894}
9895
Sam Panzere1715b62012-08-21 00:52:01 +00009896/// BuildOverloadedCallExpr - Given the call expression that calls Fn
9897/// (which eventually refers to the declaration Func) and the call
9898/// arguments Args/NumArgs, attempt to resolve the function call down
9899/// to a specific function. If overload resolution succeeds, returns
9900/// the call expression produced by overload resolution.
9901/// Otherwise, emits diagnostics and returns ExprError.
9902ExprResult Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn,
9903 UnresolvedLookupExpr *ULE,
9904 SourceLocation LParenLoc,
9905 Expr **Args, unsigned NumArgs,
9906 SourceLocation RParenLoc,
9907 Expr *ExecConfig,
9908 bool AllowTypoCorrection) {
9909 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
9910 ExprResult result;
9911
9912 if (buildOverloadedCallSet(S, Fn, ULE, Args, NumArgs, LParenLoc,
9913 &CandidateSet, &result))
9914 return result;
9915
9916 OverloadCandidateSet::iterator Best;
9917 OverloadingResult OverloadResult =
9918 CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best);
9919
9920 return FinishOverloadedCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
9921 RParenLoc, ExecConfig, &CandidateSet,
9922 &Best, OverloadResult,
9923 AllowTypoCorrection);
9924}
9925
John McCall6e266892010-01-26 03:27:55 +00009926static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00009927 return Functions.size() > 1 ||
9928 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
9929}
9930
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009931/// \brief Create a unary operation that may resolve to an overloaded
9932/// operator.
9933///
9934/// \param OpLoc The location of the operator itself (e.g., '*').
9935///
9936/// \param OpcIn The UnaryOperator::Opcode that describes this
9937/// operator.
9938///
James Dennett40ae6662012-06-22 08:52:37 +00009939/// \param Fns The set of non-member functions that will be
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009940/// considered by overload resolution. The caller needs to build this
9941/// set based on the context using, e.g.,
9942/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9943/// set should not contain any member functions; those will be added
9944/// by CreateOverloadedUnaryOp().
9945///
James Dennett8da16872012-06-22 10:32:46 +00009946/// \param Input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009947ExprResult
John McCall6e266892010-01-26 03:27:55 +00009948Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
9949 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00009950 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009951 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009952
9953 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
9954 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
9955 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00009956 // TODO: provide better source location info.
9957 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009958
John McCall5acb0c92011-10-17 18:40:02 +00009959 if (checkPlaceholderForOverload(*this, Input))
9960 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009961
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009962 Expr *Args[2] = { Input, 0 };
9963 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009964
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009965 // For post-increment and post-decrement, add the implicit '0' as
9966 // the second argument, so that we know this is a post-increment or
9967 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009968 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009969 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009970 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9971 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009972 NumArgs = 2;
9973 }
9974
9975 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009976 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009977 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009978 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009979 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009980 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009981 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009982
John McCallc373d482010-01-27 01:50:18 +00009983 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009984 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009985 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009986 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009987 /*ADL*/ true, IsOverloaded(Fns),
9988 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009989 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00009990 llvm::makeArrayRef(Args, NumArgs),
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009991 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009992 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +00009993 OpLoc, false));
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009994 }
9995
9996 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009997 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009998
9999 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010000 AddFunctionCandidates(Fns, llvm::makeArrayRef(Args, NumArgs), CandidateSet,
10001 false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010002
10003 // Add operator candidates that are member functions.
10004 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
10005
John McCall6e266892010-01-26 03:27:55 +000010006 // Add candidates from ADL.
10007 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010008 OpLoc, llvm::makeArrayRef(Args, NumArgs),
John McCall6e266892010-01-26 03:27:55 +000010009 /*ExplicitTemplateArgs*/ 0,
10010 CandidateSet);
10011
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010012 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010013 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010014
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010015 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10016
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010017 // Perform overload resolution.
10018 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010019 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010020 case OR_Success: {
10021 // We found a built-in operator or an overloaded operator.
10022 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +000010023
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010024 if (FnDecl) {
10025 // We matched an overloaded operator. Build a call to that
10026 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +000010027
Eli Friedman5f2987c2012-02-02 03:46:19 +000010028 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010029
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010030 // Convert the arguments.
10031 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +000010032 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010033
John Wiegley429bb272011-04-08 18:41:53 +000010034 ExprResult InputRes =
10035 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
10036 Best->FoundDecl, Method);
10037 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010038 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010039 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010040 } else {
10041 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010042 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +000010043 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010044 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +000010045 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010046 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +000010047 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +000010048 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010049 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +000010050 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010051 }
10052
John McCallb697e082010-05-06 18:15:07 +000010053 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10054
John McCallf89e55a2010-11-18 06:31:45 +000010055 // Determine the result type.
10056 QualType ResultTy = FnDecl->getResultType();
10057 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10058 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +000010059
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010060 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010061 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010062 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010063 if (FnExpr.isInvalid())
10064 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +000010065
Eli Friedman4c3b8962009-11-18 03:58:17 +000010066 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +000010067 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010068 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010069 llvm::makeArrayRef(Args, NumArgs),
Lang Hamesbe9af122012-10-02 04:45:10 +000010070 ResultTy, VK, OpLoc, false);
John McCallb697e082010-05-06 18:15:07 +000010071
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010072 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +000010073 FnDecl))
10074 return ExprError();
10075
John McCall9ae2f072010-08-23 23:25:46 +000010076 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010077 } else {
10078 // We matched a built-in operator. Convert the arguments, then
10079 // break out so that we will build the appropriate built-in
10080 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010081 ExprResult InputRes =
10082 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
10083 Best->Conversions[0], AA_Passing);
10084 if (InputRes.isInvalid())
10085 return ExprError();
10086 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010087 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010088 }
John Wiegley429bb272011-04-08 18:41:53 +000010089 }
10090
10091 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +000010092 // This is an erroneous use of an operator which can be overloaded by
10093 // a non-member function. Check for non-member operators which were
10094 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010095 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc,
10096 llvm::makeArrayRef(Args, NumArgs)))
Richard Smithf50e88a2011-06-05 22:42:48 +000010097 // FIXME: Recover by calling the found function.
10098 return ExprError();
10099
John Wiegley429bb272011-04-08 18:41:53 +000010100 // No viable function; fall through to handling this as a
10101 // built-in operator, which will produce an error message for us.
10102 break;
10103
10104 case OR_Ambiguous:
10105 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10106 << UnaryOperator::getOpcodeStr(Opc)
10107 << Input->getType()
10108 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010109 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10110 llvm::makeArrayRef(Args, NumArgs),
John Wiegley429bb272011-04-08 18:41:53 +000010111 UnaryOperator::getOpcodeStr(Opc), OpLoc);
10112 return ExprError();
10113
10114 case OR_Deleted:
10115 Diag(OpLoc, diag::err_ovl_deleted_oper)
10116 << Best->Function->isDeleted()
10117 << UnaryOperator::getOpcodeStr(Opc)
10118 << getDeletedOrUnavailableSuffix(Best->Function)
10119 << Input->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010120 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10121 llvm::makeArrayRef(Args, NumArgs),
Eli Friedman1795d372011-08-26 19:46:22 +000010122 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010123 return ExprError();
10124 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010125
10126 // Either we found no viable overloaded operator or we matched a
10127 // built-in operator. In either case, fall through to trying to
10128 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +000010129 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010130}
10131
Douglas Gregor063daf62009-03-13 18:40:31 +000010132/// \brief Create a binary operation that may resolve to an overloaded
10133/// operator.
10134///
10135/// \param OpLoc The location of the operator itself (e.g., '+').
10136///
10137/// \param OpcIn The BinaryOperator::Opcode that describes this
10138/// operator.
10139///
James Dennett40ae6662012-06-22 08:52:37 +000010140/// \param Fns The set of non-member functions that will be
Douglas Gregor063daf62009-03-13 18:40:31 +000010141/// considered by overload resolution. The caller needs to build this
10142/// set based on the context using, e.g.,
10143/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
10144/// set should not contain any member functions; those will be added
10145/// by CreateOverloadedBinOp().
10146///
10147/// \param LHS Left-hand argument.
10148/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +000010149ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +000010150Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +000010151 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +000010152 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +000010153 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +000010154 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010155 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +000010156
10157 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
10158 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
10159 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
10160
10161 // If either side is type-dependent, create an appropriate dependent
10162 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010163 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +000010164 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010165 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010166 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +000010167 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010168 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +000010169 Context.DependentTy,
10170 VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +000010171 OpLoc,
10172 FPFeatures.fp_contract));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010173
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010174 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
10175 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010176 VK_LValue,
10177 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010178 Context.DependentTy,
10179 Context.DependentTy,
Lang Hamesbe9af122012-10-02 04:45:10 +000010180 OpLoc,
10181 FPFeatures.fp_contract));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +000010182 }
John McCall6e266892010-01-26 03:27:55 +000010183
10184 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +000010185 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010186 // TODO: provide better source location info in DNLoc component.
10187 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +000010188 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +000010189 = UnresolvedLookupExpr::Create(Context, NamingClass,
10190 NestedNameSpecifierLoc(), OpNameInfo,
10191 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010192 Fns.begin(), Fns.end());
Lang Hamesbe9af122012-10-02 04:45:10 +000010193 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn, Args,
10194 Context.DependentTy, VK_RValue,
10195 OpLoc, FPFeatures.fp_contract));
Douglas Gregor063daf62009-03-13 18:40:31 +000010196 }
10197
John McCall5acb0c92011-10-17 18:40:02 +000010198 // Always do placeholder-like conversions on the RHS.
10199 if (checkPlaceholderForOverload(*this, Args[1]))
10200 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010201
John McCall3c3b7f92011-10-25 17:37:35 +000010202 // Do placeholder-like conversion on the LHS; note that we should
10203 // not get here with a PseudoObject LHS.
10204 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +000010205 if (checkPlaceholderForOverload(*this, Args[0]))
10206 return ExprError();
10207
Sebastian Redl275c2b42009-11-18 23:10:33 +000010208 // If this is the assignment operator, we only perform overload resolution
10209 // if the left-hand side is a class or enumeration type. This is actually
10210 // a hack. The standard requires that we do overload resolution between the
10211 // various built-in candidates, but as DR507 points out, this can lead to
10212 // problems. So we do it this way, which pretty much follows what GCC does.
10213 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +000010214 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010215 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010216
John McCall0e800c92010-12-04 08:14:53 +000010217 // If this is the .* operator, which is not overloadable, just
10218 // create a built-in binary operator.
10219 if (Opc == BO_PtrMemD)
10220 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
10221
Douglas Gregorbc736fc2009-03-13 23:49:33 +000010222 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010223 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010224
10225 // Add the candidates from the given function set.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010226 AddFunctionCandidates(Fns, Args, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +000010227
10228 // Add operator candidates that are member functions.
10229 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
10230
John McCall6e266892010-01-26 03:27:55 +000010231 // Add candidates from ADL.
10232 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010233 OpLoc, Args,
John McCall6e266892010-01-26 03:27:55 +000010234 /*ExplicitTemplateArgs*/ 0,
10235 CandidateSet);
10236
Douglas Gregor063daf62009-03-13 18:40:31 +000010237 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +000010238 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +000010239
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010240 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10241
Douglas Gregor063daf62009-03-13 18:40:31 +000010242 // Perform overload resolution.
10243 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010244 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +000010245 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +000010246 // We found a built-in operator or an overloaded operator.
10247 FunctionDecl *FnDecl = Best->Function;
10248
10249 if (FnDecl) {
10250 // We matched an overloaded operator. Build a call to that
10251 // operator.
10252
Eli Friedman5f2987c2012-02-02 03:46:19 +000010253 MarkFunctionReferenced(OpLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010254
Douglas Gregor063daf62009-03-13 18:40:31 +000010255 // Convert the arguments.
10256 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +000010257 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +000010258 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +000010259
Chandler Carruth6df868e2010-12-12 08:17:55 +000010260 ExprResult Arg1 =
10261 PerformCopyInitialization(
10262 InitializedEntity::InitializeParameter(Context,
10263 FnDecl->getParamDecl(0)),
10264 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010265 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010266 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010267
John Wiegley429bb272011-04-08 18:41:53 +000010268 ExprResult Arg0 =
10269 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10270 Best->FoundDecl, Method);
10271 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010272 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010273 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010274 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010275 } else {
10276 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +000010277 ExprResult Arg0 = PerformCopyInitialization(
10278 InitializedEntity::InitializeParameter(Context,
10279 FnDecl->getParamDecl(0)),
10280 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010281 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010282 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010283
Chandler Carruth6df868e2010-12-12 08:17:55 +000010284 ExprResult Arg1 =
10285 PerformCopyInitialization(
10286 InitializedEntity::InitializeParameter(Context,
10287 FnDecl->getParamDecl(1)),
10288 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +000010289 if (Arg1.isInvalid())
10290 return ExprError();
10291 Args[0] = LHS = Arg0.takeAs<Expr>();
10292 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +000010293 }
10294
John McCallb697e082010-05-06 18:15:07 +000010295 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
10296
John McCallf89e55a2010-11-18 06:31:45 +000010297 // Determine the result type.
10298 QualType ResultTy = FnDecl->getResultType();
10299 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10300 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +000010301
10302 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010303 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10304 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000010305 if (FnExpr.isInvalid())
10306 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +000010307
John McCall9ae2f072010-08-23 23:25:46 +000010308 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010309 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000010310 Args, ResultTy, VK, OpLoc,
10311 FPFeatures.fp_contract);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010312
10313 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010314 FnDecl))
10315 return ExprError();
10316
John McCall9ae2f072010-08-23 23:25:46 +000010317 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +000010318 } else {
10319 // We matched a built-in operator. Convert the arguments, then
10320 // break out so that we will build the appropriate built-in
10321 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010322 ExprResult ArgsRes0 =
10323 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10324 Best->Conversions[0], AA_Passing);
10325 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +000010326 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010327 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010328
John Wiegley429bb272011-04-08 18:41:53 +000010329 ExprResult ArgsRes1 =
10330 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10331 Best->Conversions[1], AA_Passing);
10332 if (ArgsRes1.isInvalid())
10333 return ExprError();
10334 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +000010335 break;
10336 }
10337 }
10338
Douglas Gregor33074752009-09-30 21:46:01 +000010339 case OR_No_Viable_Function: {
10340 // C++ [over.match.oper]p9:
10341 // If the operator is the operator , [...] and there are no
10342 // viable functions, then the operator is assumed to be the
10343 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +000010344 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +000010345 break;
10346
Chandler Carruth6df868e2010-12-12 08:17:55 +000010347 // For class as left operand for assignment or compound assigment
10348 // operator do not fall through to handling in built-in, but report that
10349 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +000010350 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010351 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +000010352 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +000010353 Diag(OpLoc, diag::err_ovl_no_viable_oper)
10354 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010355 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +000010356 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +000010357 // This is an erroneous use of an operator which can be overloaded by
10358 // a non-member function. Check for non-member operators which were
10359 // defined too late to be candidates.
Ahmed Charles13a140c2012-02-25 11:00:22 +000010360 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args))
Richard Smithf50e88a2011-06-05 22:42:48 +000010361 // FIXME: Recover by calling the found function.
10362 return ExprError();
10363
Douglas Gregor33074752009-09-30 21:46:01 +000010364 // No viable function; try to create a built-in operation, which will
10365 // produce an error. Then, show the non-viable candidates.
10366 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +000010367 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010368 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +000010369 "C++ binary operator overloading is missing candidates!");
10370 if (Result.isInvalid())
Ahmed Charles13a140c2012-02-25 11:00:22 +000010371 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010372 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000010373 return Result;
Douglas Gregor33074752009-09-30 21:46:01 +000010374 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010375
10376 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010377 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +000010378 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +000010379 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010380 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010381 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010382 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010383 return ExprError();
10384
10385 case OR_Deleted:
Douglas Gregore4e68d42012-02-15 19:33:52 +000010386 if (isImplicitlyDeleted(Best->Function)) {
10387 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
10388 Diag(OpLoc, diag::err_ovl_deleted_special_oper)
10389 << getSpecialMember(Method)
10390 << BinaryOperator::getOpcodeStr(Opc)
10391 << getDeletedOrUnavailableSuffix(Best->Function);
Richard Smith5bdaac52012-04-02 20:59:25 +000010392
10393 if (getSpecialMember(Method) != CXXInvalid) {
10394 // The user probably meant to call this special member. Just
10395 // explain why it's deleted.
10396 NoteDeletedFunction(Method);
Douglas Gregore4e68d42012-02-15 19:33:52 +000010397 return ExprError();
10398 }
10399 } else {
10400 Diag(OpLoc, diag::err_ovl_deleted_oper)
10401 << Best->Function->isDeleted()
10402 << BinaryOperator::getOpcodeStr(Opc)
10403 << getDeletedOrUnavailableSuffix(Best->Function)
10404 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10405 }
Ahmed Charles13a140c2012-02-25 11:00:22 +000010406 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
Eli Friedman1795d372011-08-26 19:46:22 +000010407 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +000010408 return ExprError();
John McCall1d318332010-01-12 00:44:57 +000010409 }
Douglas Gregor063daf62009-03-13 18:40:31 +000010410
Douglas Gregor33074752009-09-30 21:46:01 +000010411 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +000010412 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +000010413}
10414
John McCall60d7b3a2010-08-24 06:29:42 +000010415ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +000010416Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
10417 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +000010418 Expr *Base, Expr *Idx) {
10419 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +000010420 DeclarationName OpName =
10421 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
10422
10423 // If either side is type-dependent, create an appropriate dependent
10424 // expression.
10425 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
10426
John McCallc373d482010-01-27 01:50:18 +000010427 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +000010428 // CHECKME: no 'operator' keyword?
10429 DeclarationNameInfo OpNameInfo(OpName, LLoc);
10430 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +000010431 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +000010432 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +000010433 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +000010434 /*ADL*/ true, /*Overloaded*/ false,
10435 UnresolvedSetIterator(),
10436 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +000010437 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +000010438
Sebastian Redlf322ed62009-10-29 20:17:01 +000010439 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010440 Args,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010441 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +000010442 VK_RValue,
Lang Hamesbe9af122012-10-02 04:45:10 +000010443 RLoc, false));
Sebastian Redlf322ed62009-10-29 20:17:01 +000010444 }
10445
John McCall5acb0c92011-10-17 18:40:02 +000010446 // Handle placeholders on both operands.
10447 if (checkPlaceholderForOverload(*this, Args[0]))
10448 return ExprError();
10449 if (checkPlaceholderForOverload(*this, Args[1]))
10450 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010451
Sebastian Redlf322ed62009-10-29 20:17:01 +000010452 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +000010453 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010454
10455 // Subscript can only be overloaded as a member function.
10456
10457 // Add operator candidates that are member functions.
10458 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10459
10460 // Add builtin operator candidates.
10461 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
10462
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010463 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10464
Sebastian Redlf322ed62009-10-29 20:17:01 +000010465 // Perform overload resolution.
10466 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010467 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +000010468 case OR_Success: {
10469 // We found a built-in operator or an overloaded operator.
10470 FunctionDecl *FnDecl = Best->Function;
10471
10472 if (FnDecl) {
10473 // We matched an overloaded operator. Build a call to that
10474 // operator.
10475
Eli Friedman5f2987c2012-02-02 03:46:19 +000010476 MarkFunctionReferenced(LLoc, FnDecl);
Chandler Carruth25ca4212011-02-25 19:41:05 +000010477
John McCall9aa472c2010-03-19 07:35:19 +000010478 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010479 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +000010480
Sebastian Redlf322ed62009-10-29 20:17:01 +000010481 // Convert the arguments.
10482 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +000010483 ExprResult Arg0 =
10484 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
10485 Best->FoundDecl, Method);
10486 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010487 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010488 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010489
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010490 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +000010491 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010492 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010493 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010494 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010495 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +000010496 Owned(Args[1]));
10497 if (InputInit.isInvalid())
10498 return ExprError();
10499
10500 Args[1] = InputInit.takeAs<Expr>();
10501
Sebastian Redlf322ed62009-10-29 20:17:01 +000010502 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +000010503 QualType ResultTy = FnDecl->getResultType();
10504 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10505 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010506
10507 // Build the actual expression node.
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010508 DeclarationNameInfo OpLocInfo(OpName, LLoc);
10509 OpLocInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010510 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
10511 HadMultipleCandidates,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000010512 OpLocInfo.getLoc(),
10513 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000010514 if (FnExpr.isInvalid())
10515 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010516
John McCall9ae2f072010-08-23 23:25:46 +000010517 CXXOperatorCallExpr *TheCall =
10518 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010519 FnExpr.take(), Args,
Lang Hamesbe9af122012-10-02 04:45:10 +000010520 ResultTy, VK, RLoc,
10521 false);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010522
John McCall9ae2f072010-08-23 23:25:46 +000010523 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +000010524 FnDecl))
10525 return ExprError();
10526
John McCall9ae2f072010-08-23 23:25:46 +000010527 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010528 } else {
10529 // We matched a built-in operator. Convert the arguments, then
10530 // break out so that we will build the appropriate built-in
10531 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +000010532 ExprResult ArgsRes0 =
10533 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
10534 Best->Conversions[0], AA_Passing);
10535 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +000010536 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010537 Args[0] = ArgsRes0.take();
10538
10539 ExprResult ArgsRes1 =
10540 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
10541 Best->Conversions[1], AA_Passing);
10542 if (ArgsRes1.isInvalid())
10543 return ExprError();
10544 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010545
10546 break;
10547 }
10548 }
10549
10550 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +000010551 if (CandidateSet.empty())
10552 Diag(LLoc, diag::err_ovl_no_oper)
10553 << Args[0]->getType() << /*subscript*/ 0
10554 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
10555 else
10556 Diag(LLoc, diag::err_ovl_no_viable_subscript)
10557 << Args[0]->getType()
10558 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010559 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010560 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +000010561 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +000010562 }
10563
10564 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010565 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010566 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +000010567 << Args[0]->getType() << Args[1]->getType()
10568 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010569 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010570 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010571 return ExprError();
10572
10573 case OR_Deleted:
10574 Diag(LLoc, diag::err_ovl_deleted_oper)
10575 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010576 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +000010577 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010578 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args,
John McCall120d63c2010-08-24 20:38:10 +000010579 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010580 return ExprError();
10581 }
10582
10583 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +000010584 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +000010585}
10586
Douglas Gregor88a35142008-12-22 05:46:06 +000010587/// BuildCallToMemberFunction - Build a call to a member
10588/// function. MemExpr is the expression that refers to the member
10589/// function (and includes the object parameter), Args/NumArgs are the
10590/// arguments to the function call (not including the object
10591/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +000010592/// expression refers to a non-static member function or an overloaded
10593/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +000010594ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +000010595Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
10596 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +000010597 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +000010598 assert(MemExprE->getType() == Context.BoundMemberTy ||
10599 MemExprE->getType() == Context.OverloadTy);
10600
Douglas Gregor88a35142008-12-22 05:46:06 +000010601 // Dig out the member expression. This holds both the object
10602 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +000010603 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010604
John McCall864c0412011-04-26 20:42:42 +000010605 // Determine whether this is a call to a pointer-to-member function.
10606 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
10607 assert(op->getType() == Context.BoundMemberTy);
10608 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
10609
10610 QualType fnType =
10611 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
10612
10613 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
10614 QualType resultType = proto->getCallResultType(Context);
10615 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
10616
10617 // Check that the object type isn't more qualified than the
10618 // member function we're calling.
10619 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
10620
10621 QualType objectType = op->getLHS()->getType();
10622 if (op->getOpcode() == BO_PtrMemI)
10623 objectType = objectType->castAs<PointerType>()->getPointeeType();
10624 Qualifiers objectQuals = objectType.getQualifiers();
10625
10626 Qualifiers difference = objectQuals - funcQuals;
10627 difference.removeObjCGCAttr();
10628 difference.removeAddressSpace();
10629 if (difference) {
10630 std::string qualsString = difference.getAsString();
10631 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
10632 << fnType.getUnqualifiedType()
10633 << qualsString
10634 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
10635 }
10636
10637 CXXMemberCallExpr *call
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010638 = new (Context) CXXMemberCallExpr(Context, MemExprE,
10639 llvm::makeArrayRef(Args, NumArgs),
John McCall864c0412011-04-26 20:42:42 +000010640 resultType, valueKind, RParenLoc);
10641
10642 if (CheckCallReturnType(proto->getResultType(),
Daniel Dunbar96a00142012-03-09 18:35:03 +000010643 op->getRHS()->getLocStart(),
John McCall864c0412011-04-26 20:42:42 +000010644 call, 0))
10645 return ExprError();
10646
10647 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
10648 return ExprError();
10649
10650 return MaybeBindToTemporary(call);
10651 }
10652
John McCall5acb0c92011-10-17 18:40:02 +000010653 UnbridgedCastsSet UnbridgedCasts;
10654 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10655 return ExprError();
10656
John McCall129e2df2009-11-30 22:42:35 +000010657 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +000010658 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +000010659 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010660 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +000010661 if (isa<MemberExpr>(NakedMemExpr)) {
10662 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +000010663 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +000010664 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +000010665 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +000010666 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +000010667 } else {
10668 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +000010669 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010670
John McCall701c89e2009-12-03 04:06:58 +000010671 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010672 Expr::Classification ObjectClassification
10673 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
10674 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +000010675
Douglas Gregor88a35142008-12-22 05:46:06 +000010676 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +000010677 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +000010678
John McCallaa81e162009-12-01 22:10:20 +000010679 // FIXME: avoid copy.
10680 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10681 if (UnresExpr->hasExplicitTemplateArgs()) {
10682 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10683 TemplateArgs = &TemplateArgsBuffer;
10684 }
10685
John McCall129e2df2009-11-30 22:42:35 +000010686 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
10687 E = UnresExpr->decls_end(); I != E; ++I) {
10688
John McCall701c89e2009-12-03 04:06:58 +000010689 NamedDecl *Func = *I;
10690 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
10691 if (isa<UsingShadowDecl>(Func))
10692 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
10693
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010694
Francois Pichetdbee3412011-01-18 05:04:39 +000010695 // Microsoft supports direct constructor calls.
David Blaikie4e4d0842012-03-11 07:00:24 +000010696 if (getLangOpts().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Ahmed Charles13a140c2012-02-25 11:00:22 +000010697 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(),
10698 llvm::makeArrayRef(Args, NumArgs), CandidateSet);
Francois Pichetdbee3412011-01-18 05:04:39 +000010699 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010700 // If explicit template arguments were provided, we can't call a
10701 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +000010702 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +000010703 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010704
John McCall9aa472c2010-03-19 07:35:19 +000010705 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010706 ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010707 llvm::makeArrayRef(Args, NumArgs), CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010708 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010709 } else {
John McCall129e2df2009-11-30 22:42:35 +000010710 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +000010711 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010712 ObjectType, ObjectClassification,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010713 llvm::makeArrayRef(Args, NumArgs),
10714 CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +000010715 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +000010716 }
Douglas Gregordec06662009-08-21 18:42:58 +000010717 }
Mike Stump1eb44332009-09-09 15:08:12 +000010718
John McCall129e2df2009-11-30 22:42:35 +000010719 DeclarationName DeclName = UnresExpr->getMemberName();
10720
John McCall5acb0c92011-10-17 18:40:02 +000010721 UnbridgedCasts.restore();
10722
Douglas Gregor88a35142008-12-22 05:46:06 +000010723 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010724 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +000010725 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +000010726 case OR_Success:
10727 Method = cast<CXXMethodDecl>(Best->Function);
Eli Friedman5f2987c2012-02-02 03:46:19 +000010728 MarkFunctionReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +000010729 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +000010730 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010731 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +000010732 break;
10733
10734 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +000010735 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +000010736 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010737 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010738 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10739 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010740 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010741 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010742
10743 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +000010744 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +000010745 << DeclName << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010746 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10747 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor88a35142008-12-22 05:46:06 +000010748 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010749 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010750
10751 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +000010752 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010753 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010754 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010755 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010756 << MemExprE->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010757 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10758 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010759 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +000010760 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010761 }
10762
John McCall6bb80172010-03-30 21:47:33 +000010763 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +000010764
John McCallaa81e162009-12-01 22:10:20 +000010765 // If overload resolution picked a static member, build a
10766 // non-member call based on that function.
10767 if (Method->isStatic()) {
10768 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
10769 Args, NumArgs, RParenLoc);
10770 }
10771
John McCall129e2df2009-11-30 22:42:35 +000010772 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +000010773 }
10774
John McCallf89e55a2010-11-18 06:31:45 +000010775 QualType ResultType = Method->getResultType();
10776 ExprValueKind VK = Expr::getValueKindForType(ResultType);
10777 ResultType = ResultType.getNonLValueExprType(Context);
10778
Douglas Gregor88a35142008-12-22 05:46:06 +000010779 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010780 CXXMemberCallExpr *TheCall =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000010781 new (Context) CXXMemberCallExpr(Context, MemExprE,
10782 llvm::makeArrayRef(Args, NumArgs),
John McCallf89e55a2010-11-18 06:31:45 +000010783 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +000010784
Anders Carlssoneed3e692009-10-10 00:06:20 +000010785 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010786 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +000010787 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +000010788 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010789
Douglas Gregor88a35142008-12-22 05:46:06 +000010790 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +000010791 // We only need to do this if there was actually an overload; otherwise
10792 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +000010793 if (!Method->isStatic()) {
10794 ExprResult ObjectArg =
10795 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
10796 FoundDecl, Method);
10797 if (ObjectArg.isInvalid())
10798 return ExprError();
10799 MemExpr->setBase(ObjectArg.take());
10800 }
Douglas Gregor88a35142008-12-22 05:46:06 +000010801
10802 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +000010803 const FunctionProtoType *Proto =
10804 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +000010805 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +000010806 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +000010807 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +000010808
Eli Friedmane61eb042012-02-18 04:48:30 +000010809 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
10810
Richard Smith831421f2012-06-25 20:30:08 +000010811 if (CheckFunctionCall(Method, TheCall, Proto))
John McCallaa81e162009-12-01 22:10:20 +000010812 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +000010813
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010814 if ((isa<CXXConstructorDecl>(CurContext) ||
10815 isa<CXXDestructorDecl>(CurContext)) &&
10816 TheCall->getMethodDecl()->isPure()) {
10817 const CXXMethodDecl *MD = TheCall->getMethodDecl();
10818
Chandler Carruthae198062011-06-27 08:31:58 +000010819 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010820 Diag(MemExpr->getLocStart(),
10821 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
10822 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
10823 << MD->getParent()->getDeclName();
10824
10825 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +000010826 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +000010827 }
John McCall9ae2f072010-08-23 23:25:46 +000010828 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +000010829}
10830
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010831/// BuildCallToObjectOfClassType - Build a call to an object of class
10832/// type (C++ [over.call.object]), which can end up invoking an
10833/// overloaded function call operator (@c operator()) or performing a
10834/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +000010835ExprResult
John Wiegley429bb272011-04-08 18:41:53 +000010836Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +000010837 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010838 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010839 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +000010840 if (checkPlaceholderForOverload(*this, Obj))
10841 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010842 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +000010843
10844 UnbridgedCastsSet UnbridgedCasts;
10845 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
10846 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010847
John Wiegley429bb272011-04-08 18:41:53 +000010848 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
10849 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +000010850
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010851 // C++ [over.call.object]p1:
10852 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +000010853 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010854 // candidate functions includes at least the function call
10855 // operators of T. The function call operators of T are obtained by
10856 // ordinary lookup of the name operator() in the context of
10857 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +000010858 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +000010859 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +000010860
John Wiegley429bb272011-04-08 18:41:53 +000010861 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000010862 diag::err_incomplete_object_call, Object.get()))
Douglas Gregor593564b2009-11-15 07:48:03 +000010863 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010864
John McCalla24dc2e2009-11-17 02:14:36 +000010865 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
10866 LookupQualifiedName(R, Record->getDecl());
10867 R.suppressDiagnostics();
10868
Douglas Gregor593564b2009-11-15 07:48:03 +000010869 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +000010870 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +000010871 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
10872 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +000010873 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +000010874 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010875
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010876 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010877 // In addition, for each (non-explicit in C++0x) conversion function
10878 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010879 //
10880 // operator conversion-type-id () cv-qualifier;
10881 //
10882 // where cv-qualifier is the same cv-qualification as, or a
10883 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +000010884 // denotes the type "pointer to function of (P1,...,Pn) returning
10885 // R", or the type "reference to pointer to function of
10886 // (P1,...,Pn) returning R", or the type "reference to function
10887 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010888 // is also considered as a candidate function. Similarly,
10889 // surrogate call functions are added to the set of candidate
10890 // functions for each conversion function declared in an
10891 // accessible base class provided the function is not hidden
10892 // within T by another intervening declaration.
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010893 std::pair<CXXRecordDecl::conversion_iterator,
10894 CXXRecordDecl::conversion_iterator> Conversions
Douglas Gregor90073282010-01-11 19:36:35 +000010895 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
Argyrios Kyrtzidis9d295432012-11-28 03:56:09 +000010896 for (CXXRecordDecl::conversion_iterator
10897 I = Conversions.first, E = Conversions.second; I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +000010898 NamedDecl *D = *I;
10899 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
10900 if (isa<UsingShadowDecl>(D))
10901 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010902
Douglas Gregor4a27d702009-10-21 06:18:39 +000010903 // Skip over templated conversion functions; they aren't
10904 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +000010905 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +000010906 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +000010907
John McCall701c89e2009-12-03 04:06:58 +000010908 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010909 if (!Conv->isExplicit()) {
10910 // Strip the reference type (if any) and then the pointer type (if
10911 // any) to get down to what might be a function type.
10912 QualType ConvType = Conv->getConversionType().getNonReferenceType();
10913 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
10914 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +000010915
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010916 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
10917 {
10918 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Ahmed Charles13a140c2012-02-25 11:00:22 +000010919 Object.get(), llvm::makeArrayRef(Args, NumArgs),
10920 CandidateSet);
Douglas Gregorbf6e3172011-07-23 18:59:35 +000010921 }
10922 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010923 }
Mike Stump1eb44332009-09-09 15:08:12 +000010924
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010925 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10926
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010927 // Perform overload resolution.
10928 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +000010929 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +000010930 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010931 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010932 // Overload resolution succeeded; we'll build the appropriate call
10933 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010934 break;
10935
10936 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +000010937 if (CandidateSet.empty())
Daniel Dunbar96a00142012-03-09 18:35:03 +000010938 Diag(Object.get()->getLocStart(), diag::err_ovl_no_oper)
John Wiegley429bb272011-04-08 18:41:53 +000010939 << Object.get()->getType() << /*call*/ 1
10940 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +000010941 else
Daniel Dunbar96a00142012-03-09 18:35:03 +000010942 Diag(Object.get()->getLocStart(),
John McCall1eb3e102010-01-07 02:04:15 +000010943 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010944 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010945 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10946 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010947 break;
10948
10949 case OR_Ambiguous:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010950 Diag(Object.get()->getLocStart(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010951 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +000010952 << Object.get()->getType() << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010953 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
10954 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010955 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010956
10957 case OR_Deleted:
Daniel Dunbar96a00142012-03-09 18:35:03 +000010958 Diag(Object.get()->getLocStart(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010959 diag::err_ovl_deleted_object_call)
10960 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +000010961 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010962 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +000010963 << Object.get()->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000010964 CandidateSet.NoteCandidates(*this, OCD_AllCandidates,
10965 llvm::makeArrayRef(Args, NumArgs));
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010966 break;
Mike Stump1eb44332009-09-09 15:08:12 +000010967 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010968
Douglas Gregorff331c12010-07-25 18:17:45 +000010969 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010970 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010971
John McCall5acb0c92011-10-17 18:40:02 +000010972 UnbridgedCasts.restore();
10973
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010974 if (Best->Function == 0) {
10975 // Since there is no function declaration, this is one of the
10976 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +000010977 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010978 = cast<CXXConversionDecl>(
10979 Best->Conversions[0].UserDefined.ConversionFunction);
10980
John Wiegley429bb272011-04-08 18:41:53 +000010981 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010982 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010983
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010984 // We selected one of the surrogate functions that converts the
10985 // object parameter to a function pointer. Perform the conversion
10986 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010987
Fariborz Jahaniand8307b12009-09-28 18:35:46 +000010988 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +000010989 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010990 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
10991 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010992 if (Call.isInvalid())
10993 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010994 // Record usage of conversion in an implicit cast.
10995 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10996 CK_UserDefinedConversion,
10997 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010998
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010999 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000011000 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011001 }
11002
Eli Friedman5f2987c2012-02-02 03:46:19 +000011003 MarkFunctionReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011004 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011005 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000011006
Douglas Gregor106c6eb2008-11-19 22:57:39 +000011007 // We found an overloaded operator(). Build a CXXOperatorCallExpr
11008 // that calls this method, using Object for the implicit object
11009 // parameter and passing along the remaining arguments.
11010 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Nico Webere0ff6902012-11-09 06:06:14 +000011011
11012 // An error diagnostic has already been printed when parsing the declaration.
Nico Weber1a52a4d2012-11-09 08:38:04 +000011013 if (Method->isInvalidDecl())
Nico Webere0ff6902012-11-09 06:06:14 +000011014 return ExprError();
11015
Chandler Carruth6df868e2010-12-12 08:17:55 +000011016 const FunctionProtoType *Proto =
11017 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011018
11019 unsigned NumArgsInProto = Proto->getNumArgs();
11020 unsigned NumArgsToCheck = NumArgs;
11021
11022 // Build the full argument list for the method call (the
11023 // implicit object parameter is placed at the beginning of the
11024 // list).
11025 Expr **MethodArgs;
11026 if (NumArgs < NumArgsInProto) {
11027 NumArgsToCheck = NumArgsInProto;
11028 MethodArgs = new Expr*[NumArgsInProto + 1];
11029 } else {
11030 MethodArgs = new Expr*[NumArgs + 1];
11031 }
John Wiegley429bb272011-04-08 18:41:53 +000011032 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011033 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
11034 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000011035
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011036 DeclarationNameInfo OpLocInfo(
11037 Context.DeclarationNames.getCXXOperatorName(OO_Call), LParenLoc);
11038 OpLocInfo.setCXXOperatorNameRange(SourceRange(LParenLoc, RParenLoc));
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011039 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011040 HadMultipleCandidates,
11041 OpLocInfo.getLoc(),
11042 OpLocInfo.getInfo());
John Wiegley429bb272011-04-08 18:41:53 +000011043 if (NewFn.isInvalid())
11044 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011045
11046 // Once we've built TheCall, all of the expressions are properly
11047 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000011048 QualType ResultTy = Method->getResultType();
11049 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11050 ResultTy = ResultTy.getNonLValueExprType(Context);
11051
John McCall9ae2f072010-08-23 23:25:46 +000011052 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011053 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011054 llvm::makeArrayRef(MethodArgs, NumArgs+1),
Lang Hamesbe9af122012-10-02 04:45:10 +000011055 ResultTy, VK, RParenLoc, false);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011056 delete [] MethodArgs;
11057
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011058 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000011059 Method))
11060 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011061
Douglas Gregor518fda12009-01-13 05:10:00 +000011062 // We may have default arguments. If so, we need to allocate more
11063 // slots in the call for them.
11064 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000011065 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000011066 else if (NumArgs > NumArgsInProto)
11067 NumArgsToCheck = NumArgsInProto;
11068
Chris Lattner312531a2009-04-12 08:11:20 +000011069 bool IsError = false;
11070
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011071 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000011072 ExprResult ObjRes =
11073 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
11074 Best->FoundDecl, Method);
11075 if (ObjRes.isInvalid())
11076 IsError = true;
11077 else
Benjamin Kramer3fe198b2012-08-23 21:35:17 +000011078 Object = ObjRes;
John Wiegley429bb272011-04-08 18:41:53 +000011079 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000011080
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011081 // Check the argument types.
11082 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011083 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000011084 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011085 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000011086
Douglas Gregor518fda12009-01-13 05:10:00 +000011087 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000011088
John McCall60d7b3a2010-08-24 06:29:42 +000011089 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000011090 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000011091 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000011092 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000011093 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011094
Anders Carlsson3faa4862010-01-29 18:43:53 +000011095 IsError |= InputInit.isInvalid();
11096 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011097 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000011098 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000011099 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
11100 if (DefArg.isInvalid()) {
11101 IsError = true;
11102 break;
11103 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011104
Douglas Gregord47c47d2009-11-09 19:27:57 +000011105 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000011106 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011107
11108 TheCall->setArg(i + 1, Arg);
11109 }
11110
11111 // If this is a variadic call, handle args passed through "...".
11112 if (Proto->isVariadic()) {
11113 // Promote the arguments (C99 6.5.2.2p7).
Aaron Ballman4914c282012-07-20 20:40:35 +000011114 for (unsigned i = NumArgsInProto; i < NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000011115 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
11116 IsError |= Arg.isInvalid();
11117 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011118 }
11119 }
11120
Chris Lattner312531a2009-04-12 08:11:20 +000011121 if (IsError) return true;
11122
Eli Friedmane61eb042012-02-18 04:48:30 +000011123 DiagnoseSentinelCalls(Method, LParenLoc, Args, NumArgs);
11124
Richard Smith831421f2012-06-25 20:30:08 +000011125 if (CheckFunctionCall(Method, TheCall, Proto))
Anders Carlssond406bf02009-08-16 01:56:34 +000011126 return true;
11127
John McCall182f7092010-08-24 06:09:16 +000011128 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000011129}
11130
Douglas Gregor8ba10742008-11-20 16:27:02 +000011131/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000011132/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000011133/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000011134ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000011135Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000011136 assert(Base->getType()->isRecordType() &&
11137 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000011138
John McCall5acb0c92011-10-17 18:40:02 +000011139 if (checkPlaceholderForOverload(*this, Base))
11140 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000011141
John McCall5769d612010-02-08 23:07:23 +000011142 SourceLocation Loc = Base->getExprLoc();
11143
Douglas Gregor8ba10742008-11-20 16:27:02 +000011144 // C++ [over.ref]p1:
11145 //
11146 // [...] An expression x->m is interpreted as (x.operator->())->m
11147 // for a class object x of type T if T::operator->() exists and if
11148 // the operator is selected as the best match function by the
11149 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000011150 DeclarationName OpName =
11151 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000011152 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000011153 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011154
John McCall5769d612010-02-08 23:07:23 +000011155 if (RequireCompleteType(Loc, Base->getType(),
Douglas Gregord10099e2012-05-04 16:32:21 +000011156 diag::err_typecheck_incomplete_tag, Base))
Eli Friedmanf43fb722009-11-18 01:28:03 +000011157 return ExprError();
11158
John McCalla24dc2e2009-11-17 02:14:36 +000011159 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
11160 LookupQualifiedName(R, BaseRecord->getDecl());
11161 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000011162
11163 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000011164 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000011165 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
11166 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000011167 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000011168
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011169 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11170
Douglas Gregor8ba10742008-11-20 16:27:02 +000011171 // Perform overload resolution.
11172 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000011173 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000011174 case OR_Success:
11175 // Overload resolution succeeded; we'll build the call below.
11176 break;
11177
11178 case OR_No_Viable_Function:
11179 if (CandidateSet.empty())
11180 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011181 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011182 else
11183 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011184 << "operator->" << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011185 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011186 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011187
11188 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000011189 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
11190 << "->" << Base->getType() << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011191 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011192 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000011193
11194 case OR_Deleted:
11195 Diag(OpLoc, diag::err_ovl_deleted_oper)
11196 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011197 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000011198 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000011199 << Base->getSourceRange();
Ahmed Charles13a140c2012-02-25 11:00:22 +000011200 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Base);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011201 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000011202 }
11203
Eli Friedman5f2987c2012-02-02 03:46:19 +000011204 MarkFunctionReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000011205 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000011206 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000011207
Douglas Gregor8ba10742008-11-20 16:27:02 +000011208 // Convert the object parameter.
11209 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000011210 ExprResult BaseResult =
11211 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
11212 Best->FoundDecl, Method);
11213 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000011214 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000011215 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000011216
Douglas Gregor8ba10742008-11-20 16:27:02 +000011217 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011218 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
Argyrios Kyrtzidis46e75472012-02-08 01:21:13 +000011219 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +000011220 if (FnExpr.isInvalid())
11221 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011222
John McCallf89e55a2010-11-18 06:31:45 +000011223 QualType ResultTy = Method->getResultType();
11224 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11225 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000011226 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000011227 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
Lang Hamesbe9af122012-10-02 04:45:10 +000011228 Base, ResultTy, VK, OpLoc, false);
Anders Carlsson15ea3782009-10-13 22:43:21 +000011229
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011230 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000011231 Method))
11232 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000011233
11234 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000011235}
11236
Richard Smith36f5cfe2012-03-09 08:00:36 +000011237/// BuildLiteralOperatorCall - Build a UserDefinedLiteral by creating a call to
11238/// a literal operator described by the provided lookup results.
11239ExprResult Sema::BuildLiteralOperatorCall(LookupResult &R,
11240 DeclarationNameInfo &SuffixInfo,
11241 ArrayRef<Expr*> Args,
11242 SourceLocation LitEndLoc,
11243 TemplateArgumentListInfo *TemplateArgs) {
11244 SourceLocation UDSuffixLoc = SuffixInfo.getCXXLiteralOperatorNameLoc();
Richard Smith9fcce652012-03-07 08:35:16 +000011245
Richard Smith36f5cfe2012-03-09 08:00:36 +000011246 OverloadCandidateSet CandidateSet(UDSuffixLoc);
11247 AddFunctionCandidates(R.asUnresolvedSet(), Args, CandidateSet, true,
11248 TemplateArgs);
Richard Smith9fcce652012-03-07 08:35:16 +000011249
Richard Smith36f5cfe2012-03-09 08:00:36 +000011250 bool HadMultipleCandidates = (CandidateSet.size() > 1);
11251
Richard Smith36f5cfe2012-03-09 08:00:36 +000011252 // Perform overload resolution. This will usually be trivial, but might need
11253 // to perform substitutions for a literal operator template.
11254 OverloadCandidateSet::iterator Best;
11255 switch (CandidateSet.BestViableFunction(*this, UDSuffixLoc, Best)) {
11256 case OR_Success:
11257 case OR_Deleted:
11258 break;
11259
11260 case OR_No_Viable_Function:
11261 Diag(UDSuffixLoc, diag::err_ovl_no_viable_function_in_call)
11262 << R.getLookupName();
11263 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args);
11264 return ExprError();
11265
11266 case OR_Ambiguous:
11267 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
11268 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args);
11269 return ExprError();
Richard Smith9fcce652012-03-07 08:35:16 +000011270 }
11271
Richard Smith36f5cfe2012-03-09 08:00:36 +000011272 FunctionDecl *FD = Best->Function;
11273 MarkFunctionReferenced(UDSuffixLoc, FD);
11274 DiagnoseUseOfDecl(Best->FoundDecl, UDSuffixLoc);
Richard Smith9fcce652012-03-07 08:35:16 +000011275
Richard Smith36f5cfe2012-03-09 08:00:36 +000011276 ExprResult Fn = CreateFunctionRefExpr(*this, FD, HadMultipleCandidates,
11277 SuffixInfo.getLoc(),
11278 SuffixInfo.getInfo());
11279 if (Fn.isInvalid())
11280 return true;
Richard Smith9fcce652012-03-07 08:35:16 +000011281
11282 // Check the argument types. This should almost always be a no-op, except
11283 // that array-to-pointer decay is applied to string literals.
Richard Smith9fcce652012-03-07 08:35:16 +000011284 Expr *ConvArgs[2];
11285 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
11286 ExprResult InputInit = PerformCopyInitialization(
11287 InitializedEntity::InitializeParameter(Context, FD->getParamDecl(ArgIdx)),
11288 SourceLocation(), Args[ArgIdx]);
11289 if (InputInit.isInvalid())
11290 return true;
11291 ConvArgs[ArgIdx] = InputInit.take();
11292 }
11293
Richard Smith9fcce652012-03-07 08:35:16 +000011294 QualType ResultTy = FD->getResultType();
11295 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
11296 ResultTy = ResultTy.getNonLValueExprType(Context);
11297
Richard Smith9fcce652012-03-07 08:35:16 +000011298 UserDefinedLiteral *UDL =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000011299 new (Context) UserDefinedLiteral(Context, Fn.take(),
11300 llvm::makeArrayRef(ConvArgs, Args.size()),
Richard Smith9fcce652012-03-07 08:35:16 +000011301 ResultTy, VK, LitEndLoc, UDSuffixLoc);
11302
11303 if (CheckCallReturnType(FD->getResultType(), UDSuffixLoc, UDL, FD))
11304 return ExprError();
11305
Richard Smith831421f2012-06-25 20:30:08 +000011306 if (CheckFunctionCall(FD, UDL, NULL))
Richard Smith9fcce652012-03-07 08:35:16 +000011307 return ExprError();
11308
11309 return MaybeBindToTemporary(UDL);
11310}
11311
Sam Panzere1715b62012-08-21 00:52:01 +000011312/// Build a call to 'begin' or 'end' for a C++11 for-range statement. If the
11313/// given LookupResult is non-empty, it is assumed to describe a member which
11314/// will be invoked. Otherwise, the function will be found via argument
11315/// dependent lookup.
11316/// CallExpr is set to a valid expression and FRS_Success returned on success,
11317/// otherwise CallExpr is set to ExprError() and some non-success value
11318/// is returned.
11319Sema::ForRangeStatus
11320Sema::BuildForRangeBeginEndCall(Scope *S, SourceLocation Loc,
11321 SourceLocation RangeLoc, VarDecl *Decl,
11322 BeginEndFunction BEF,
11323 const DeclarationNameInfo &NameInfo,
11324 LookupResult &MemberLookup,
11325 OverloadCandidateSet *CandidateSet,
11326 Expr *Range, ExprResult *CallExpr) {
11327 CandidateSet->clear();
11328 if (!MemberLookup.empty()) {
11329 ExprResult MemberRef =
11330 BuildMemberReferenceExpr(Range, Range->getType(), Loc,
11331 /*IsPtr=*/false, CXXScopeSpec(),
11332 /*TemplateKWLoc=*/SourceLocation(),
11333 /*FirstQualifierInScope=*/0,
11334 MemberLookup,
11335 /*TemplateArgs=*/0);
11336 if (MemberRef.isInvalid()) {
11337 *CallExpr = ExprError();
11338 Diag(Range->getLocStart(), diag::note_in_for_range)
11339 << RangeLoc << BEF << Range->getType();
11340 return FRS_DiagnosticIssued;
11341 }
11342 *CallExpr = ActOnCallExpr(S, MemberRef.get(), Loc, MultiExprArg(), Loc, 0);
11343 if (CallExpr->isInvalid()) {
11344 *CallExpr = ExprError();
11345 Diag(Range->getLocStart(), diag::note_in_for_range)
11346 << RangeLoc << BEF << Range->getType();
11347 return FRS_DiagnosticIssued;
11348 }
11349 } else {
11350 UnresolvedSet<0> FoundNames;
Sam Panzere1715b62012-08-21 00:52:01 +000011351 UnresolvedLookupExpr *Fn =
11352 UnresolvedLookupExpr::Create(Context, /*NamingClass=*/0,
11353 NestedNameSpecifierLoc(), NameInfo,
11354 /*NeedsADL=*/true, /*Overloaded=*/false,
Richard Smithb1502bc2012-10-18 17:56:02 +000011355 FoundNames.begin(), FoundNames.end());
Sam Panzere1715b62012-08-21 00:52:01 +000011356
11357 bool CandidateSetError = buildOverloadedCallSet(S, Fn, Fn, &Range, 1, Loc,
11358 CandidateSet, CallExpr);
11359 if (CandidateSet->empty() || CandidateSetError) {
11360 *CallExpr = ExprError();
11361 return FRS_NoViableFunction;
11362 }
11363 OverloadCandidateSet::iterator Best;
11364 OverloadingResult OverloadResult =
11365 CandidateSet->BestViableFunction(*this, Fn->getLocStart(), Best);
11366
11367 if (OverloadResult == OR_No_Viable_Function) {
11368 *CallExpr = ExprError();
11369 return FRS_NoViableFunction;
11370 }
11371 *CallExpr = FinishOverloadedCallExpr(*this, S, Fn, Fn, Loc, &Range, 1,
11372 Loc, 0, CandidateSet, &Best,
11373 OverloadResult,
11374 /*AllowTypoCorrection=*/false);
11375 if (CallExpr->isInvalid() || OverloadResult != OR_Success) {
11376 *CallExpr = ExprError();
11377 Diag(Range->getLocStart(), diag::note_in_for_range)
11378 << RangeLoc << BEF << Range->getType();
11379 return FRS_DiagnosticIssued;
11380 }
11381 }
11382 return FRS_Success;
11383}
11384
11385
Douglas Gregor904eed32008-11-10 20:40:00 +000011386/// FixOverloadedFunctionReference - E is an expression that refers to
11387/// a C++ overloaded function (possibly with some parentheses and
11388/// perhaps a '&' around it). We have resolved the overloaded function
11389/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000011390/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000011391Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000011392 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000011393 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011394 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
11395 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011396 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011397 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011398
Douglas Gregor699ee522009-11-20 19:42:02 +000011399 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011400 }
11401
Douglas Gregor699ee522009-11-20 19:42:02 +000011402 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000011403 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
11404 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011405 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000011406 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000011407 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000011408 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000011409 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011410 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011411
11412 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000011413 ICE->getCastKind(),
11414 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000011415 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011416 }
11417
Douglas Gregor699ee522009-11-20 19:42:02 +000011418 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000011419 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000011420 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000011421 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
11422 if (Method->isStatic()) {
11423 // Do nothing: static member functions aren't any different
11424 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000011425 } else {
John McCallf7a1a742009-11-24 19:00:30 +000011426 // Fix the sub expression, which really has to be an
11427 // UnresolvedLookupExpr holding an overloaded member function
11428 // or template.
John McCall6bb80172010-03-30 21:47:33 +000011429 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11430 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000011431 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011432 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000011433
John McCallba135432009-11-21 08:51:07 +000011434 assert(isa<DeclRefExpr>(SubExpr)
11435 && "fixed to something other than a decl ref");
11436 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
11437 && "fixed to a member ref with no nested name qualifier");
11438
11439 // We have taken the address of a pointer to member
11440 // function. Perform the computation here so that we get the
11441 // appropriate pointer to member type.
11442 QualType ClassType
11443 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
11444 QualType MemPtrType
11445 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
11446
John McCallf89e55a2010-11-18 06:31:45 +000011447 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
11448 VK_RValue, OK_Ordinary,
11449 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000011450 }
11451 }
John McCall6bb80172010-03-30 21:47:33 +000011452 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
11453 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000011454 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000011455 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011456
John McCall2de56d12010-08-25 11:45:40 +000011457 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000011458 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000011459 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000011460 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011461 }
John McCallba135432009-11-21 08:51:07 +000011462
11463 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000011464 // FIXME: avoid copy.
11465 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000011466 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000011467 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
11468 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000011469 }
11470
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011471 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11472 ULE->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011473 ULE->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011474 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011475 /*enclosing*/ false, // FIXME?
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011476 ULE->getNameLoc(),
11477 Fn->getType(),
11478 VK_LValue,
11479 Found.getDecl(),
11480 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011481 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011482 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
11483 return DRE;
John McCallba135432009-11-21 08:51:07 +000011484 }
11485
John McCall129e2df2009-11-30 22:42:35 +000011486 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000011487 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000011488 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
11489 if (MemExpr->hasExplicitTemplateArgs()) {
11490 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
11491 TemplateArgs = &TemplateArgsBuffer;
11492 }
John McCalld5532b62009-11-23 01:53:49 +000011493
John McCallaa81e162009-12-01 22:10:20 +000011494 Expr *Base;
11495
John McCallf89e55a2010-11-18 06:31:45 +000011496 // If we're filling in a static method where we used to have an
11497 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000011498 if (MemExpr->isImplicitAccess()) {
11499 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011500 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
11501 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011502 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011503 Fn,
John McCallf4b88a42012-03-10 09:33:50 +000011504 /*enclosing*/ false,
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011505 MemExpr->getMemberLoc(),
11506 Fn->getType(),
11507 VK_LValue,
11508 Found.getDecl(),
11509 TemplateArgs);
Richard Smithe6975e92012-04-17 00:58:00 +000011510 MarkDeclRefReferenced(DRE);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011511 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
11512 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000011513 } else {
11514 SourceLocation Loc = MemExpr->getMemberLoc();
11515 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000011516 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Eli Friedman72899c32012-01-07 04:59:52 +000011517 CheckCXXThisCapture(Loc);
Douglas Gregor828a1972010-01-07 23:12:05 +000011518 Base = new (Context) CXXThisExpr(Loc,
11519 MemExpr->getBaseType(),
11520 /*isImplicit=*/true);
11521 }
John McCallaa81e162009-12-01 22:10:20 +000011522 } else
John McCall3fa5cae2010-10-26 07:05:15 +000011523 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000011524
John McCallf5307512011-04-27 00:36:17 +000011525 ExprValueKind valueKind;
11526 QualType type;
11527 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
11528 valueKind = VK_LValue;
11529 type = Fn->getType();
11530 } else {
11531 valueKind = VK_RValue;
11532 type = Context.BoundMemberTy;
11533 }
11534
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011535 MemberExpr *ME = MemberExpr::Create(Context, Base,
11536 MemExpr->isArrow(),
11537 MemExpr->getQualifierLoc(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +000011538 MemExpr->getTemplateKeywordLoc(),
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011539 Fn,
11540 Found,
11541 MemExpr->getMemberNameInfo(),
11542 TemplateArgs,
11543 type, valueKind, OK_Ordinary);
11544 ME->setHadMultipleCandidates(true);
Richard Smith4a030222012-11-14 07:06:31 +000011545 MarkMemberReferenced(ME);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000011546 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000011547 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011548
John McCall3fa5cae2010-10-26 07:05:15 +000011549 llvm_unreachable("Invalid reference to overloaded function");
Douglas Gregor904eed32008-11-10 20:40:00 +000011550}
11551
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000011552ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000011553 DeclAccessPair Found,
11554 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000011555 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000011556}
11557
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000011558} // end namespace clang